Publish pinned IR assets 399e6147372d
Browse files- README.md +15 -0
- releases/20261004-retained-checkpoints-v1/MODEL_CARD.md +15 -0
- releases/20261004-retained-checkpoints-v1/SOURCE-LICENSE-AGPL-3.0.txt +661 -0
- releases/20261004-retained-checkpoints-v1/lane-manifest.json +710 -0
- releases/20261004-retained-checkpoints-v1/original-lane-inventory.json +193 -0
- releases/20261004-retained-checkpoints-v1/source/0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py +0 -0
- releases/20261004-retained-checkpoints-v1/source/21e8315b0054f7755512212d610d4e3f5f4ac86387f3b27edb9632fa8ca68bc3/ipfs_datasets_py/logic/ui_ux_ir/decoder.py +157 -0
- releases/20261004-retained-checkpoints-v1/source/3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py +434 -0
- releases/20261004-retained-checkpoints-v1/source/587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d/ipfs_datasets_py/logic/autoformal/tree_pin.py +55 -0
- releases/20261004-retained-checkpoints-v1/source/66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py +919 -0
- releases/20261004-retained-checkpoints-v1/source/6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py +209 -0
- releases/20261004-retained-checkpoints-v1/source/7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257/ipfs_datasets_py/logic/intent_ir/decoder.py +721 -0
- releases/20261004-retained-checkpoints-v1/source/8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855/ipfs_datasets_py/logic/ui_ux_ir/schema.py +0 -0
- releases/20261004-retained-checkpoints-v1/source/8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py +512 -0
- releases/20261004-retained-checkpoints-v1/source/93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56/ipfs_datasets_py/logic/intent_ir/schema.py +699 -0
- releases/20261004-retained-checkpoints-v1/source/abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39/ipfs_datasets_py/logic/security_ir/model.py +1017 -0
- releases/20261004-retained-checkpoints-v1/source/d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py +0 -0
- releases/20261004-retained-checkpoints-v1/source/d7be6bff3a1f1464d4783567b90942258ef718bc1c2b7e02938698ed4e619e57/ipfs_datasets_py/logic/ui_ux_ir/decoder.py +207 -0
- releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py +611 -0
- releases/20261004-retained-checkpoints-v1/source/f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91/ipfs_datasets_py/logic/software_verification/program.py +1430 -0
- releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py +313 -0
- releases/retained-checkpoints/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930/asset-manifest.json +308 -0
- releases/retained-checkpoints/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930/checkpoint.json +0 -0
- releases/retained-checkpoints/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f/asset-manifest.json +306 -0
- releases/retained-checkpoints/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f/checkpoint.json +0 -0
README.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
tags:
|
| 3 |
+
- intermediate-representation
|
| 4 |
+
- retained-checkpoint
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# codebase_ir: 384D retained assets
|
| 8 |
+
|
| 9 |
+
This lane contains 2 distinct original checkpoint variants. Each checkpoint uses a content-addressed path and an asset manifest preserving its schema, decoder role, available format/profile binding, codec, source declarations, and companion corpus or embedding assets. Unknown bindings remain unknown.
|
| 10 |
+
|
| 11 |
+
Registration and publication do not qualify numerical quality, source-only reconstruction, teacher use, proof authority, or serving. No retained checkpoint is activated for inference. The Legal 768D checkpoint is inherited initialization only; Codebase, Intent, and Security 768D lanes have no retained checkpoints. Codebase 384D envelopes retain their borrowed Security payload identity and are not promoted as complete native Codebase decoders.
|
| 12 |
+
|
| 13 |
+
See [releases/20261004-retained-checkpoints-v1/lane-manifest.json](releases/20261004-retained-checkpoints-v1/lane-manifest.json) for exact checkpoint hashes and source mappings. Matching listed implementation sources are preserved, but a complete executable closure is not asserted. Existing assets and embeddings are copied without recomputation.
|
| 14 |
+
|
| 15 |
+
Source code retains the repository AGPL-3.0 license; original weights/data licensing is preserved and no new blanket grant is made.
|
releases/20261004-retained-checkpoints-v1/MODEL_CARD.md
ADDED
|
@@ -0,0 +1,15 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
---
|
| 2 |
+
tags:
|
| 3 |
+
- intermediate-representation
|
| 4 |
+
- retained-checkpoint
|
| 5 |
+
---
|
| 6 |
+
|
| 7 |
+
# codebase_ir: 384D retained assets
|
| 8 |
+
|
| 9 |
+
This lane contains 2 distinct original checkpoint variants. Each checkpoint uses a content-addressed path and an asset manifest preserving its schema, decoder role, available format/profile binding, codec, source declarations, and companion corpus or embedding assets. Unknown bindings remain unknown.
|
| 10 |
+
|
| 11 |
+
Registration and publication do not qualify numerical quality, source-only reconstruction, teacher use, proof authority, or serving. No retained checkpoint is activated for inference. The Legal 768D checkpoint is inherited initialization only; Codebase, Intent, and Security 768D lanes have no retained checkpoints. Codebase 384D envelopes retain their borrowed Security payload identity and are not promoted as complete native Codebase decoders.
|
| 12 |
+
|
| 13 |
+
See [releases/20261004-retained-checkpoints-v1/lane-manifest.json](releases/20261004-retained-checkpoints-v1/lane-manifest.json) for exact checkpoint hashes and source mappings. Matching listed implementation sources are preserved, but a complete executable closure is not asserted. Existing assets and embeddings are copied without recomputation.
|
| 14 |
+
|
| 15 |
+
Source code retains the repository AGPL-3.0 license; original weights/data licensing is preserved and no new blanket grant is made.
|
releases/20261004-retained-checkpoints-v1/SOURCE-LICENSE-AGPL-3.0.txt
ADDED
|
@@ -0,0 +1,661 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
GNU AFFERO GENERAL PUBLIC LICENSE
|
| 2 |
+
Version 3, 19 November 2007
|
| 3 |
+
|
| 4 |
+
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
|
| 5 |
+
Everyone is permitted to copy and distribute verbatim copies
|
| 6 |
+
of this license document, but changing it is not allowed.
|
| 7 |
+
|
| 8 |
+
Preamble
|
| 9 |
+
|
| 10 |
+
The GNU Affero General Public License is a free, copyleft license for
|
| 11 |
+
software and other kinds of works, specifically designed to ensure
|
| 12 |
+
cooperation with the community in the case of network server software.
|
| 13 |
+
|
| 14 |
+
The licenses for most software and other practical works are designed
|
| 15 |
+
to take away your freedom to share and change the works. By contrast,
|
| 16 |
+
our General Public Licenses are intended to guarantee your freedom to
|
| 17 |
+
share and change all versions of a program--to make sure it remains free
|
| 18 |
+
software for all its users.
|
| 19 |
+
|
| 20 |
+
When we speak of free software, we are referring to freedom, not
|
| 21 |
+
price. Our General Public Licenses are designed to make sure that you
|
| 22 |
+
have the freedom to distribute copies of free software (and charge for
|
| 23 |
+
them if you wish), that you receive source code or can get it if you
|
| 24 |
+
want it, that you can change the software or use pieces of it in new
|
| 25 |
+
free programs, and that you know you can do these things.
|
| 26 |
+
|
| 27 |
+
Developers that use our General Public Licenses protect your rights
|
| 28 |
+
with two steps: (1) assert copyright on the software, and (2) offer
|
| 29 |
+
you this License which gives you legal permission to copy, distribute
|
| 30 |
+
and/or modify the software.
|
| 31 |
+
|
| 32 |
+
A secondary benefit of defending all users' freedom is that
|
| 33 |
+
improvements made in alternate versions of the program, if they
|
| 34 |
+
receive widespread use, become available for other developers to
|
| 35 |
+
incorporate. Many developers of free software are heartened and
|
| 36 |
+
encouraged by the resulting cooperation. However, in the case of
|
| 37 |
+
software used on network servers, this result may fail to come about.
|
| 38 |
+
The GNU General Public License permits making a modified version and
|
| 39 |
+
letting the public access it on a server without ever releasing its
|
| 40 |
+
source code to the public.
|
| 41 |
+
|
| 42 |
+
The GNU Affero General Public License is designed specifically to
|
| 43 |
+
ensure that, in such cases, the modified source code becomes available
|
| 44 |
+
to the community. It requires the operator of a network server to
|
| 45 |
+
provide the source code of the modified version running there to the
|
| 46 |
+
users of that server. Therefore, public use of a modified version, on
|
| 47 |
+
a publicly accessible server, gives the public access to the source
|
| 48 |
+
code of the modified version.
|
| 49 |
+
|
| 50 |
+
An older license, called the Affero General Public License and
|
| 51 |
+
published by Affero, was designed to accomplish similar goals. This is
|
| 52 |
+
a different license, not a version of the Affero GPL, but Affero has
|
| 53 |
+
released a new version of the Affero GPL which permits relicensing under
|
| 54 |
+
this license.
|
| 55 |
+
|
| 56 |
+
The precise terms and conditions for copying, distribution and
|
| 57 |
+
modification follow.
|
| 58 |
+
|
| 59 |
+
TERMS AND CONDITIONS
|
| 60 |
+
|
| 61 |
+
0. Definitions.
|
| 62 |
+
|
| 63 |
+
"This License" refers to version 3 of the GNU Affero General Public License.
|
| 64 |
+
|
| 65 |
+
"Copyright" also means copyright-like laws that apply to other kinds of
|
| 66 |
+
works, such as semiconductor masks.
|
| 67 |
+
|
| 68 |
+
"The Program" refers to any copyrightable work licensed under this
|
| 69 |
+
License. Each licensee is addressed as "you". "Licensees" and
|
| 70 |
+
"recipients" may be individuals or organizations.
|
| 71 |
+
|
| 72 |
+
To "modify" a work means to copy from or adapt all or part of the work
|
| 73 |
+
in a fashion requiring copyright permission, other than the making of an
|
| 74 |
+
exact copy. The resulting work is called a "modified version" of the
|
| 75 |
+
earlier work or a work "based on" the earlier work.
|
| 76 |
+
|
| 77 |
+
A "covered work" means either the unmodified Program or a work based
|
| 78 |
+
on the Program.
|
| 79 |
+
|
| 80 |
+
To "propagate" a work means to do anything with it that, without
|
| 81 |
+
permission, would make you directly or secondarily liable for
|
| 82 |
+
infringement under applicable copyright law, except executing it on a
|
| 83 |
+
computer or modifying a private copy. Propagation includes copying,
|
| 84 |
+
distribution (with or without modification), making available to the
|
| 85 |
+
public, and in some countries other activities as well.
|
| 86 |
+
|
| 87 |
+
To "convey" a work means any kind of propagation that enables other
|
| 88 |
+
parties to make or receive copies. Mere interaction with a user through
|
| 89 |
+
a computer network, with no transfer of a copy, is not conveying.
|
| 90 |
+
|
| 91 |
+
An interactive user interface displays "Appropriate Legal Notices"
|
| 92 |
+
to the extent that it includes a convenient and prominently visible
|
| 93 |
+
feature that (1) displays an appropriate copyright notice, and (2)
|
| 94 |
+
tells the user that there is no warranty for the work (except to the
|
| 95 |
+
extent that warranties are provided), that licensees may convey the
|
| 96 |
+
work under this License, and how to view a copy of this License. If
|
| 97 |
+
the interface presents a list of user commands or options, such as a
|
| 98 |
+
menu, a prominent item in the list meets this criterion.
|
| 99 |
+
|
| 100 |
+
1. Source Code.
|
| 101 |
+
|
| 102 |
+
The "source code" for a work means the preferred form of the work
|
| 103 |
+
for making modifications to it. "Object code" means any non-source
|
| 104 |
+
form of a work.
|
| 105 |
+
|
| 106 |
+
A "Standard Interface" means an interface that either is an official
|
| 107 |
+
standard defined by a recognized standards body, or, in the case of
|
| 108 |
+
interfaces specified for a particular programming language, one that
|
| 109 |
+
is widely used among developers working in that language.
|
| 110 |
+
|
| 111 |
+
The "System Libraries" of an executable work include anything, other
|
| 112 |
+
than the work as a whole, that (a) is included in the normal form of
|
| 113 |
+
packaging a Major Component, but which is not part of that Major
|
| 114 |
+
Component, and (b) serves only to enable use of the work with that
|
| 115 |
+
Major Component, or to implement a Standard Interface for which an
|
| 116 |
+
implementation is available to the public in source code form. A
|
| 117 |
+
"Major Component", in this context, means a major essential component
|
| 118 |
+
(kernel, window system, and so on) of the specific operating system
|
| 119 |
+
(if any) on which the executable work runs, or a compiler used to
|
| 120 |
+
produce the work, or an object code interpreter used to run it.
|
| 121 |
+
|
| 122 |
+
The "Corresponding Source" for a work in object code form means all
|
| 123 |
+
the source code needed to generate, install, and (for an executable
|
| 124 |
+
work) run the object code and to modify the work, including scripts to
|
| 125 |
+
control those activities. However, it does not include the work's
|
| 126 |
+
System Libraries, or general-purpose tools or generally available free
|
| 127 |
+
programs which are used unmodified in performing those activities but
|
| 128 |
+
which are not part of the work. For example, Corresponding Source
|
| 129 |
+
includes interface definition files associated with source files for
|
| 130 |
+
the work, and the source code for shared libraries and dynamically
|
| 131 |
+
linked subprograms that the work is specifically designed to require,
|
| 132 |
+
such as by intimate data communication or control flow between those
|
| 133 |
+
subprograms and other parts of the work.
|
| 134 |
+
|
| 135 |
+
The Corresponding Source need not include anything that users
|
| 136 |
+
can regenerate automatically from other parts of the Corresponding
|
| 137 |
+
Source.
|
| 138 |
+
|
| 139 |
+
The Corresponding Source for a work in source code form is that
|
| 140 |
+
same work.
|
| 141 |
+
|
| 142 |
+
2. Basic Permissions.
|
| 143 |
+
|
| 144 |
+
All rights granted under this License are granted for the term of
|
| 145 |
+
copyright on the Program, and are irrevocable provided the stated
|
| 146 |
+
conditions are met. This License explicitly affirms your unlimited
|
| 147 |
+
permission to run the unmodified Program. The output from running a
|
| 148 |
+
covered work is covered by this License only if the output, given its
|
| 149 |
+
content, constitutes a covered work. This License acknowledges your
|
| 150 |
+
rights of fair use or other equivalent, as provided by copyright law.
|
| 151 |
+
|
| 152 |
+
You may make, run and propagate covered works that you do not
|
| 153 |
+
convey, without conditions so long as your license otherwise remains
|
| 154 |
+
in force. You may convey covered works to others for the sole purpose
|
| 155 |
+
of having them make modifications exclusively for you, or provide you
|
| 156 |
+
with facilities for running those works, provided that you comply with
|
| 157 |
+
the terms of this License in conveying all material for which you do
|
| 158 |
+
not control copyright. Those thus making or running the covered works
|
| 159 |
+
for you must do so exclusively on your behalf, under your direction
|
| 160 |
+
and control, on terms that prohibit them from making any copies of
|
| 161 |
+
your copyrighted material outside their relationship with you.
|
| 162 |
+
|
| 163 |
+
Conveying under any other circumstances is permitted solely under
|
| 164 |
+
the conditions stated below. Sublicensing is not allowed; section 10
|
| 165 |
+
makes it unnecessary.
|
| 166 |
+
|
| 167 |
+
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
| 168 |
+
|
| 169 |
+
No covered work shall be deemed part of an effective technological
|
| 170 |
+
measure under any applicable law fulfilling obligations under article
|
| 171 |
+
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
| 172 |
+
similar laws prohibiting or restricting circumvention of such
|
| 173 |
+
measures.
|
| 174 |
+
|
| 175 |
+
When you convey a covered work, you waive any legal power to forbid
|
| 176 |
+
circumvention of technological measures to the extent such circumvention
|
| 177 |
+
is effected by exercising rights under this License with respect to
|
| 178 |
+
the covered work, and you disclaim any intention to limit operation or
|
| 179 |
+
modification of the work as a means of enforcing, against the work's
|
| 180 |
+
users, your or third parties' legal rights to forbid circumvention of
|
| 181 |
+
technological measures.
|
| 182 |
+
|
| 183 |
+
4. Conveying Verbatim Copies.
|
| 184 |
+
|
| 185 |
+
You may convey verbatim copies of the Program's source code as you
|
| 186 |
+
receive it, in any medium, provided that you conspicuously and
|
| 187 |
+
appropriately publish on each copy an appropriate copyright notice;
|
| 188 |
+
keep intact all notices stating that this License and any
|
| 189 |
+
non-permissive terms added in accord with section 7 apply to the code;
|
| 190 |
+
keep intact all notices of the absence of any warranty; and give all
|
| 191 |
+
recipients a copy of this License along with the Program.
|
| 192 |
+
|
| 193 |
+
You may charge any price or no price for each copy that you convey,
|
| 194 |
+
and you may offer support or warranty protection for a fee.
|
| 195 |
+
|
| 196 |
+
5. Conveying Modified Source Versions.
|
| 197 |
+
|
| 198 |
+
You may convey a work based on the Program, or the modifications to
|
| 199 |
+
produce it from the Program, in the form of source code under the
|
| 200 |
+
terms of section 4, provided that you also meet all of these conditions:
|
| 201 |
+
|
| 202 |
+
a) The work must carry prominent notices stating that you modified
|
| 203 |
+
it, and giving a relevant date.
|
| 204 |
+
|
| 205 |
+
b) The work must carry prominent notices stating that it is
|
| 206 |
+
released under this License and any conditions added under section
|
| 207 |
+
7. This requirement modifies the requirement in section 4 to
|
| 208 |
+
"keep intact all notices".
|
| 209 |
+
|
| 210 |
+
c) You must license the entire work, as a whole, under this
|
| 211 |
+
License to anyone who comes into possession of a copy. This
|
| 212 |
+
License will therefore apply, along with any applicable section 7
|
| 213 |
+
additional terms, to the whole of the work, and all its parts,
|
| 214 |
+
regardless of how they are packaged. This License gives no
|
| 215 |
+
permission to license the work in any other way, but it does not
|
| 216 |
+
invalidate such permission if you have separately received it.
|
| 217 |
+
|
| 218 |
+
d) If the work has interactive user interfaces, each must display
|
| 219 |
+
Appropriate Legal Notices; however, if the Program has interactive
|
| 220 |
+
interfaces that do not display Appropriate Legal Notices, your
|
| 221 |
+
work need not make them do so.
|
| 222 |
+
|
| 223 |
+
A compilation of a covered work with other separate and independent
|
| 224 |
+
works, which are not by their nature extensions of the covered work,
|
| 225 |
+
and which are not combined with it such as to form a larger program,
|
| 226 |
+
in or on a volume of a storage or distribution medium, is called an
|
| 227 |
+
"aggregate" if the compilation and its resulting copyright are not
|
| 228 |
+
used to limit the access or legal rights of the compilation's users
|
| 229 |
+
beyond what the individual works permit. Inclusion of a covered work
|
| 230 |
+
in an aggregate does not cause this License to apply to the other
|
| 231 |
+
parts of the aggregate.
|
| 232 |
+
|
| 233 |
+
6. Conveying Non-Source Forms.
|
| 234 |
+
|
| 235 |
+
You may convey a covered work in object code form under the terms
|
| 236 |
+
of sections 4 and 5, provided that you also convey the
|
| 237 |
+
machine-readable Corresponding Source under the terms of this License,
|
| 238 |
+
in one of these ways:
|
| 239 |
+
|
| 240 |
+
a) Convey the object code in, or embodied in, a physical product
|
| 241 |
+
(including a physical distribution medium), accompanied by the
|
| 242 |
+
Corresponding Source fixed on a durable physical medium
|
| 243 |
+
customarily used for software interchange.
|
| 244 |
+
|
| 245 |
+
b) Convey the object code in, or embodied in, a physical product
|
| 246 |
+
(including a physical distribution medium), accompanied by a
|
| 247 |
+
written offer, valid for at least three years and valid for as
|
| 248 |
+
long as you offer spare parts or customer support for that product
|
| 249 |
+
model, to give anyone who possesses the object code either (1) a
|
| 250 |
+
copy of the Corresponding Source for all the software in the
|
| 251 |
+
product that is covered by this License, on a durable physical
|
| 252 |
+
medium customarily used for software interchange, for a price no
|
| 253 |
+
more than your reasonable cost of physically performing this
|
| 254 |
+
conveying of source, or (2) access to copy the
|
| 255 |
+
Corresponding Source from a network server at no charge.
|
| 256 |
+
|
| 257 |
+
c) Convey individual copies of the object code with a copy of the
|
| 258 |
+
written offer to provide the Corresponding Source. This
|
| 259 |
+
alternative is allowed only occasionally and noncommercially, and
|
| 260 |
+
only if you received the object code with such an offer, in accord
|
| 261 |
+
with subsection 6b.
|
| 262 |
+
|
| 263 |
+
d) Convey the object code by offering access from a designated
|
| 264 |
+
place (gratis or for a charge), and offer equivalent access to the
|
| 265 |
+
Corresponding Source in the same way through the same place at no
|
| 266 |
+
further charge. You need not require recipients to copy the
|
| 267 |
+
Corresponding Source along with the object code. If the place to
|
| 268 |
+
copy the object code is a network server, the Corresponding Source
|
| 269 |
+
may be on a different server (operated by you or a third party)
|
| 270 |
+
that supports equivalent copying facilities, provided you maintain
|
| 271 |
+
clear directions next to the object code saying where to find the
|
| 272 |
+
Corresponding Source. Regardless of what server hosts the
|
| 273 |
+
Corresponding Source, you remain obligated to ensure that it is
|
| 274 |
+
available for as long as needed to satisfy these requirements.
|
| 275 |
+
|
| 276 |
+
e) Convey the object code using peer-to-peer transmission, provided
|
| 277 |
+
you inform other peers where the object code and Corresponding
|
| 278 |
+
Source of the work are being offered to the general public at no
|
| 279 |
+
charge under subsection 6d.
|
| 280 |
+
|
| 281 |
+
A separable portion of the object code, whose source code is excluded
|
| 282 |
+
from the Corresponding Source as a System Library, need not be
|
| 283 |
+
included in conveying the object code work.
|
| 284 |
+
|
| 285 |
+
A "User Product" is either (1) a "consumer product", which means any
|
| 286 |
+
tangible personal property which is normally used for personal, family,
|
| 287 |
+
or household purposes, or (2) anything designed or sold for incorporation
|
| 288 |
+
into a dwelling. In determining whether a product is a consumer product,
|
| 289 |
+
doubtful cases shall be resolved in favor of coverage. For a particular
|
| 290 |
+
product received by a particular user, "normally used" refers to a
|
| 291 |
+
typical or common use of that class of product, regardless of the status
|
| 292 |
+
of the particular user or of the way in which the particular user
|
| 293 |
+
actually uses, or expects or is expected to use, the product. A product
|
| 294 |
+
is a consumer product regardless of whether the product has substantial
|
| 295 |
+
commercial, industrial or non-consumer uses, unless such uses represent
|
| 296 |
+
the only significant mode of use of the product.
|
| 297 |
+
|
| 298 |
+
"Installation Information" for a User Product means any methods,
|
| 299 |
+
procedures, authorization keys, or other information required to install
|
| 300 |
+
and execute modified versions of a covered work in that User Product from
|
| 301 |
+
a modified version of its Corresponding Source. The information must
|
| 302 |
+
suffice to ensure that the continued functioning of the modified object
|
| 303 |
+
code is in no case prevented or interfered with solely because
|
| 304 |
+
modification has been made.
|
| 305 |
+
|
| 306 |
+
If you convey an object code work under this section in, or with, or
|
| 307 |
+
specifically for use in, a User Product, and the conveying occurs as
|
| 308 |
+
part of a transaction in which the right of possession and use of the
|
| 309 |
+
User Product is transferred to the recipient in perpetuity or for a
|
| 310 |
+
fixed term (regardless of how the transaction is characterized), the
|
| 311 |
+
Corresponding Source conveyed under this section must be accompanied
|
| 312 |
+
by the Installation Information. But this requirement does not apply
|
| 313 |
+
if neither you nor any third party retains the ability to install
|
| 314 |
+
modified object code on the User Product (for example, the work has
|
| 315 |
+
been installed in ROM).
|
| 316 |
+
|
| 317 |
+
The requirement to provide Installation Information does not include a
|
| 318 |
+
requirement to continue to provide support service, warranty, or updates
|
| 319 |
+
for a work that has been modified or installed by the recipient, or for
|
| 320 |
+
the User Product in which it has been modified or installed. Access to a
|
| 321 |
+
network may be denied when the modification itself materially and
|
| 322 |
+
adversely affects the operation of the network or violates the rules and
|
| 323 |
+
protocols for communication across the network.
|
| 324 |
+
|
| 325 |
+
Corresponding Source conveyed, and Installation Information provided,
|
| 326 |
+
in accord with this section must be in a format that is publicly
|
| 327 |
+
documented (and with an implementation available to the public in
|
| 328 |
+
source code form), and must require no special password or key for
|
| 329 |
+
unpacking, reading or copying.
|
| 330 |
+
|
| 331 |
+
7. Additional Terms.
|
| 332 |
+
|
| 333 |
+
"Additional permissions" are terms that supplement the terms of this
|
| 334 |
+
License by making exceptions from one or more of its conditions.
|
| 335 |
+
Additional permissions that are applicable to the entire Program shall
|
| 336 |
+
be treated as though they were included in this License, to the extent
|
| 337 |
+
that they are valid under applicable law. If additional permissions
|
| 338 |
+
apply only to part of the Program, that part may be used separately
|
| 339 |
+
under those permissions, but the entire Program remains governed by
|
| 340 |
+
this License without regard to the additional permissions.
|
| 341 |
+
|
| 342 |
+
When you convey a copy of a covered work, you may at your option
|
| 343 |
+
remove any additional permissions from that copy, or from any part of
|
| 344 |
+
it. (Additional permissions may be written to require their own
|
| 345 |
+
removal in certain cases when you modify the work.) You may place
|
| 346 |
+
additional permissions on material, added by you to a covered work,
|
| 347 |
+
for which you have or can give appropriate copyright permission.
|
| 348 |
+
|
| 349 |
+
Notwithstanding any other provision of this License, for material you
|
| 350 |
+
add to a covered work, you may (if authorized by the copyright holders of
|
| 351 |
+
that material) supplement the terms of this License with terms:
|
| 352 |
+
|
| 353 |
+
a) Disclaiming warranty or limiting liability differently from the
|
| 354 |
+
terms of sections 15 and 16 of this License; or
|
| 355 |
+
|
| 356 |
+
b) Requiring preservation of specified reasonable legal notices or
|
| 357 |
+
author attributions in that material or in the Appropriate Legal
|
| 358 |
+
Notices displayed by works containing it; or
|
| 359 |
+
|
| 360 |
+
c) Prohibiting misrepresentation of the origin of that material, or
|
| 361 |
+
requiring that modified versions of such material be marked in
|
| 362 |
+
reasonable ways as different from the original version; or
|
| 363 |
+
|
| 364 |
+
d) Limiting the use for publicity purposes of names of licensors or
|
| 365 |
+
authors of the material; or
|
| 366 |
+
|
| 367 |
+
e) Declining to grant rights under trademark law for use of some
|
| 368 |
+
trade names, trademarks, or service marks; or
|
| 369 |
+
|
| 370 |
+
f) Requiring indemnification of licensors and authors of that
|
| 371 |
+
material by anyone who conveys the material (or modified versions of
|
| 372 |
+
it) with contractual assumptions of liability to the recipient, for
|
| 373 |
+
any liability that these contractual assumptions directly impose on
|
| 374 |
+
those licensors and authors.
|
| 375 |
+
|
| 376 |
+
All other non-permissive additional terms are considered "further
|
| 377 |
+
restrictions" within the meaning of section 10. If the Program as you
|
| 378 |
+
received it, or any part of it, contains a notice stating that it is
|
| 379 |
+
governed by this License along with a term that is a further
|
| 380 |
+
restriction, you may remove that term. If a license document contains
|
| 381 |
+
a further restriction but permits relicensing or conveying under this
|
| 382 |
+
License, you may add to a covered work material governed by the terms
|
| 383 |
+
of that license document, provided that the further restriction does
|
| 384 |
+
not survive such relicensing or conveying.
|
| 385 |
+
|
| 386 |
+
If you add terms to a covered work in accord with this section, you
|
| 387 |
+
must place, in the relevant source files, a statement of the
|
| 388 |
+
additional terms that apply to those files, or a notice indicating
|
| 389 |
+
where to find the applicable terms.
|
| 390 |
+
|
| 391 |
+
Additional terms, permissive or non-permissive, may be stated in the
|
| 392 |
+
form of a separately written license, or stated as exceptions;
|
| 393 |
+
the above requirements apply either way.
|
| 394 |
+
|
| 395 |
+
8. Termination.
|
| 396 |
+
|
| 397 |
+
You may not propagate or modify a covered work except as expressly
|
| 398 |
+
provided under this License. Any attempt otherwise to propagate or
|
| 399 |
+
modify it is void, and will automatically terminate your rights under
|
| 400 |
+
this License (including any patent licenses granted under the third
|
| 401 |
+
paragraph of section 11).
|
| 402 |
+
|
| 403 |
+
However, if you cease all violation of this License, then your
|
| 404 |
+
license from a particular copyright holder is reinstated (a)
|
| 405 |
+
provisionally, unless and until the copyright holder explicitly and
|
| 406 |
+
finally terminates your license, and (b) permanently, if the copyright
|
| 407 |
+
holder fails to notify you of the violation by some reasonable means
|
| 408 |
+
prior to 60 days after the cessation.
|
| 409 |
+
|
| 410 |
+
Moreover, your license from a particular copyright holder is
|
| 411 |
+
reinstated permanently if the copyright holder notifies you of the
|
| 412 |
+
violation by some reasonable means, this is the first time you have
|
| 413 |
+
received notice of violation of this License (for any work) from that
|
| 414 |
+
copyright holder, and you cure the violation prior to 30 days after
|
| 415 |
+
your receipt of the notice.
|
| 416 |
+
|
| 417 |
+
Termination of your rights under this section does not terminate the
|
| 418 |
+
licenses of parties who have received copies or rights from you under
|
| 419 |
+
this License. If your rights have been terminated and not permanently
|
| 420 |
+
reinstated, you do not qualify to receive new licenses for the same
|
| 421 |
+
material under section 10.
|
| 422 |
+
|
| 423 |
+
9. Acceptance Not Required for Having Copies.
|
| 424 |
+
|
| 425 |
+
You are not required to accept this License in order to receive or
|
| 426 |
+
run a copy of the Program. Ancillary propagation of a covered work
|
| 427 |
+
occurring solely as a consequence of using peer-to-peer transmission
|
| 428 |
+
to receive a copy likewise does not require acceptance. However,
|
| 429 |
+
nothing other than this License grants you permission to propagate or
|
| 430 |
+
modify any covered work. These actions infringe copyright if you do
|
| 431 |
+
not accept this License. Therefore, by modifying or propagating a
|
| 432 |
+
covered work, you indicate your acceptance of this License to do so.
|
| 433 |
+
|
| 434 |
+
10. Automatic Licensing of Downstream Recipients.
|
| 435 |
+
|
| 436 |
+
Each time you convey a covered work, the recipient automatically
|
| 437 |
+
receives a license from the original licensors, to run, modify and
|
| 438 |
+
propagate that work, subject to this License. You are not responsible
|
| 439 |
+
for enforcing compliance by third parties with this License.
|
| 440 |
+
|
| 441 |
+
An "entity transaction" is a transaction transferring control of an
|
| 442 |
+
organization, or substantially all assets of one, or subdividing an
|
| 443 |
+
organization, or merging organizations. If propagation of a covered
|
| 444 |
+
work results from an entity transaction, each party to that
|
| 445 |
+
transaction who receives a copy of the work also receives whatever
|
| 446 |
+
licenses to the work the party's predecessor in interest had or could
|
| 447 |
+
give under the previous paragraph, plus a right to possession of the
|
| 448 |
+
Corresponding Source of the work from the predecessor in interest, if
|
| 449 |
+
the predecessor has it or can get it with reasonable efforts.
|
| 450 |
+
|
| 451 |
+
You may not impose any further restrictions on the exercise of the
|
| 452 |
+
rights granted or affirmed under this License. For example, you may
|
| 453 |
+
not impose a license fee, royalty, or other charge for exercise of
|
| 454 |
+
rights granted under this License, and you may not initiate litigation
|
| 455 |
+
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
| 456 |
+
any patent claim is infringed by making, using, selling, offering for
|
| 457 |
+
sale, or importing the Program or any portion of it.
|
| 458 |
+
|
| 459 |
+
11. Patents.
|
| 460 |
+
|
| 461 |
+
A "contributor" is a copyright holder who authorizes use under this
|
| 462 |
+
License of the Program or a work on which the Program is based. The
|
| 463 |
+
work thus licensed is called the contributor's "contributor version".
|
| 464 |
+
|
| 465 |
+
A contributor's "essential patent claims" are all patent claims
|
| 466 |
+
owned or controlled by the contributor, whether already acquired or
|
| 467 |
+
hereafter acquired, that would be infringed by some manner, permitted
|
| 468 |
+
by this License, of making, using, or selling its contributor version,
|
| 469 |
+
but do not include claims that would be infringed only as a
|
| 470 |
+
consequence of further modification of the contributor version. For
|
| 471 |
+
purposes of this definition, "control" includes the right to grant
|
| 472 |
+
patent sublicenses in a manner consistent with the requirements of
|
| 473 |
+
this License.
|
| 474 |
+
|
| 475 |
+
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
| 476 |
+
patent license under the contributor's essential patent claims, to
|
| 477 |
+
make, use, sell, offer for sale, import and otherwise run, modify and
|
| 478 |
+
propagate the contents of its contributor version.
|
| 479 |
+
|
| 480 |
+
In the following three paragraphs, a "patent license" is any express
|
| 481 |
+
agreement or commitment, however denominated, not to enforce a patent
|
| 482 |
+
(such as an express permission to practice a patent or covenant not to
|
| 483 |
+
sue for patent infringement). To "grant" such a patent license to a
|
| 484 |
+
party means to make such an agreement or commitment not to enforce a
|
| 485 |
+
patent against the party.
|
| 486 |
+
|
| 487 |
+
If you convey a covered work, knowingly relying on a patent license,
|
| 488 |
+
and the Corresponding Source of the work is not available for anyone
|
| 489 |
+
to copy, free of charge and under the terms of this License, through a
|
| 490 |
+
publicly available network server or other readily accessible means,
|
| 491 |
+
then you must either (1) cause the Corresponding Source to be so
|
| 492 |
+
available, or (2) arrange to deprive yourself of the benefit of the
|
| 493 |
+
patent license for this particular work, or (3) arrange, in a manner
|
| 494 |
+
consistent with the requirements of this License, to extend the patent
|
| 495 |
+
license to downstream recipients. "Knowingly relying" means you have
|
| 496 |
+
actual knowledge that, but for the patent license, your conveying the
|
| 497 |
+
covered work in a country, or your recipient's use of the covered work
|
| 498 |
+
in a country, would infringe one or more identifiable patents in that
|
| 499 |
+
country that you have reason to believe are valid.
|
| 500 |
+
|
| 501 |
+
If, pursuant to or in connection with a single transaction or
|
| 502 |
+
arrangement, you convey, or propagate by procuring conveyance of, a
|
| 503 |
+
covered work, and grant a patent license to some of the parties
|
| 504 |
+
receiving the covered work authorizing them to use, propagate, modify
|
| 505 |
+
or convey a specific copy of the covered work, then the patent license
|
| 506 |
+
you grant is automatically extended to all recipients of the covered
|
| 507 |
+
work and works based on it.
|
| 508 |
+
|
| 509 |
+
A patent license is "discriminatory" if it does not include within
|
| 510 |
+
the scope of its coverage, prohibits the exercise of, or is
|
| 511 |
+
conditioned on the non-exercise of one or more of the rights that are
|
| 512 |
+
specifically granted under this License. You may not convey a covered
|
| 513 |
+
work if you are a party to an arrangement with a third party that is
|
| 514 |
+
in the business of distributing software, under which you make payment
|
| 515 |
+
to the third party based on the extent of your activity of conveying
|
| 516 |
+
the work, and under which the third party grants, to any of the
|
| 517 |
+
parties who would receive the covered work from you, a discriminatory
|
| 518 |
+
patent license (a) in connection with copies of the covered work
|
| 519 |
+
conveyed by you (or copies made from those copies), or (b) primarily
|
| 520 |
+
for and in connection with specific products or compilations that
|
| 521 |
+
contain the covered work, unless you entered into that arrangement,
|
| 522 |
+
or that patent license was granted, prior to 28 March 2007.
|
| 523 |
+
|
| 524 |
+
Nothing in this License shall be construed as excluding or limiting
|
| 525 |
+
any implied license or other defenses to infringement that may
|
| 526 |
+
otherwise be available to you under applicable patent law.
|
| 527 |
+
|
| 528 |
+
12. No Surrender of Others' Freedom.
|
| 529 |
+
|
| 530 |
+
If conditions are imposed on you (whether by court order, agreement or
|
| 531 |
+
otherwise) that contradict the conditions of this License, they do not
|
| 532 |
+
excuse you from the conditions of this License. If you cannot convey a
|
| 533 |
+
covered work so as to satisfy simultaneously your obligations under this
|
| 534 |
+
License and any other pertinent obligations, then as a consequence you may
|
| 535 |
+
not convey it at all. For example, if you agree to terms that obligate you
|
| 536 |
+
to collect a royalty for further conveying from those to whom you convey
|
| 537 |
+
the Program, the only way you could satisfy both those terms and this
|
| 538 |
+
License would be to refrain entirely from conveying the Program.
|
| 539 |
+
|
| 540 |
+
13. Remote Network Interaction; Use with the GNU General Public License.
|
| 541 |
+
|
| 542 |
+
Notwithstanding any other provision of this License, if you modify the
|
| 543 |
+
Program, your modified version must prominently offer all users
|
| 544 |
+
interacting with it remotely through a computer network (if your version
|
| 545 |
+
supports such interaction) an opportunity to receive the Corresponding
|
| 546 |
+
Source of your version by providing access to the Corresponding Source
|
| 547 |
+
from a network server at no charge, through some standard or customary
|
| 548 |
+
means of facilitating copying of software. This Corresponding Source
|
| 549 |
+
shall include the Corresponding Source for any work covered by version 3
|
| 550 |
+
of the GNU General Public License that is incorporated pursuant to the
|
| 551 |
+
following paragraph.
|
| 552 |
+
|
| 553 |
+
Notwithstanding any other provision of this License, you have
|
| 554 |
+
permission to link or combine any covered work with a work licensed
|
| 555 |
+
under version 3 of the GNU General Public License into a single
|
| 556 |
+
combined work, and to convey the resulting work. The terms of this
|
| 557 |
+
License will continue to apply to the part which is the covered work,
|
| 558 |
+
but the work with which it is combined will remain governed by version
|
| 559 |
+
3 of the GNU General Public License.
|
| 560 |
+
|
| 561 |
+
14. Revised Versions of this License.
|
| 562 |
+
|
| 563 |
+
The Free Software Foundation may publish revised and/or new versions of
|
| 564 |
+
the GNU Affero General Public License from time to time. Such new versions
|
| 565 |
+
will be similar in spirit to the present version, but may differ in detail to
|
| 566 |
+
address new problems or concerns.
|
| 567 |
+
|
| 568 |
+
Each version is given a distinguishing version number. If the
|
| 569 |
+
Program specifies that a certain numbered version of the GNU Affero General
|
| 570 |
+
Public License "or any later version" applies to it, you have the
|
| 571 |
+
option of following the terms and conditions either of that numbered
|
| 572 |
+
version or of any later version published by the Free Software
|
| 573 |
+
Foundation. If the Program does not specify a version number of the
|
| 574 |
+
GNU Affero General Public License, you may choose any version ever published
|
| 575 |
+
by the Free Software Foundation.
|
| 576 |
+
|
| 577 |
+
If the Program specifies that a proxy can decide which future
|
| 578 |
+
versions of the GNU Affero General Public License can be used, that proxy's
|
| 579 |
+
public statement of acceptance of a version permanently authorizes you
|
| 580 |
+
to choose that version for the Program.
|
| 581 |
+
|
| 582 |
+
Later license versions may give you additional or different
|
| 583 |
+
permissions. However, no additional obligations are imposed on any
|
| 584 |
+
author or copyright holder as a result of your choosing to follow a
|
| 585 |
+
later version.
|
| 586 |
+
|
| 587 |
+
15. Disclaimer of Warranty.
|
| 588 |
+
|
| 589 |
+
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
| 590 |
+
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
| 591 |
+
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
| 592 |
+
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
| 593 |
+
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
| 594 |
+
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
| 595 |
+
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
| 596 |
+
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
| 597 |
+
|
| 598 |
+
16. Limitation of Liability.
|
| 599 |
+
|
| 600 |
+
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
| 601 |
+
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
| 602 |
+
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
| 603 |
+
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
| 604 |
+
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
| 605 |
+
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
| 606 |
+
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
| 607 |
+
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
| 608 |
+
SUCH DAMAGES.
|
| 609 |
+
|
| 610 |
+
17. Interpretation of Sections 15 and 16.
|
| 611 |
+
|
| 612 |
+
If the disclaimer of warranty and limitation of liability provided
|
| 613 |
+
above cannot be given local legal effect according to their terms,
|
| 614 |
+
reviewing courts shall apply local law that most closely approximates
|
| 615 |
+
an absolute waiver of all civil liability in connection with the
|
| 616 |
+
Program, unless a warranty or assumption of liability accompanies a
|
| 617 |
+
copy of the Program in return for a fee.
|
| 618 |
+
|
| 619 |
+
END OF TERMS AND CONDITIONS
|
| 620 |
+
|
| 621 |
+
How to Apply These Terms to Your New Programs
|
| 622 |
+
|
| 623 |
+
If you develop a new program, and you want it to be of the greatest
|
| 624 |
+
possible use to the public, the best way to achieve this is to make it
|
| 625 |
+
free software which everyone can redistribute and change under these terms.
|
| 626 |
+
|
| 627 |
+
To do so, attach the following notices to the program. It is safest
|
| 628 |
+
to attach them to the start of each source file to most effectively
|
| 629 |
+
state the exclusion of warranty; and each file should have at least
|
| 630 |
+
the "copyright" line and a pointer to where the full notice is found.
|
| 631 |
+
|
| 632 |
+
<one line to give the program's name and a brief idea of what it does.>
|
| 633 |
+
Copyright (C) <year> <name of author>
|
| 634 |
+
|
| 635 |
+
This program is free software: you can redistribute it and/or modify
|
| 636 |
+
it under the terms of the GNU Affero General Public License as published
|
| 637 |
+
by the Free Software Foundation, either version 3 of the License, or
|
| 638 |
+
(at your option) any later version.
|
| 639 |
+
|
| 640 |
+
This program is distributed in the hope that it will be useful,
|
| 641 |
+
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
| 642 |
+
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
| 643 |
+
GNU Affero General Public License for more details.
|
| 644 |
+
|
| 645 |
+
You should have received a copy of the GNU Affero General Public License
|
| 646 |
+
along with this program. If not, see <https://www.gnu.org/licenses/>.
|
| 647 |
+
|
| 648 |
+
Also add information on how to contact you by electronic and paper mail.
|
| 649 |
+
|
| 650 |
+
If your software can interact with users remotely through a computer
|
| 651 |
+
network, you should also make sure that it provides a way for users to
|
| 652 |
+
get its source. For example, if your program is a web application, its
|
| 653 |
+
interface could display a "Source" link that leads users to an archive
|
| 654 |
+
of the code. There are many ways you could offer source, and different
|
| 655 |
+
solutions will be better for different programs; see section 13 for the
|
| 656 |
+
specific requirements.
|
| 657 |
+
|
| 658 |
+
You should also get your employer (if you work as a programmer) or school,
|
| 659 |
+
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
| 660 |
+
For more information on this, and how to apply and follow the GNU AGPL, see
|
| 661 |
+
<https://www.gnu.org/licenses/>.
|
releases/20261004-retained-checkpoints-v1/lane-manif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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"authority": "Original byte identities and recorded provenance only.",
|
| 3 |
+
"checkpoints": [
|
| 4 |
+
{
|
| 5 |
+
"checkpoint": {
|
| 6 |
+
"bytes": 1009515,
|
| 7 |
+
"path_in_repo": "releases/retained-checkpoints/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f/checkpoint.json",
|
| 8 |
+
"sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
|
| 9 |
+
},
|
| 10 |
+
"codec": null,
|
| 11 |
+
"companion_assets": [],
|
| 12 |
+
"config": {
|
| 13 |
+
"embedding_provenance": {
|
| 14 |
+
"assets": [
|
| 15 |
+
{
|
| 16 |
+
"bytes": 190,
|
| 17 |
+
"name": "1_Pooling/config.json",
|
| 18 |
+
"sha256": "4be450dde3b0273bb9787637cfbd28fe04a7ba6ab9d36ac48e92b11e350ffc23"
|
| 19 |
+
},
|
| 20 |
+
{
|
| 21 |
+
"bytes": 583,
|
| 22 |
+
"name": "config.json",
|
| 23 |
+
"sha256": "00273cdfb3e05c7304d180270bdef8adae45023e7bdfc396338bdd815943dc59"
|
| 24 |
+
},
|
| 25 |
+
{
|
| 26 |
+
"bytes": 66746168,
|
| 27 |
+
"name": "model.safetensors",
|
| 28 |
+
"sha256": "9a1eb90bbac323ea08aa5629b624fe6ae75db121b904799c2266a1e2c2de22d2"
|
| 29 |
+
},
|
| 30 |
+
{
|
| 31 |
+
"bytes": 385,
|
| 32 |
+
"name": "modules.json",
|
| 33 |
+
"sha256": "73348a3d8f8ae4cc5f851dc6b98be3ea819390b814e83656d5eebbadf75fe43e"
|
| 34 |
+
},
|
| 35 |
+
{
|
| 36 |
+
"bytes": 57,
|
| 37 |
+
"name": "sentence_bert_config.json",
|
| 38 |
+
"sha256": "948201d8329907aae938fa62f9ceeed53f5694dacc2b87b9f3b78b37ee986529"
|
| 39 |
+
},
|
| 40 |
+
{
|
| 41 |
+
"bytes": 125,
|
| 42 |
+
"name": "special_tokens_map.json",
|
| 43 |
+
"sha256": "b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3"
|
| 44 |
+
},
|
| 45 |
+
{
|
| 46 |
+
"bytes": 711661,
|
| 47 |
+
"name": "tokenizer.json",
|
| 48 |
+
"sha256": "da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0"
|
| 49 |
+
},
|
| 50 |
+
{
|
| 51 |
+
"bytes": 394,
|
| 52 |
+
"name": "tokenizer_config.json",
|
| 53 |
+
"sha256": "e1790949631401af1bfb6c9c7aeec7fcf612e274d73579d99f704faea40c8ba7"
|
| 54 |
+
},
|
| 55 |
+
{
|
| 56 |
+
"bytes": 231508,
|
| 57 |
+
"name": "vocab.txt",
|
| 58 |
+
"sha256": "07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3"
|
| 59 |
+
}
|
| 60 |
+
],
|
| 61 |
+
"batch_size": 32,
|
| 62 |
+
"device": "cuda",
|
| 63 |
+
"dimension": 384,
|
| 64 |
+
"dtype": "float32",
|
| 65 |
+
"encode_rows_per_second": 2155.864994796075,
|
| 66 |
+
"encode_seconds": 0.890593800926581,
|
| 67 |
+
"load_seconds": 0.6136547059286386,
|
| 68 |
+
"max_tokens_observed": 34,
|
| 69 |
+
"model_id": "thenlper/gte-small",
|
| 70 |
+
"normalized": true,
|
| 71 |
+
"revision": "17e1f347d17fe144873b1201da91788898c639cd",
|
| 72 |
+
"rows": 1920,
|
| 73 |
+
"truncated": false
|
| 74 |
+
},
|
| 75 |
+
"ridges": [
|
| 76 |
+
0.0001,
|
| 77 |
+
0.001,
|
| 78 |
+
0.01,
|
| 79 |
+
0.1
|
| 80 |
+
]
|
| 81 |
+
},
|
| 82 |
+
"contract": null,
|
| 83 |
+
"declaration": {
|
| 84 |
+
"decoder_kind": "frozen projection and fixed-tree ridge readout",
|
| 85 |
+
"dimension_role": "input_embedding",
|
| 86 |
+
"input_width": 384,
|
| 87 |
+
"native_codebase_decoder_complete": false,
|
| 88 |
+
"owning_ir_family": "codebase_ir",
|
| 89 |
+
"payload_ir_family": "security_ir",
|
| 90 |
+
"receipt": {
|
| 91 |
+
"bytes": 1009515,
|
| 92 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/cc/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f",
|
| 93 |
+
"sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
|
| 94 |
+
},
|
| 95 |
+
"role": "registered shared parent envelope"
|
| 96 |
+
},
|
| 97 |
+
"full_runtime_closure_verified": false,
|
| 98 |
+
"identity": {
|
| 99 |
+
"checkpoint_schema": "codebase-source-384-generation@1",
|
| 100 |
+
"dimension": 384,
|
| 101 |
+
"dimension_role": "input_embedding",
|
| 102 |
+
"donor": null,
|
| 103 |
+
"donor_pins": null,
|
| 104 |
+
"embedded_decoder_schema": "structured-source-384-autoencoder/v1",
|
| 105 |
+
"format_id": null,
|
| 106 |
+
"initialization_only": false,
|
| 107 |
+
"ir_family_id": "codebase_ir",
|
| 108 |
+
"legacy_profile": "codebase_ir/source_conditioned_384_v1",
|
| 109 |
+
"native_codebase_decoder_complete": false,
|
| 110 |
+
"original_checkpoint_pin": {
|
| 111 |
+
"bytes": 1009515,
|
| 112 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/cc/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f",
|
| 113 |
+
"sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
|
| 114 |
+
},
|
| 115 |
+
"payload_ir_family": "security_ir",
|
| 116 |
+
"profile_id": null,
|
| 117 |
+
"proof_authority": false,
|
| 118 |
+
"record_id": "ir-model-asset-binding/v1:40237a9b6a4dd5723f36fcd80a37ba4d4cadb59067bc2de399c72ea9f96a99d2",
|
| 119 |
+
"retained_status": "borrowed_security_payload_unpromoted",
|
| 120 |
+
"role": "registered shared parent envelope",
|
| 121 |
+
"runtime_ready": false,
|
| 122 |
+
"schema_version": null,
|
| 123 |
+
"source_profile_id": null,
|
| 124 |
+
"task_id": null,
|
| 125 |
+
"teacher_qualified": false,
|
| 126 |
+
"trained": null
|
| 127 |
+
},
|
| 128 |
+
"license_scope": {
|
| 129 |
+
"repository_source": "AGPL-3.0, see SOURCE-LICENSE",
|
| 130 |
+
"weights_and_companions": "Original provenance retained; this release supplies no new blanket license grant."
|
| 131 |
+
},
|
| 132 |
+
"numerical_execution_performed": false,
|
| 133 |
+
"original_package": null,
|
| 134 |
+
"schema": "retained-ir-checkpoint-release/v1",
|
| 135 |
+
"source_binding_scope": "listed checkpoint implementation hashes only, not full import/native closure",
|
| 136 |
+
"source_map": [
|
| 137 |
+
{
|
| 138 |
+
"declaration_pointer": "/runtime_sha256",
|
| 139 |
+
"expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
|
| 140 |
+
"original_pin": {
|
| 141 |
+
"bytes": 27328,
|
| 142 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
|
| 143 |
+
"sha256": "3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7"
|
| 144 |
+
},
|
| 145 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py"
|
| 146 |
+
},
|
| 147 |
+
{
|
| 148 |
+
"declaration_pointer": "/shared_runtime/legal_codec_sha256",
|
| 149 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 150 |
+
"original_pin": {
|
| 151 |
+
"bytes": 14622,
|
| 152 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 153 |
+
"sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
|
| 154 |
+
},
|
| 155 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
|
| 156 |
+
},
|
| 157 |
+
{
|
| 158 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.decoder",
|
| 159 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/decoder.py",
|
| 160 |
+
"original_pin": {
|
| 161 |
+
"bytes": 24220,
|
| 162 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/decoder.py",
|
| 163 |
+
"sha256": "7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257"
|
| 164 |
+
},
|
| 165 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257/ipfs_datasets_py/logic/intent_ir/decoder.py"
|
| 166 |
+
},
|
| 167 |
+
{
|
| 168 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.formalize.rich_grammar",
|
| 169 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
|
| 170 |
+
"original_pin": {
|
| 171 |
+
"bytes": 11527,
|
| 172 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
|
| 173 |
+
"sha256": "6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b"
|
| 174 |
+
},
|
| 175 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py"
|
| 176 |
+
},
|
| 177 |
+
{
|
| 178 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.schema",
|
| 179 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/schema.py",
|
| 180 |
+
"original_pin": {
|
| 181 |
+
"bytes": 27163,
|
| 182 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/schema.py",
|
| 183 |
+
"sha256": "93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56"
|
| 184 |
+
},
|
| 185 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56/ipfs_datasets_py/logic/intent_ir/schema.py"
|
| 186 |
+
},
|
| 187 |
+
{
|
| 188 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.security_ir.model",
|
| 189 |
+
"expected_relative_path": "ipfs_datasets_py/logic/security_ir/model.py",
|
| 190 |
+
"original_pin": {
|
| 191 |
+
"bytes": 37220,
|
| 192 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/security_ir/model.py",
|
| 193 |
+
"sha256": "abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39"
|
| 194 |
+
},
|
| 195 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39/ipfs_datasets_py/logic/security_ir/model.py"
|
| 196 |
+
},
|
| 197 |
+
{
|
| 198 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.software_verification.program",
|
| 199 |
+
"expected_relative_path": "ipfs_datasets_py/logic/software_verification/program.py",
|
| 200 |
+
"original_pin": {
|
| 201 |
+
"bytes": 58065,
|
| 202 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/software_verification/program.py",
|
| 203 |
+
"sha256": "f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91"
|
| 204 |
+
},
|
| 205 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91/ipfs_datasets_py/logic/software_verification/program.py"
|
| 206 |
+
},
|
| 207 |
+
{
|
| 208 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.decoder",
|
| 209 |
+
"expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
|
| 210 |
+
"original_pin": {
|
| 211 |
+
"bytes": 8008,
|
| 212 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
|
| 213 |
+
"sha256": "d7be6bff3a1f1464d4783567b90942258ef718bc1c2b7e02938698ed4e619e57"
|
| 214 |
+
},
|
| 215 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/d7be6bff3a1f1464d4783567b90942258ef718bc1c2b7e02938698ed4e619e57/ipfs_datasets_py/logic/ui_ux_ir/decoder.py"
|
| 216 |
+
},
|
| 217 |
+
{
|
| 218 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.schema",
|
| 219 |
+
"expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/schema.py",
|
| 220 |
+
"original_pin": {
|
| 221 |
+
"bytes": 120714,
|
| 222 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/ui_ux_ir/schema.py",
|
| 223 |
+
"sha256": "8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855"
|
| 224 |
+
},
|
| 225 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855/ipfs_datasets_py/logic/ui_ux_ir/schema.py"
|
| 226 |
+
},
|
| 227 |
+
{
|
| 228 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.optimizers.logic_theorem_optimizer.modal_latent_formula",
|
| 229 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 230 |
+
"original_pin": {
|
| 231 |
+
"bytes": 35427,
|
| 232 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 233 |
+
"sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
|
| 234 |
+
},
|
| 235 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
|
| 236 |
+
},
|
| 237 |
+
{
|
| 238 |
+
"declaration_pointer": "/shared_runtime/native/runtime",
|
| 239 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
|
| 240 |
+
"original_pin": {
|
| 241 |
+
"bytes": 34679,
|
| 242 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
|
| 243 |
+
"sha256": "66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6"
|
| 244 |
+
},
|
| 245 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py"
|
| 246 |
+
},
|
| 247 |
+
{
|
| 248 |
+
"declaration_pointer": "/shared_runtime/numerical/files/canonical_contracts.py",
|
| 249 |
+
"expected_relative_path": "ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
|
| 250 |
+
"original_pin": {
|
| 251 |
+
"bytes": 109257,
|
| 252 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
|
| 253 |
+
"sha256": "d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b"
|
| 254 |
+
},
|
| 255 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py"
|
| 256 |
+
},
|
| 257 |
+
{
|
| 258 |
+
"declaration_pointer": "/shared_runtime/numerical/files/legal_formula_codec.py",
|
| 259 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 260 |
+
"original_pin": {
|
| 261 |
+
"bytes": 14622,
|
| 262 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 263 |
+
"sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
|
| 264 |
+
},
|
| 265 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
|
| 266 |
+
},
|
| 267 |
+
{
|
| 268 |
+
"declaration_pointer": "/shared_runtime/numerical/files/legal_ir_grammar_decoder.py",
|
| 269 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
|
| 270 |
+
"original_pin": {
|
| 271 |
+
"bytes": 146870,
|
| 272 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
|
| 273 |
+
"sha256": "0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd"
|
| 274 |
+
},
|
| 275 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py"
|
| 276 |
+
},
|
| 277 |
+
{
|
| 278 |
+
"declaration_pointer": "/shared_runtime/numerical/files/modal_latent_formula.py",
|
| 279 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 280 |
+
"original_pin": {
|
| 281 |
+
"bytes": 35427,
|
| 282 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 283 |
+
"sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
|
| 284 |
+
},
|
| 285 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
|
| 286 |
+
},
|
| 287 |
+
{
|
| 288 |
+
"declaration_pointer": "/shared_runtime/numerical/files/tree_pin.py",
|
| 289 |
+
"expected_relative_path": "ipfs_datasets_py/logic/autoformal/tree_pin.py",
|
| 290 |
+
"original_pin": {
|
| 291 |
+
"bytes": 1948,
|
| 292 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/autoformal/tree_pin.py",
|
| 293 |
+
"sha256": "587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d"
|
| 294 |
+
},
|
| 295 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d/ipfs_datasets_py/logic/autoformal/tree_pin.py"
|
| 296 |
+
},
|
| 297 |
+
{
|
| 298 |
+
"declaration_pointer": "/shared_runtime/runtime_sha256",
|
| 299 |
+
"expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
|
| 300 |
+
"original_pin": {
|
| 301 |
+
"bytes": 31851,
|
| 302 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
|
| 303 |
+
"sha256": "8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4"
|
| 304 |
+
},
|
| 305 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py"
|
| 306 |
+
}
|
| 307 |
+
],
|
| 308 |
+
"unknown_schema_task_profile_policy": "Unknown fields remain null; no family-only alias or default serving route."
|
| 309 |
+
},
|
| 310 |
+
{
|
| 311 |
+
"checkpoint": {
|
| 312 |
+
"bytes": 304490,
|
| 313 |
+
"path_in_repo": "releases/retained-checkpoints/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930/checkpoint.json",
|
| 314 |
+
"sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
|
| 315 |
+
},
|
| 316 |
+
"codec": null,
|
| 317 |
+
"companion_assets": [],
|
| 318 |
+
"config": {
|
| 319 |
+
"embedding_provenance": {
|
| 320 |
+
"assets": [
|
| 321 |
+
{
|
| 322 |
+
"bytes": 190,
|
| 323 |
+
"name": "1_Pooling/config.json",
|
| 324 |
+
"sha256": "4be450dde3b0273bb9787637cfbd28fe04a7ba6ab9d36ac48e92b11e350ffc23"
|
| 325 |
+
},
|
| 326 |
+
{
|
| 327 |
+
"bytes": 583,
|
| 328 |
+
"name": "config.json",
|
| 329 |
+
"sha256": "00273cdfb3e05c7304d180270bdef8adae45023e7bdfc396338bdd815943dc59"
|
| 330 |
+
},
|
| 331 |
+
{
|
| 332 |
+
"bytes": 66746168,
|
| 333 |
+
"name": "model.safetensors",
|
| 334 |
+
"sha256": "9a1eb90bbac323ea08aa5629b624fe6ae75db121b904799c2266a1e2c2de22d2"
|
| 335 |
+
},
|
| 336 |
+
{
|
| 337 |
+
"bytes": 385,
|
| 338 |
+
"name": "modules.json",
|
| 339 |
+
"sha256": "73348a3d8f8ae4cc5f851dc6b98be3ea819390b814e83656d5eebbadf75fe43e"
|
| 340 |
+
},
|
| 341 |
+
{
|
| 342 |
+
"bytes": 57,
|
| 343 |
+
"name": "sentence_bert_config.json",
|
| 344 |
+
"sha256": "948201d8329907aae938fa62f9ceeed53f5694dacc2b87b9f3b78b37ee986529"
|
| 345 |
+
},
|
| 346 |
+
{
|
| 347 |
+
"bytes": 125,
|
| 348 |
+
"name": "special_tokens_map.json",
|
| 349 |
+
"sha256": "b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3"
|
| 350 |
+
},
|
| 351 |
+
{
|
| 352 |
+
"bytes": 711661,
|
| 353 |
+
"name": "tokenizer.json",
|
| 354 |
+
"sha256": "da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0"
|
| 355 |
+
},
|
| 356 |
+
{
|
| 357 |
+
"bytes": 394,
|
| 358 |
+
"name": "tokenizer_config.json",
|
| 359 |
+
"sha256": "e1790949631401af1bfb6c9c7aeec7fcf612e274d73579d99f704faea40c8ba7"
|
| 360 |
+
},
|
| 361 |
+
{
|
| 362 |
+
"bytes": 231508,
|
| 363 |
+
"name": "vocab.txt",
|
| 364 |
+
"sha256": "07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3"
|
| 365 |
+
}
|
| 366 |
+
],
|
| 367 |
+
"batch_size": 32,
|
| 368 |
+
"device": "cuda",
|
| 369 |
+
"dimension": 384,
|
| 370 |
+
"dtype": "float32",
|
| 371 |
+
"encode_rows_per_second": 2155.864994796075,
|
| 372 |
+
"encode_seconds": 0.890593800926581,
|
| 373 |
+
"load_seconds": 0.6136547059286386,
|
| 374 |
+
"max_tokens_observed": 34,
|
| 375 |
+
"model_id": "thenlper/gte-small",
|
| 376 |
+
"normalized": true,
|
| 377 |
+
"revision": "17e1f347d17fe144873b1201da91788898c639cd",
|
| 378 |
+
"rows": 1920,
|
| 379 |
+
"truncated": false
|
| 380 |
+
},
|
| 381 |
+
"ridges": [
|
| 382 |
+
0.0001,
|
| 383 |
+
0.001,
|
| 384 |
+
0.01,
|
| 385 |
+
0.1
|
| 386 |
+
]
|
| 387 |
+
},
|
| 388 |
+
"contract": null,
|
| 389 |
+
"declaration": {
|
| 390 |
+
"decoder_budget_unit": "fixed schema/scalar slots",
|
| 391 |
+
"development_child_exact": "0/9",
|
| 392 |
+
"development_parent_exact": "9/9",
|
| 393 |
+
"dimension_role": "input_embedding",
|
| 394 |
+
"input_width": 384,
|
| 395 |
+
"parent_pretraining_independence": "unknown",
|
| 396 |
+
"payload_ir_family": "security_ir",
|
| 397 |
+
"promoted": false,
|
| 398 |
+
"receipt": {
|
| 399 |
+
"bytes": 304490,
|
| 400 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/06/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930",
|
| 401 |
+
"sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
|
| 402 |
+
},
|
| 403 |
+
"role": "unpromoted repository child envelope"
|
| 404 |
+
},
|
| 405 |
+
"full_runtime_closure_verified": false,
|
| 406 |
+
"identity": {
|
| 407 |
+
"checkpoint_schema": "codebase-source-384-generation@1",
|
| 408 |
+
"dimension": 384,
|
| 409 |
+
"dimension_role": "input_embedding",
|
| 410 |
+
"donor": null,
|
| 411 |
+
"donor_pins": null,
|
| 412 |
+
"embedded_decoder_schema": "structured-source-384-autoencoder/v1",
|
| 413 |
+
"format_id": null,
|
| 414 |
+
"initialization_only": false,
|
| 415 |
+
"ir_family_id": "codebase_ir",
|
| 416 |
+
"legacy_profile": "codebase_ir/source_conditioned_384_v1",
|
| 417 |
+
"native_codebase_decoder_complete": false,
|
| 418 |
+
"original_checkpoint_pin": {
|
| 419 |
+
"bytes": 304490,
|
| 420 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/06/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930",
|
| 421 |
+
"sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
|
| 422 |
+
},
|
| 423 |
+
"payload_ir_family": "security_ir",
|
| 424 |
+
"profile_id": null,
|
| 425 |
+
"proof_authority": false,
|
| 426 |
+
"record_id": "ir-model-asset-binding/v1:327b68fdd5889632e5752370a9c168a80ada5597436264fb1d6fb5fc483e778f",
|
| 427 |
+
"retained_status": "borrowed_security_payload_unpromoted",
|
| 428 |
+
"role": "unpromoted repository child envelope",
|
| 429 |
+
"runtime_ready": false,
|
| 430 |
+
"schema_version": null,
|
| 431 |
+
"source_profile_id": null,
|
| 432 |
+
"task_id": null,
|
| 433 |
+
"teacher_qualified": false,
|
| 434 |
+
"trained": null
|
| 435 |
+
},
|
| 436 |
+
"license_scope": {
|
| 437 |
+
"repository_source": "AGPL-3.0, see SOURCE-LICENSE",
|
| 438 |
+
"weights_and_companions": "Original provenance retained; this release supplies no new blanket license grant."
|
| 439 |
+
},
|
| 440 |
+
"numerical_execution_performed": false,
|
| 441 |
+
"original_package": null,
|
| 442 |
+
"schema": "retained-ir-checkpoint-release/v1",
|
| 443 |
+
"source_binding_scope": "listed checkpoint implementation hashes only, not full import/native closure",
|
| 444 |
+
"source_map": [
|
| 445 |
+
{
|
| 446 |
+
"declaration_pointer": "/runtime_sha256",
|
| 447 |
+
"expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
|
| 448 |
+
"original_pin": {
|
| 449 |
+
"bytes": 27328,
|
| 450 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
|
| 451 |
+
"sha256": "3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7"
|
| 452 |
+
},
|
| 453 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py"
|
| 454 |
+
},
|
| 455 |
+
{
|
| 456 |
+
"declaration_pointer": "/shared_runtime/legal_codec_sha256",
|
| 457 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 458 |
+
"original_pin": {
|
| 459 |
+
"bytes": 14622,
|
| 460 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 461 |
+
"sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
|
| 462 |
+
},
|
| 463 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
|
| 464 |
+
},
|
| 465 |
+
{
|
| 466 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.decoder",
|
| 467 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/decoder.py",
|
| 468 |
+
"original_pin": {
|
| 469 |
+
"bytes": 24220,
|
| 470 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/decoder.py",
|
| 471 |
+
"sha256": "7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257"
|
| 472 |
+
},
|
| 473 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257/ipfs_datasets_py/logic/intent_ir/decoder.py"
|
| 474 |
+
},
|
| 475 |
+
{
|
| 476 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.formalize.rich_grammar",
|
| 477 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
|
| 478 |
+
"original_pin": {
|
| 479 |
+
"bytes": 11527,
|
| 480 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
|
| 481 |
+
"sha256": "6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b"
|
| 482 |
+
},
|
| 483 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py"
|
| 484 |
+
},
|
| 485 |
+
{
|
| 486 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.schema",
|
| 487 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/schema.py",
|
| 488 |
+
"original_pin": {
|
| 489 |
+
"bytes": 27163,
|
| 490 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/schema.py",
|
| 491 |
+
"sha256": "93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56"
|
| 492 |
+
},
|
| 493 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56/ipfs_datasets_py/logic/intent_ir/schema.py"
|
| 494 |
+
},
|
| 495 |
+
{
|
| 496 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.security_ir.model",
|
| 497 |
+
"expected_relative_path": "ipfs_datasets_py/logic/security_ir/model.py",
|
| 498 |
+
"original_pin": {
|
| 499 |
+
"bytes": 37220,
|
| 500 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/security_ir/model.py",
|
| 501 |
+
"sha256": "abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39"
|
| 502 |
+
},
|
| 503 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39/ipfs_datasets_py/logic/security_ir/model.py"
|
| 504 |
+
},
|
| 505 |
+
{
|
| 506 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.software_verification.program",
|
| 507 |
+
"expected_relative_path": "ipfs_datasets_py/logic/software_verification/program.py",
|
| 508 |
+
"original_pin": {
|
| 509 |
+
"bytes": 58065,
|
| 510 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/software_verification/program.py",
|
| 511 |
+
"sha256": "f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91"
|
| 512 |
+
},
|
| 513 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91/ipfs_datasets_py/logic/software_verification/program.py"
|
| 514 |
+
},
|
| 515 |
+
{
|
| 516 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.decoder",
|
| 517 |
+
"expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
|
| 518 |
+
"original_pin": {
|
| 519 |
+
"bytes": 7300,
|
| 520 |
+
"path": "/home/barberb/lift_coding/artifacts/ir-original-corpus-replay-20261003/inputs/legal-original/ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
|
| 521 |
+
"sha256": "21e8315b0054f7755512212d610d4e3f5f4ac86387f3b27edb9632fa8ca68bc3"
|
| 522 |
+
},
|
| 523 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/21e8315b0054f7755512212d610d4e3f5f4ac86387f3b27edb9632fa8ca68bc3/ipfs_datasets_py/logic/ui_ux_ir/decoder.py"
|
| 524 |
+
},
|
| 525 |
+
{
|
| 526 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.schema",
|
| 527 |
+
"expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/schema.py",
|
| 528 |
+
"original_pin": {
|
| 529 |
+
"bytes": 120714,
|
| 530 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/ui_ux_ir/schema.py",
|
| 531 |
+
"sha256": "8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855"
|
| 532 |
+
},
|
| 533 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855/ipfs_datasets_py/logic/ui_ux_ir/schema.py"
|
| 534 |
+
},
|
| 535 |
+
{
|
| 536 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.optimizers.logic_theorem_optimizer.modal_latent_formula",
|
| 537 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 538 |
+
"original_pin": {
|
| 539 |
+
"bytes": 35427,
|
| 540 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 541 |
+
"sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
|
| 542 |
+
},
|
| 543 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
|
| 544 |
+
},
|
| 545 |
+
{
|
| 546 |
+
"declaration_pointer": "/shared_runtime/native/runtime",
|
| 547 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
|
| 548 |
+
"original_pin": {
|
| 549 |
+
"bytes": 34679,
|
| 550 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
|
| 551 |
+
"sha256": "66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6"
|
| 552 |
+
},
|
| 553 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py"
|
| 554 |
+
},
|
| 555 |
+
{
|
| 556 |
+
"declaration_pointer": "/shared_runtime/numerical/files/canonical_contracts.py",
|
| 557 |
+
"expected_relative_path": "ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
|
| 558 |
+
"original_pin": {
|
| 559 |
+
"bytes": 109257,
|
| 560 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
|
| 561 |
+
"sha256": "d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b"
|
| 562 |
+
},
|
| 563 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py"
|
| 564 |
+
},
|
| 565 |
+
{
|
| 566 |
+
"declaration_pointer": "/shared_runtime/numerical/files/legal_formula_codec.py",
|
| 567 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 568 |
+
"original_pin": {
|
| 569 |
+
"bytes": 14622,
|
| 570 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 571 |
+
"sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
|
| 572 |
+
},
|
| 573 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
|
| 574 |
+
},
|
| 575 |
+
{
|
| 576 |
+
"declaration_pointer": "/shared_runtime/numerical/files/legal_ir_grammar_decoder.py",
|
| 577 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
|
| 578 |
+
"original_pin": {
|
| 579 |
+
"bytes": 146870,
|
| 580 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
|
| 581 |
+
"sha256": "0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd"
|
| 582 |
+
},
|
| 583 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py"
|
| 584 |
+
},
|
| 585 |
+
{
|
| 586 |
+
"declaration_pointer": "/shared_runtime/numerical/files/modal_latent_formula.py",
|
| 587 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 588 |
+
"original_pin": {
|
| 589 |
+
"bytes": 35427,
|
| 590 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 591 |
+
"sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
|
| 592 |
+
},
|
| 593 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
|
| 594 |
+
},
|
| 595 |
+
{
|
| 596 |
+
"declaration_pointer": "/shared_runtime/numerical/files/tree_pin.py",
|
| 597 |
+
"expected_relative_path": "ipfs_datasets_py/logic/autoformal/tree_pin.py",
|
| 598 |
+
"original_pin": {
|
| 599 |
+
"bytes": 1948,
|
| 600 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/autoformal/tree_pin.py",
|
| 601 |
+
"sha256": "587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d"
|
| 602 |
+
},
|
| 603 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d/ipfs_datasets_py/logic/autoformal/tree_pin.py"
|
| 604 |
+
},
|
| 605 |
+
{
|
| 606 |
+
"declaration_pointer": "/shared_runtime/runtime_sha256",
|
| 607 |
+
"expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
|
| 608 |
+
"original_pin": {
|
| 609 |
+
"bytes": 31851,
|
| 610 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
|
| 611 |
+
"sha256": "8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4"
|
| 612 |
+
},
|
| 613 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py"
|
| 614 |
+
}
|
| 615 |
+
],
|
| 616 |
+
"unknown_schema_task_profile_policy": "Unknown fields remain null; no family-only alias or default serving route."
|
| 617 |
+
}
|
| 618 |
+
],
|
| 619 |
+
"dimension": 384,
|
| 620 |
+
"empty_lane": false,
|
| 621 |
+
"input_audit_pins": [
|
| 622 |
+
{
|
| 623 |
+
"bytes": 661812,
|
| 624 |
+
"path": "/home/barberb/lift_coding/artifacts/ir-model-manager-hf-sync-20261004/publication_inventory_audit.json",
|
| 625 |
+
"sha256": "8e857941cee73c75e8dc4ac7aa5df604e8953aa9dc87ec00bd2f83c0677e93ae"
|
| 626 |
+
},
|
| 627 |
+
{
|
| 628 |
+
"bytes": 1033525,
|
| 629 |
+
"path": "/home/barberb/lift_coding/artifacts/ir-model-manager-hf-sync-20261004/publication_source_binding_audit.json",
|
| 630 |
+
"sha256": "1ae36985f031ac16fa989cb4ec27f1ec49fdebf2d769b771c7db491dec1f6d9a"
|
| 631 |
+
}
|
| 632 |
+
],
|
| 633 |
+
"ir_family_id": "codebase_ir",
|
| 634 |
+
"original_lane_declaration": {
|
| 635 |
+
"cell_id": "codebase_ir_384d",
|
| 636 |
+
"checkpoint_count": 2,
|
| 637 |
+
"dimension": 384,
|
| 638 |
+
"dimension_profile": {
|
| 639 |
+
"dimension": 384,
|
| 640 |
+
"dimension_role_required": true,
|
| 641 |
+
"encoder_kind": "GTE-small source embedding for source-conditioned tasks",
|
| 642 |
+
"hard_encoder_token_limit": 512,
|
| 643 |
+
"model_id": "thenlper/gte-small",
|
| 644 |
+
"model_revision": "17e1f347d17fe144873b1201da91788898c639cd",
|
| 645 |
+
"normalization": "l2",
|
| 646 |
+
"pooling": "mean",
|
| 647 |
+
"qualified_source_token_limit": null,
|
| 648 |
+
"unknown_limit_policy": "freeze task/span-specific admitted budget within encoder ceiling; historical compiler profiles remain separate"
|
| 649 |
+
},
|
| 650 |
+
"empty_model_lane": false,
|
| 651 |
+
"huggingface_plan": {
|
| 652 |
+
"existing_descriptor_source": null,
|
| 653 |
+
"existing_read_only_descriptors": [],
|
| 654 |
+
"load_requires": [
|
| 655 |
+
"full immutable commit",
|
| 656 |
+
"manifest SHA256",
|
| 657 |
+
"matching family/dimension role/task/profile/codec",
|
| 658 |
+
"actual checkpoint SHA256"
|
| 659 |
+
],
|
| 660 |
+
"namespace_write_access_verified": false,
|
| 661 |
+
"release_path_template": "releases/<task>/<profile>/<release_id>/",
|
| 662 |
+
"repo_type": "model",
|
| 663 |
+
"repository_id_template": "<hf_namespace>/codebase-ir-autoencoder-384d",
|
| 664 |
+
"status": "proposed_not_created",
|
| 665 |
+
"suggested_namespace_from_existing_release_descriptors": "Publicus",
|
| 666 |
+
"suggested_repository_id": "Publicus/codebase-ir-autoencoder-384d",
|
| 667 |
+
"visibility": null,
|
| 668 |
+
"visibility_status": "explicit deployment configuration required; no visibility changes performed during planning"
|
| 669 |
+
},
|
| 670 |
+
"inventory_receipt": {
|
| 671 |
+
"bytes": 8393,
|
| 672 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-ir-numerical-replay-20261003/inputs/inventories/codebase_ir/384d.json",
|
| 673 |
+
"sha256": "d01836c6d11996d6d4e88a7d2722fca63004ed4fea19e08f331db65903b4fdc4"
|
| 674 |
+
},
|
| 675 |
+
"ir_family_id": "codebase_ir",
|
| 676 |
+
"reference_checks": [
|
| 677 |
+
{
|
| 678 |
+
"kind": "checkpoint",
|
| 679 |
+
"receipt": {
|
| 680 |
+
"bytes": 1009515,
|
| 681 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/cc/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f",
|
| 682 |
+
"sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
|
| 683 |
+
},
|
| 684 |
+
"status": "verified"
|
| 685 |
+
},
|
| 686 |
+
{
|
| 687 |
+
"kind": "checkpoint",
|
| 688 |
+
"receipt": {
|
| 689 |
+
"bytes": 304490,
|
| 690 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/06/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930",
|
| 691 |
+
"sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
|
| 692 |
+
},
|
| 693 |
+
"status": "verified"
|
| 694 |
+
}
|
| 695 |
+
],
|
| 696 |
+
"task_profiles_to_inventory": [
|
| 697 |
+
"source_to_native_ir",
|
| 698 |
+
"structural_reconstruction",
|
| 699 |
+
"native_ir_to_logic",
|
| 700 |
+
"native_ir_to_source",
|
| 701 |
+
"retained_source_byte_restoration"
|
| 702 |
+
],
|
| 703 |
+
"unsupported_checkpoint_deserialization_for_runtime": false
|
| 704 |
+
},
|
| 705 |
+
"qualified_runtime_count": 0,
|
| 706 |
+
"repository_id": "Publicus/codebase-ir-autoencoder-384d",
|
| 707 |
+
"schema": "retained-ir-lane-release/v1",
|
| 708 |
+
"teacher_qualified_count": 0,
|
| 709 |
+
"trained_768_model_count": 0
|
| 710 |
+
}
|
releases/20261004-retained-checkpoints-v1/original-lane-inventory.json
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"schema": "ir-family-dimension-inventory-plan/v1",
|
| 3 |
+
"status": "declarative_plan_not_runtime_inventory",
|
| 4 |
+
"cell_id": "codebase_ir_384d",
|
| 5 |
+
"ir_family_id": "codebase_ir",
|
| 6 |
+
"dimension": 384,
|
| 7 |
+
"store_id_proposed": "ir-cell:codebase_ir:384d",
|
| 8 |
+
"store_identity_dimensions": [
|
| 9 |
+
"ir_family_id",
|
| 10 |
+
"dimension"
|
| 11 |
+
],
|
| 12 |
+
"variant_identity_additions": [
|
| 13 |
+
"dimension_role",
|
| 14 |
+
"task_id",
|
| 15 |
+
"input_representation_profile",
|
| 16 |
+
"encoder_tokenizer_revisions",
|
| 17 |
+
"decoder_architecture",
|
| 18 |
+
"target_ir_family",
|
| 19 |
+
"target_schema",
|
| 20 |
+
"target_codec",
|
| 21 |
+
"input_budget",
|
| 22 |
+
"output_budget",
|
| 23 |
+
"span_profile",
|
| 24 |
+
"objective_implementation"
|
| 25 |
+
],
|
| 26 |
+
"native_semantics": [
|
| 27 |
+
"observed code and source versions",
|
| 28 |
+
"typed ProgramIR/contracts",
|
| 29 |
+
"calls/effects/dependencies",
|
| 30 |
+
"native Codebase grammar and code inverse"
|
| 31 |
+
],
|
| 32 |
+
"canonical_ir_identity_depends_on_model_dimension": false,
|
| 33 |
+
"storage": {
|
| 34 |
+
"status": "planned_not_created",
|
| 35 |
+
"root_template": "<ir_store_root>/codebase_ir/384d",
|
| 36 |
+
"inventory_export": "<ir_store_root>/codebase_ir/384d/inventory.json",
|
| 37 |
+
"registry_database": "<ir_store_root>/codebase_ir/384d/registry.duckdb",
|
| 38 |
+
"index_database": "<ir_store_root>/codebase_ir/384d/index.duckdb",
|
| 39 |
+
"ducklake_catalog_database": "<ir_store_root>/codebase_ir/384d/lake/catalog.duckdb",
|
| 40 |
+
"ducklake_data_prefix": "<ir_store_root>/codebase_ir/384d/lake/data/",
|
| 41 |
+
"mutable_artifact_root": "<ir_store_root>/codebase_ir/384d/artifacts/",
|
| 42 |
+
"run_namespace": "<ir_store_root>/codebase_ir/384d/runs/<task>/<profile>/<run_id>/",
|
| 43 |
+
"database_writer_policy": "separate serialized owner per physical database; registry forbids foreign tables",
|
| 44 |
+
"canonical_repository_source_owner": "RepositoryCodebaseIndex captures repository code once; cell indexes reference exact admitted source/semantic heads when relevant",
|
| 45 |
+
"family_source_owner": "Canonical repository/source snapshot and source-correspondence owners",
|
| 46 |
+
"source_roots_required": [
|
| 47 |
+
"family source/corpus version and complete span/context manifest",
|
| 48 |
+
"repository source/semantic roots when code-grounding applies",
|
| 49 |
+
"applicability source revisions and both typed join endpoint roots"
|
| 50 |
+
],
|
| 51 |
+
"ducklake_layout_adapter_required": true,
|
| 52 |
+
"current_isolated_history_limits": {
|
| 53 |
+
"metadata_name": "history.ducklake",
|
| 54 |
+
"byte_cap": 268435456,
|
| 55 |
+
"production_supported": false
|
| 56 |
+
}
|
| 57 |
+
},
|
| 58 |
+
"huggingface": {
|
| 59 |
+
"status": "proposed_not_created",
|
| 60 |
+
"repo_type": "model",
|
| 61 |
+
"repository_id_template": "<hf_namespace>/codebase-ir-autoencoder-384d",
|
| 62 |
+
"suggested_namespace_from_existing_release_descriptors": "Publicus",
|
| 63 |
+
"suggested_repository_id": "Publicus/codebase-ir-autoencoder-384d",
|
| 64 |
+
"namespace_write_access_verified": false,
|
| 65 |
+
"release_path_template": "releases/<task>/<profile>/<release_id>/",
|
| 66 |
+
"load_requires": [
|
| 67 |
+
"full immutable commit",
|
| 68 |
+
"manifest SHA256",
|
| 69 |
+
"matching family/dimension role/task/profile/codec",
|
| 70 |
+
"actual checkpoint SHA256"
|
| 71 |
+
],
|
| 72 |
+
"existing_read_only_descriptors": [],
|
| 73 |
+
"existing_descriptor_source": null,
|
| 74 |
+
"visibility": null,
|
| 75 |
+
"visibility_status": "explicit deployment configuration required; no visibility changes performed during planning"
|
| 76 |
+
},
|
| 77 |
+
"dimension_profile": {
|
| 78 |
+
"dimension": 384,
|
| 79 |
+
"encoder_kind": "GTE-small source embedding for source-conditioned tasks",
|
| 80 |
+
"model_id": "thenlper/gte-small",
|
| 81 |
+
"model_revision": "17e1f347d17fe144873b1201da91788898c639cd",
|
| 82 |
+
"hard_encoder_token_limit": 512,
|
| 83 |
+
"qualified_source_token_limit": null,
|
| 84 |
+
"pooling": "mean",
|
| 85 |
+
"normalization": "l2",
|
| 86 |
+
"unknown_limit_policy": "freeze task/span-specific admitted budget within encoder ceiling; historical compiler profiles remain separate",
|
| 87 |
+
"dimension_role_required": true
|
| 88 |
+
},
|
| 89 |
+
"task_profiles_to_inventory": [
|
| 90 |
+
"source_to_native_ir",
|
| 91 |
+
"structural_reconstruction",
|
| 92 |
+
"native_ir_to_logic",
|
| 93 |
+
"native_ir_to_source",
|
| 94 |
+
"retained_source_byte_restoration"
|
| 95 |
+
],
|
| 96 |
+
"source_only_raw_text_decoder_admission": "not asserted by this plan; task/profile evidence and complete source access must be qualified independently",
|
| 97 |
+
"existing_checkpoint_evidence": [
|
| 98 |
+
{
|
| 99 |
+
"role": "registered shared parent envelope",
|
| 100 |
+
"receipt": {
|
| 101 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/cc/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f",
|
| 102 |
+
"bytes": 1009515,
|
| 103 |
+
"sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
|
| 104 |
+
},
|
| 105 |
+
"dimension_role": "input_embedding",
|
| 106 |
+
"input_width": 384,
|
| 107 |
+
"owning_ir_family": "codebase_ir",
|
| 108 |
+
"payload_ir_family": "security_ir",
|
| 109 |
+
"decoder_kind": "frozen projection and fixed-tree ridge readout",
|
| 110 |
+
"native_codebase_decoder_complete": false
|
| 111 |
+
},
|
| 112 |
+
{
|
| 113 |
+
"role": "unpromoted repository child envelope",
|
| 114 |
+
"receipt": {
|
| 115 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/06/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930",
|
| 116 |
+
"bytes": 304490,
|
| 117 |
+
"sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
|
| 118 |
+
},
|
| 119 |
+
"dimension_role": "input_embedding",
|
| 120 |
+
"input_width": 384,
|
| 121 |
+
"payload_ir_family": "security_ir",
|
| 122 |
+
"development_parent_exact": "9/9",
|
| 123 |
+
"development_child_exact": "0/9",
|
| 124 |
+
"parent_pretraining_independence": "unknown",
|
| 125 |
+
"decoder_budget_unit": "fixed schema/scalar slots",
|
| 126 |
+
"promoted": false
|
| 127 |
+
}
|
| 128 |
+
],
|
| 129 |
+
"checkpoint_discovery_complete": false,
|
| 130 |
+
"existing_cached_vector_rows": [],
|
| 131 |
+
"cached_codebase_rows_in_previous2640_transfer_inventory": 0,
|
| 132 |
+
"old_asset_policy": "Adopt authenticated read-only references. No recomputation, relabeling, in-place training or physical migration during planning.",
|
| 133 |
+
"span_curriculum": [
|
| 134 |
+
{
|
| 135 |
+
"stage_id": "S0",
|
| 136 |
+
"subject_scope": "same inherited expression cohort",
|
| 137 |
+
"qualified_input_budget": null,
|
| 138 |
+
"qualified_output_budget": null,
|
| 139 |
+
"budget_status": "freeze from pinned-tokenizer/codec measurements before fitting",
|
| 140 |
+
"requires_complete_span_accounting": true
|
| 141 |
+
},
|
| 142 |
+
{
|
| 143 |
+
"stage_id": "S1",
|
| 144 |
+
"subject_scope": "complete supported expression/function",
|
| 145 |
+
"qualified_input_budget": null,
|
| 146 |
+
"qualified_output_budget": null,
|
| 147 |
+
"budget_status": "freeze from pinned-tokenizer/codec measurements before fitting",
|
| 148 |
+
"requires_complete_span_accounting": true
|
| 149 |
+
},
|
| 150 |
+
{
|
| 151 |
+
"stage_id": "S2",
|
| 152 |
+
"subject_scope": "connected calls/import context",
|
| 153 |
+
"qualified_input_budget": null,
|
| 154 |
+
"qualified_output_budget": null,
|
| 155 |
+
"budget_status": "freeze from pinned-tokenizer/codec measurements before fitting",
|
| 156 |
+
"requires_complete_span_accounting": true
|
| 157 |
+
},
|
| 158 |
+
{
|
| 159 |
+
"stage_id": "S3",
|
| 160 |
+
"subject_scope": "complete supported function/module unit",
|
| 161 |
+
"qualified_input_budget": null,
|
| 162 |
+
"qualified_output_budget": null,
|
| 163 |
+
"budget_status": "freeze from pinned-tokenizer/codec measurements before fitting",
|
| 164 |
+
"requires_complete_span_accounting": true
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"stage_id": "S4",
|
| 168 |
+
"subject_scope": "sealed module/dependency-slice aggregation",
|
| 169 |
+
"qualified_input_budget": null,
|
| 170 |
+
"qualified_output_budget": null,
|
| 171 |
+
"budget_status": "freeze from pinned-tokenizer/codec measurements before fitting",
|
| 172 |
+
"requires_complete_span_accounting": true
|
| 173 |
+
}
|
| 174 |
+
],
|
| 175 |
+
"independent_heads": [
|
| 176 |
+
"source_applicability",
|
| 177 |
+
"serving_model_by_task_profile",
|
| 178 |
+
"candidate_training",
|
| 179 |
+
"lake_history_delivery",
|
| 180 |
+
"hub_publication"
|
| 181 |
+
],
|
| 182 |
+
"promotion_policy": "Independent family/task/profile gate; original parent and shorter-span replay retained; another cell cannot grant qualification.",
|
| 183 |
+
"notes": [
|
| 184 |
+
"Existing wrapper retains SecurityIR numerical payload; native Codebase codec/head and source-successor coverage require separate qualification."
|
| 185 |
+
],
|
| 186 |
+
"runtime_databases_created": false,
|
| 187 |
+
"remote_repository_created": false,
|
| 188 |
+
"model_or_embeddings_modified": false,
|
| 189 |
+
"continuation_and_transfer_policy": {
|
| 190 |
+
"same_variant_resume_parent_required": true,
|
| 191 |
+
"cross_cell_or_contract_transfer": "Use authenticated donor store/version/checkpoint refs and explicit transfer/KD edge, then initialize a new compatible variant; never fake same-variant parentage."
|
| 192 |
+
}
|
| 193 |
+
}
|
releases/20261004-retained-checkpoints-v1/source/0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
releases/20261004-retained-checkpoints-v1/source/21e8315b0054f7755512212d610d4e3f5f4ac86387f3b27edb9632fa8ca68bc3/ipfs_datasets_py/logic/ui_ux_ir/decoder.py
ADDED
|
@@ -0,0 +1,157 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact-version decoding of every declared UI/UX IR wire field.
|
| 2 |
+
|
| 3 |
+
All nested records are constructed from the local schema's closed dataclasses.
|
| 4 |
+
No field is silently dropped, no scalar is stringified/coerced, and ordered
|
| 5 |
+
collections retain order. Schema validation remains the cross-reference owner.
|
| 6 |
+
This wire codec does not claim neural decoding or source semantic fidelity.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from collections.abc import Mapping
|
| 11 |
+
from dataclasses import MISSING, fields, is_dataclass
|
| 12 |
+
from enum import Enum
|
| 13 |
+
from functools import lru_cache
|
| 14 |
+
import json
|
| 15 |
+
import math
|
| 16 |
+
from types import UnionType
|
| 17 |
+
from typing import Any, get_args, get_origin, get_type_hints
|
| 18 |
+
|
| 19 |
+
from . import schema
|
| 20 |
+
from .schema import UIIRDocument, UIIRValidationError
|
| 21 |
+
|
| 22 |
+
MAX_WIRE_BYTES = 16 * 1024 * 1024
|
| 23 |
+
MAX_WIRE_NODES = 200000
|
| 24 |
+
MAX_WIRE_DEPTH = 64
|
| 25 |
+
_WIRE_CLASSES = frozenset(value for value in vars(schema).values()
|
| 26 |
+
if isinstance(value, type) and is_dataclass(value) and value.__module__ == schema.__name__)
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
class UIIRDecodeError(UIIRValidationError):
|
| 30 |
+
"""An untrusted payload cannot be decoded without loss or coercion."""
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def _require(condition, message):
|
| 34 |
+
if not condition:
|
| 35 |
+
raise UIIRDecodeError(message)
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _unique_object(pairs):
|
| 39 |
+
result = {}
|
| 40 |
+
for key, value in pairs:
|
| 41 |
+
_require(key not in result, "duplicate UI/UX IR JSON field: " + key)
|
| 42 |
+
result[key] = value
|
| 43 |
+
return result
|
| 44 |
+
|
| 45 |
+
|
| 46 |
+
def _snapshot(value, budget, depth=0):
|
| 47 |
+
budget[0] -= 1
|
| 48 |
+
_require(budget[0] >= 0 and depth <= MAX_WIRE_DEPTH, "UI/UX IR wire resource bound exceeded")
|
| 49 |
+
if isinstance(value, Mapping):
|
| 50 |
+
_require(all(type(key) is str for key in value), "UI/UX IR object keys must be strings")
|
| 51 |
+
return {key: _snapshot(item, budget, depth + 1) for key, item in value.items()}
|
| 52 |
+
if type(value) in (list, tuple):
|
| 53 |
+
return [_snapshot(item, budget, depth + 1) for item in value]
|
| 54 |
+
_require(value is None or type(value) in (str, bool, int, float), "UI/UX IR requires JSON values")
|
| 55 |
+
_require(type(value) is not float or math.isfinite(value), "UI/UX IR contains nonfinite number")
|
| 56 |
+
return value
|
| 57 |
+
|
| 58 |
+
|
| 59 |
+
@lru_cache(maxsize=len(_WIRE_CLASSES))
|
| 60 |
+
def _field_types(record_type):
|
| 61 |
+
_require(record_type in _WIRE_CLASSES, "unsupported UI/UX IR record type")
|
| 62 |
+
return get_type_hints(record_type)
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _decode_value(value, expected, path):
|
| 66 |
+
origin, arguments = get_origin(expected), get_args(expected)
|
| 67 |
+
if origin is UnionType:
|
| 68 |
+
nonnull = tuple(item for item in arguments if item is not type(None))
|
| 69 |
+
_require(len(nonnull) == 1 and type(None) in arguments, "unsupported UI/UX IR union type")
|
| 70 |
+
return None if value is None else _decode_value(value, nonnull[0], path)
|
| 71 |
+
if origin is tuple:
|
| 72 |
+
_require(len(arguments) == 2 and arguments[1] is Ellipsis and type(value) is list,
|
| 73 |
+
path + " must be an array")
|
| 74 |
+
return tuple(_decode_value(item, arguments[0], path + "[" + str(index) + "]")
|
| 75 |
+
for index, item in enumerate(value))
|
| 76 |
+
if origin is Mapping:
|
| 77 |
+
_require(arguments == (str, Any) and type(value) is dict, path + " must be a JSON object")
|
| 78 |
+
# The complete JSON snapshot was bounded above. The existing schema
|
| 79 |
+
# owner freezes these extension/settings payloads and rejects code.
|
| 80 |
+
return value
|
| 81 |
+
if expected in _WIRE_CLASSES:
|
| 82 |
+
return _decode_record(value, expected, path)
|
| 83 |
+
if isinstance(expected, type) and issubclass(expected, Enum):
|
| 84 |
+
_require(expected.__module__ == schema.__name__ and type(value) is str,
|
| 85 |
+
path + " must be a declared enum string")
|
| 86 |
+
try:
|
| 87 |
+
return expected(value)
|
| 88 |
+
except ValueError as exc:
|
| 89 |
+
raise UIIRDecodeError(path + " has an unknown enum value") from exc
|
| 90 |
+
_require(expected in (str, bool, int) and type(value) is expected,
|
| 91 |
+
path + " has the wrong scalar type")
|
| 92 |
+
return value
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _decode_record(payload, record_type, path):
|
| 96 |
+
_require(type(payload) is dict, path + " must be an object")
|
| 97 |
+
declared = {field.name: field for field in fields(record_type)}
|
| 98 |
+
unknown = sorted(set(payload) - set(declared))
|
| 99 |
+
_require(not unknown, path + " has unknown fields: " + ", ".join(unknown))
|
| 100 |
+
missing = [name for name, field in declared.items() if name not in payload
|
| 101 |
+
and field.default is MISSING and field.default_factory is MISSING]
|
| 102 |
+
_require(not missing, path + " is missing required fields: " + ", ".join(missing))
|
| 103 |
+
hints = _field_types(record_type)
|
| 104 |
+
return record_type(**{key: _decode_value(value, hints[key], path + "." + key)
|
| 105 |
+
for key, value in payload.items()})
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
# Retain the original private helper names for local consumers, with exact
|
| 109 |
+
# nested schemas and types instead of lossy str()/int() conversions.
|
| 110 |
+
def _decode_source(payload):
|
| 111 |
+
return _decode_record(_snapshot(payload, [MAX_WIRE_NODES]), schema.UISourceRef, "UISourceRef")
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _decode_component(payload):
|
| 115 |
+
return _decode_record(_snapshot(payload, [MAX_WIRE_NODES]), schema.UIComponent, "UIComponent")
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _decode_terminal(payload):
|
| 119 |
+
return _decode_record(_snapshot(payload, [MAX_WIRE_NODES]), schema.UITerminalOutcome, "UITerminalOutcome")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _decode_locale(payload):
|
| 123 |
+
return _decode_record(_snapshot(payload, [MAX_WIRE_NODES]), schema.UILocaleDefaults, "UILocaleDefaults")
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def decode_ui_ir(payload: Mapping[str, Any] | str | bytes) -> UIIRDocument:
|
| 127 |
+
"""Decode every schema field and validate the complete reference closure.
|
| 128 |
+
|
| 129 |
+
Omitted optional fields receive only schema-declared defaults. Present null,
|
| 130 |
+
false, zero or empty values never substitute for a missing field. Legacy
|
| 131 |
+
versions still require the explicit migration owner.
|
| 132 |
+
"""
|
| 133 |
+
try:
|
| 134 |
+
if isinstance(payload, (str, bytes, bytearray)):
|
| 135 |
+
raw = payload.encode("utf-8") if isinstance(payload, str) else bytes(payload)
|
| 136 |
+
_require(len(raw) <= MAX_WIRE_BYTES, "UI/UX IR wire exceeds byte bound")
|
| 137 |
+
payload = json.loads(raw.decode("utf-8"), object_pairs_hook=_unique_object)
|
| 138 |
+
payload = _snapshot(payload, [MAX_WIRE_NODES])
|
| 139 |
+
_require(type(payload) is dict, "UI/UX IR payload must decode to an object")
|
| 140 |
+
raw = json.dumps(payload, ensure_ascii=False, separators=(",", ":"), allow_nan=False).encode()
|
| 141 |
+
_require(len(raw) <= MAX_WIRE_BYTES, "UI/UX IR wire exceeds byte bound")
|
| 142 |
+
version = payload.get("schema_version")
|
| 143 |
+
_require(type(version) is str and bool(version), "UI/UX IR payload missing schema_version")
|
| 144 |
+
if version == schema.LEGACY_UI_UX_IR_SCHEMA_VERSION:
|
| 145 |
+
raise UIIRDecodeError(f"Legacy schema_version {version!r} requires explicit migration before decode")
|
| 146 |
+
_require(version == schema.UI_UX_IR_SCHEMA_VERSION,
|
| 147 |
+
f"Unsupported schema_version {version!r}; expected {schema.UI_UX_IR_SCHEMA_VERSION!r}")
|
| 148 |
+
schema.reject_unknown_document_fields(payload)
|
| 149 |
+
document = _decode_record(payload, UIIRDocument, "UIIRDocument")
|
| 150 |
+
return schema.validate_ui_ir(document)
|
| 151 |
+
except UIIRDecodeError:
|
| 152 |
+
raise
|
| 153 |
+
except (UIIRValidationError, UnicodeError, ValueError, TypeError, KeyError, RecursionError) as exc:
|
| 154 |
+
raise UIIRDecodeError(f"Failed to decode UI/UX IR document: {exc}") from exc
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
__all__ = ["UIIRDecodeError", "decode_ui_ir"]
|
releases/20261004-retained-checkpoints-v1/source/3f9ca9ce7b4cf2a2d10d6aeb1fae78543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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experimental fixed-schema typed IR decoder over a trained Legal 384D encoder.
|
| 2 |
+
|
| 3 |
+
A frozen inherited residual projection feeds parallel learned scalar classifiers.
|
| 4 |
+
Training consensus supplies constants and the exact typed JSON tree. Inference
|
| 5 |
+
combines independently predicted scalar classes, never retrieves whole targets.
|
| 6 |
+
This intentionally rejects variable schemas, array lengths, and unseen classes.
|
| 7 |
+
Native validation and held-out accuracy do not grant semantic or proof authority.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from contextlib import contextmanager
|
| 12 |
+
from copy import deepcopy
|
| 13 |
+
import hashlib
|
| 14 |
+
import math
|
| 15 |
+
from pathlib import Path
|
| 16 |
+
import time
|
| 17 |
+
|
| 18 |
+
from . import source_training_v2 as shared
|
| 19 |
+
from ....optimizers.logic_theorem_optimizer import domain_384_autoencoder as native
|
| 20 |
+
from ....optimizers.logic_theorem_optimizer import modal_latent_formula as legal
|
| 21 |
+
|
| 22 |
+
SCHEMA = "structured-source-384-autoencoder/v1"
|
| 23 |
+
DOMAINS, DIMENSION, FALSE = shared.DOMAINS, 384, native.FALSE
|
| 24 |
+
MAX_BYTES = native.MAX_BYTES
|
| 25 |
+
RIDGES = (.0001, .001, .01, .1)
|
| 26 |
+
PROJECTION_KEYS = ("projection_down.weight", "projection_down.bias", "projection_up.weight", "projection_up.bias")
|
| 27 |
+
_require, _raw, digest = native._require, native._raw, native.digest
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
@contextmanager
|
| 31 |
+
def _numeric():
|
| 32 |
+
import numpy as np
|
| 33 |
+
# Explicitly bound BLAS work without permanently changing caller settings.
|
| 34 |
+
try:
|
| 35 |
+
from threadpoolctl import threadpool_limits
|
| 36 |
+
except ImportError:
|
| 37 |
+
yield np
|
| 38 |
+
else:
|
| 39 |
+
with threadpool_limits(limits=1, user_api="blas"):
|
| 40 |
+
yield np
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def _implementation():
|
| 44 |
+
return {"runtime_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
| 45 |
+
"shared_runtime": shared._implementation()}
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _shape(value):
|
| 49 |
+
if type(value) is dict:
|
| 50 |
+
return {"kind": "object", "fields": [[key, _shape(value[key])] for key in sorted(value)]}
|
| 51 |
+
if type(value) is list:
|
| 52 |
+
return {"kind": "array", "items": [_shape(item) for item in value]}
|
| 53 |
+
names = {str: "string", bool: "boolean", int: "integer", float: "float", type(None): "null"}
|
| 54 |
+
_require(type(value) in names, "non-JSON target scalar")
|
| 55 |
+
return {"kind": names[type(value)]}
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _scalar_leaves(value, path=()):
|
| 59 |
+
if type(value) is dict:
|
| 60 |
+
return {key: leaf for field in sorted(value) for key, leaf in _scalar_leaves(value[field], (*path, field)).items()}
|
| 61 |
+
if type(value) is list:
|
| 62 |
+
return {key: leaf for index, item in enumerate(value) for key, leaf in _scalar_leaves(item, (*path, index)).items()}
|
| 63 |
+
return {path: value}
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def _replace(document, path, value):
|
| 67 |
+
_require(path, "root scalar IR is unsupported")
|
| 68 |
+
target = document
|
| 69 |
+
for part in path[:-1]:
|
| 70 |
+
target = target[part]
|
| 71 |
+
target[path[-1]] = deepcopy(value)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _fit_schema(rows):
|
| 75 |
+
shape = _shape(rows[0]["target"])
|
| 76 |
+
_require(all(_shape(row["target"]) == shape for row in rows),
|
| 77 |
+
"fixed typed JSON tree required; array lengths, keys, and scalar types may not vary")
|
| 78 |
+
leaves = [_scalar_leaves(row["target"]) for row in rows]
|
| 79 |
+
template, slots = deepcopy(rows[0]["target"]), []
|
| 80 |
+
for path in sorted(leaves[0], key=lambda item: _raw(list(item))):
|
| 81 |
+
classes = {_raw(row[path]): row[path] for row in leaves}
|
| 82 |
+
if len(classes) > 1:
|
| 83 |
+
_require(len(classes) <= 512, "too many training classes for one scalar")
|
| 84 |
+
slots.append({"path": list(path), "classes": [deepcopy(classes[key]) for key in sorted(classes)]})
|
| 85 |
+
_replace(template, path, None)
|
| 86 |
+
_require(1 <= len(slots) <= 256, "one to 256 varying training scalar slots required")
|
| 87 |
+
return {"schema": "fixed-typed-json-consensus/v1", "shape": shape, "template": template,
|
| 88 |
+
"slots": slots, "origin": "training_only", "whole_target_memory": False}
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def _targets(np, rows, schema):
|
| 92 |
+
target_ids, width = [], sum(len(slot["classes"]) for slot in schema["slots"])
|
| 93 |
+
_require(width <= 4096, "total training class vocabulary exceeds bound")
|
| 94 |
+
one_hot = np.zeros((len(rows), width), dtype=np.float64)
|
| 95 |
+
for row_index, row in enumerate(rows):
|
| 96 |
+
_require(_shape(row["target"]) == schema["shape"], "target fixed typed JSON tree differs")
|
| 97 |
+
leaves, ids, offset = _scalar_leaves(row["target"]), [], 0
|
| 98 |
+
masked = deepcopy(row["target"])
|
| 99 |
+
for slot in schema["slots"]:
|
| 100 |
+
path = tuple(slot["path"])
|
| 101 |
+
classes = [_raw(value) for value in slot["classes"]]
|
| 102 |
+
value = _raw(leaves[path])
|
| 103 |
+
_require(value in classes, "target scalar outside training vocabulary")
|
| 104 |
+
index = classes.index(value)
|
| 105 |
+
ids.append(index)
|
| 106 |
+
one_hot[row_index, offset+index] = 1.
|
| 107 |
+
offset += len(classes)
|
| 108 |
+
_replace(masked, slot["path"], None)
|
| 109 |
+
_require(_raw(masked) == _raw(schema["template"]), "target differs from training consensus constants")
|
| 110 |
+
target_ids.append(ids)
|
| 111 |
+
return one_hot, target_ids
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _project(np, rows, projection, *, zero_residual=False):
|
| 115 |
+
values = np.asarray([row["embedding"] for row in rows], dtype=np.float64)
|
| 116 |
+
if zero_residual:
|
| 117 |
+
return values
|
| 118 |
+
down = np.asarray(projection["projection_down.weight"], dtype=np.float64)
|
| 119 |
+
down_bias = np.asarray(projection["projection_down.bias"], dtype=np.float64)
|
| 120 |
+
up = np.asarray(projection["projection_up.weight"], dtype=np.float64)
|
| 121 |
+
up_bias = np.asarray(projection["projection_up.bias"], dtype=np.float64)
|
| 122 |
+
projected = values + np.tanh(values @ down.T + down_bias) @ up.T + up_bias
|
| 123 |
+
_require(bool(np.isfinite(projected).all()), "nonfinite projected embedding")
|
| 124 |
+
return projected
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _projection(parent):
|
| 128 |
+
state = {key: deepcopy(parent["model_state"][key]) for key in PROJECTION_KEYS}
|
| 129 |
+
_validate_projection(state, parent["config"]["projection_width"])
|
| 130 |
+
return state
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _validate_projection(state, width):
|
| 134 |
+
import numpy as np
|
| 135 |
+
_require(type(width) is int and 1 <= width <= 64, "invalid inherited projection width")
|
| 136 |
+
_require(type(state) is dict and set(state) == set(PROJECTION_KEYS), "closed inherited projection required")
|
| 137 |
+
expected = dict(zip(PROJECTION_KEYS, ((width, DIMENSION), (width,), (DIMENSION, width), (DIMENSION,))))
|
| 138 |
+
for name, shape in expected.items():
|
| 139 |
+
try:
|
| 140 |
+
value = np.asarray(state[name], dtype=np.float64)
|
| 141 |
+
except (ValueError, TypeError) as exc:
|
| 142 |
+
raise ValueError("invalid projection tensor") from exc
|
| 143 |
+
_require(value.shape == shape and bool(np.isfinite(value).all()), "projection tensor shape or finiteness differs")
|
| 144 |
+
|
| 145 |
+
|
| 146 |
+
def _normalize(np, projected, transform=None):
|
| 147 |
+
if transform is None:
|
| 148 |
+
mean = projected.mean(0)
|
| 149 |
+
scale = max(float(np.sqrt(np.mean(np.sum((projected-mean)**2, axis=1)))), .01)
|
| 150 |
+
transform = {"mean": mean.tolist(), "scale": scale, "origin": "training_projected_embeddings_only"}
|
| 151 |
+
return (projected-np.asarray(transform["mean"])) / transform["scale"], transform
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _assemble(domain, scores, schema):
|
| 155 |
+
reports = []
|
| 156 |
+
for score in scores:
|
| 157 |
+
target, predicted, offset = deepcopy(schema["template"]), [], 0
|
| 158 |
+
for slot in schema["slots"]:
|
| 159 |
+
width = len(slot["classes"])
|
| 160 |
+
index = int(score[offset:offset+width].argmax())
|
| 161 |
+
predicted.append(index)
|
| 162 |
+
_replace(target, slot["path"], slot["classes"][index])
|
| 163 |
+
offset += width
|
| 164 |
+
candidate, reason = None, None
|
| 165 |
+
try:
|
| 166 |
+
candidate = shared.validate_target(domain, target)["canonical_ir"]
|
| 167 |
+
except (ValueError, TypeError, KeyError, RecursionError) as exc:
|
| 168 |
+
reason = str(exc)[:512]
|
| 169 |
+
reports.append({"candidate_ir": candidate, "predicted_classes": predicted, "reason": reason})
|
| 170 |
+
return reports
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
def _score(domain, scores, rows, target_ids, schema):
|
| 174 |
+
generated = _assemble(domain, scores, schema)
|
| 175 |
+
slot_correct = sum(sum(actual == expected for actual, expected in zip(row["predicted_classes"], gold))
|
| 176 |
+
for row, gold in zip(generated, target_ids))
|
| 177 |
+
correct = sum(sum(actual == expected for actual, expected in zip(row["predicted_classes"], gold))
|
| 178 |
+
for row, gold in zip(generated, target_ids) if row["candidate_ir"] is not None)
|
| 179 |
+
count = len(rows)*len(schema["slots"])
|
| 180 |
+
return {"exact_targets": sum(row["candidate_ir"] is not None and _raw(row["candidate_ir"]) == _raw(gold["target"])
|
| 181 |
+
for row, gold in zip(generated, rows)),
|
| 182 |
+
"valid_candidates": sum(row["candidate_ir"] is not None for row in generated), "count": len(rows),
|
| 183 |
+
"semantic_leaf_correct": correct, "semantic_leaf_count": count,
|
| 184 |
+
"semantic_leaf_accuracy": correct/max(count, 1),
|
| 185 |
+
"classifier_slot_correct": slot_correct, "classifier_slot_accuracy": slot_correct/max(count, 1),
|
| 186 |
+
"semantic_metric_scope": "correct_variable_leaves_only_for_native_valid_candidates", "teacher_forcing": False}
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _manifest(rows):
|
| 190 |
+
return [{"id": row["id"], "source_sha256": hashlib.sha256(row["source_text"].encode()).hexdigest(),
|
| 191 |
+
"normalized_source_sha256": hashlib.sha256(" ".join(row["source_text"].casefold().split()).encode()).hexdigest(),
|
| 192 |
+
"embedding_sha256": digest(row["embedding"]), "target_sha256": digest(row["target"])} for row in rows]
|
| 193 |
+
|
| 194 |
+
|
| 195 |
+
def train(domain, training_rows, validation_rows, *, parent_projection, config=None):
|
| 196 |
+
"""Fit parallel classifiers on training data; tuning selects a fixed ridge grid."""
|
| 197 |
+
started = time.monotonic()
|
| 198 |
+
options = {"ridges": list(RIDGES), "embedding_provenance": {"model_id": "caller_supplied", "verified_by_runtime": False}}
|
| 199 |
+
_require(config is None or type(config) is dict and set(config) <= set(options), "unknown structured training option")
|
| 200 |
+
options.update(config or {})
|
| 201 |
+
_require(type(options["ridges"]) is list and 1 <= len(options["ridges"]) <= 16
|
| 202 |
+
and all(type(value) in (int, float) and math.isfinite(value) and 0 < value <= 100 for value in options["ridges"])
|
| 203 |
+
and options["ridges"] == sorted(set(options["ridges"])), "finite increasing positive ridge grid required")
|
| 204 |
+
_require(type(options["embedding_provenance"]) is dict and len(_raw(options["embedding_provenance"])) <= 16384,
|
| 205 |
+
"bounded embedding provenance required")
|
| 206 |
+
training = shared._rows(domain, training_rows, training=True)
|
| 207 |
+
validation = shared._rows(domain, validation_rows, training=True)
|
| 208 |
+
_require(len(training) <= 2048, "dual ridge training is bounded to 2048 rows")
|
| 209 |
+
for key in (lambda row: row["id"], lambda row: " ".join(row["source_text"].casefold().split()), lambda row: digest(row["embedding"])):
|
| 210 |
+
_require(not {key(row) for row in training} & {key(row) for row in validation},
|
| 211 |
+
"training/validation identity, source, or embedding overlap")
|
| 212 |
+
parent, parent_sha, parent_file = shared._parent(parent_projection)
|
| 213 |
+
with native._cpu():
|
| 214 |
+
legal.validate_checkpoint(parent)
|
| 215 |
+
_require(parent["binding"]["dimension"] == DIMENSION and parent["progress"]["optimizer_steps"] > 0,
|
| 216 |
+
"trained 384D Legal parent required")
|
| 217 |
+
projection = _projection(parent)
|
| 218 |
+
schema = _fit_schema(training)
|
| 219 |
+
with _numeric() as np:
|
| 220 |
+
train_targets, _ = _targets(np, training, schema)
|
| 221 |
+
_, validation_ids = _targets(np, validation, schema)
|
| 222 |
+
train_x, transform = _normalize(np, _project(np, training, projection))
|
| 223 |
+
validation_x, _ = _normalize(np, _project(np, validation, projection), transform)
|
| 224 |
+
bias = train_targets.mean(0)
|
| 225 |
+
centered_targets = train_targets-bias
|
| 226 |
+
gram = train_x @ train_x.T
|
| 227 |
+
initial = _score(domain, np.zeros((len(validation), train_targets.shape[1])), validation, validation_ids, schema)
|
| 228 |
+
selected, best_rank, best_weights, history = None, None, None, []
|
| 229 |
+
fit_started = time.monotonic()
|
| 230 |
+
factorization_seconds = validation_seconds = 0.
|
| 231 |
+
for ridge in options["ridges"]:
|
| 232 |
+
tick = time.monotonic()
|
| 233 |
+
# One solve handles every class of every semantic slot. There is
|
| 234 |
+
# no independent factorization per classifier or target document.
|
| 235 |
+
dual = np.linalg.solve(gram + float(ridge)*np.eye(len(training)), centered_targets)
|
| 236 |
+
weights = train_x.T @ dual
|
| 237 |
+
factorization_seconds += time.monotonic()-tick
|
| 238 |
+
_require(bool(np.isfinite(weights).all()), "nonfinite learned decoder weights")
|
| 239 |
+
tick = time.monotonic()
|
| 240 |
+
observed = _score(domain, validation_x @ weights + bias, validation, validation_ids, schema)
|
| 241 |
+
validation_seconds += time.monotonic()-tick
|
| 242 |
+
rank = (observed["exact_targets"], observed["semantic_leaf_correct"])
|
| 243 |
+
chosen = best_rank is None or rank > best_rank
|
| 244 |
+
history.append({"ridge": ridge, **observed, "selected_at_step": chosen})
|
| 245 |
+
if chosen:
|
| 246 |
+
selected, best_rank, best_weights, best = ridge, rank, weights.copy(), observed
|
| 247 |
+
elapsed = time.monotonic()-fit_started
|
| 248 |
+
state = {"weights": best_weights.tolist(), "bias": bias.tolist()}
|
| 249 |
+
metrics = {"selected_ridge": selected, "selected_validation": best, "initial_zero_head_validation": initial,
|
| 250 |
+
"history": history, "factorizations": len(options["ridges"]), "factorization_seconds": factorization_seconds,
|
| 251 |
+
"validation_seconds": validation_seconds, "fit_seconds": elapsed,
|
| 252 |
+
"unique_training_examples": len(training), "fit_unique_examples_per_second": len(training)/max(elapsed, 1e-9),
|
| 253 |
+
"pre_checkpoint_seconds": time.monotonic()-started, "test_used_for_selection": False,
|
| 254 |
+
"selection": "free_running_exact_then_variable_leaf_accuracy_first_ridge_on_ties",
|
| 255 |
+
"optimizer_steps": 0, "gradient_training_used": False}
|
| 256 |
+
checkpoint = {"schema": SCHEMA, "domain_id": domain, "dimension": DIMENSION,
|
| 257 |
+
"implementation": _implementation(), "config": options, "parent_sha256": parent_sha,
|
| 258 |
+
"parent_binding": deepcopy(parent["binding"]), "projection_width": parent["config"]["projection_width"],
|
| 259 |
+
"projection_state": projection, "projection_sha256": digest(projection), "input_transform": transform,
|
| 260 |
+
"target_schema": schema, "head_state": state, "head_sha256": digest(state),
|
| 261 |
+
"training_manifest": _manifest(training), "validation_manifest": _manifest(validation), "training": metrics,
|
| 262 |
+
"lineage": {"parent_encoder_frozen": True, "projection_tensors_inherited_exactly": list(PROJECTION_KEYS),
|
| 263 |
+
"parent_modified": False, "random_parameters_used": False}, **FALSE}
|
| 264 |
+
_require(len(_raw(checkpoint)) <= MAX_BYTES, "checkpoint exceeds bound")
|
| 265 |
+
if parent_file:
|
| 266 |
+
_require(parent_file[0].read_bytes() == parent_file[1], "parent changed during training")
|
| 267 |
+
Runtime(checkpoint)
|
| 268 |
+
return {"checkpoint": checkpoint, "metrics": deepcopy(metrics)}
|
| 269 |
+
|
| 270 |
+
|
| 271 |
+
class Runtime:
|
| 272 |
+
"""Independent learned scalar predictions assembled through a fixed schema."""
|
| 273 |
+
def __init__(self, checkpoint):
|
| 274 |
+
fields = {"schema", "domain_id", "dimension", "implementation", "config", "parent_sha256", "parent_binding",
|
| 275 |
+
"projection_width", "projection_state", "projection_sha256", "input_transform", "target_schema",
|
| 276 |
+
"head_state", "head_sha256", "training_manifest", "validation_manifest", "training", "lineage", *FALSE}
|
| 277 |
+
_require(type(checkpoint) is dict and set(checkpoint) == fields and checkpoint["schema"] == SCHEMA,
|
| 278 |
+
"closed structured source checkpoint required")
|
| 279 |
+
_require(len(_raw(checkpoint)) <= MAX_BYTES, "checkpoint exceeds bound")
|
| 280 |
+
_require(checkpoint["domain_id"] in DOMAINS and type(checkpoint["dimension"]) is int and checkpoint["dimension"] == DIMENSION,
|
| 281 |
+
"checkpoint requires genuine 384D domain")
|
| 282 |
+
_require(all(checkpoint[key] is False for key in FALSE), "checkpoint cannot grant authority")
|
| 283 |
+
_require(checkpoint["implementation"] == _implementation(), "implementation pins differ")
|
| 284 |
+
_require(type(checkpoint["parent_sha256"]) is str and native._SHA.fullmatch(checkpoint["parent_sha256"])
|
| 285 |
+
and type(checkpoint["parent_binding"]) is dict and checkpoint["parent_binding"].get("dimension") == DIMENSION,
|
| 286 |
+
"invalid parent binding")
|
| 287 |
+
_require(digest(checkpoint["projection_state"]) == checkpoint["projection_sha256"], "projection digest differs")
|
| 288 |
+
_validate_projection(checkpoint["projection_state"], checkpoint["projection_width"])
|
| 289 |
+
transform = checkpoint["input_transform"]
|
| 290 |
+
_require(type(transform) is dict and set(transform) == {"mean", "scale", "origin"}
|
| 291 |
+
and transform["origin"] == "training_projected_embeddings_only", "invalid input transform")
|
| 292 |
+
native._vector(transform["mean"])
|
| 293 |
+
_require(type(transform["scale"]) in (int, float) and math.isfinite(transform["scale"]) and .01 <= transform["scale"] <= 1e8,
|
| 294 |
+
"invalid input scale")
|
| 295 |
+
schema = checkpoint["target_schema"]
|
| 296 |
+
_require(type(schema) is dict and set(schema) == {"schema", "shape", "template", "slots", "origin", "whole_target_memory"}
|
| 297 |
+
and schema["schema"] == "fixed-typed-json-consensus/v1" and schema["origin"] == "training_only"
|
| 298 |
+
and schema["whole_target_memory"] is False and type(schema["template"]) is dict, "invalid fixed target schema")
|
| 299 |
+
slots = schema["slots"]
|
| 300 |
+
_require(type(slots) is list and 1 <= len(slots) <= 256, "invalid varying scalar slots")
|
| 301 |
+
candidate, seen = deepcopy(schema["template"]), set()
|
| 302 |
+
canonical_paths = set(_scalar_leaves(schema["template"]))
|
| 303 |
+
for slot in slots:
|
| 304 |
+
_require(type(slot) is dict and set(slot) == {"path", "classes"} and type(slot["path"]) is list
|
| 305 |
+
and 1 <= len(slot["path"]) <= 128 and all(type(part) in (int, str) for part in slot["path"]), "invalid scalar path")
|
| 306 |
+
_require(tuple(slot["path"]) in canonical_paths, "noncanonical scalar path")
|
| 307 |
+
path = _raw(slot["path"])
|
| 308 |
+
_require(path not in seen, "duplicate scalar path")
|
| 309 |
+
seen.add(path)
|
| 310 |
+
classes = slot["classes"]
|
| 311 |
+
_require(type(classes) is list and 2 <= len(classes) <= 512
|
| 312 |
+
and all(type(value) in (str, int, float, bool, type(None)) for value in classes)
|
| 313 |
+
and all(type(value) is type(classes[0]) for value in classes)
|
| 314 |
+
and [_raw(value) for value in classes] == sorted(set(_raw(value) for value in classes)), "invalid scalar classes")
|
| 315 |
+
try:
|
| 316 |
+
existing = schema["template"]
|
| 317 |
+
for part in slot["path"]:
|
| 318 |
+
existing = existing[part]
|
| 319 |
+
_require(existing is None, "varying scalar must use an empty template slot")
|
| 320 |
+
_replace(candidate, slot["path"], classes[0])
|
| 321 |
+
except (TypeError, KeyError, IndexError) as exc:
|
| 322 |
+
raise ValueError("scalar path outside schema") from exc
|
| 323 |
+
_require(_shape(candidate) == schema["shape"], "stored typed target shape differs")
|
| 324 |
+
width = sum(len(slot["classes"]) for slot in slots)
|
| 325 |
+
_require(width <= 4096, "total class vocabulary exceeds bound")
|
| 326 |
+
state = checkpoint["head_state"]
|
| 327 |
+
_require(type(state) is dict and set(state) == {"weights", "bias"} and digest(state) == checkpoint["head_sha256"], "head digest differs")
|
| 328 |
+
with _numeric() as np:
|
| 329 |
+
weights, bias = np.asarray(state["weights"], dtype=np.float64), np.asarray(state["bias"], dtype=np.float64)
|
| 330 |
+
_require(weights.shape == (DIMENSION, width) and bias.shape == (width,)
|
| 331 |
+
and bool(np.isfinite(weights).all()) and bool(np.isfinite(bias).all()), "invalid head tensor shape or finiteness")
|
| 332 |
+
for name in ("training_manifest", "validation_manifest"):
|
| 333 |
+
rows = checkpoint[name]
|
| 334 |
+
_require(type(rows) is list and 1 <= len(rows) <= 4096, "invalid split manifest")
|
| 335 |
+
_require(all(type(row) is dict and set(row) == {"id", "source_sha256", "normalized_source_sha256", "embedding_sha256", "target_sha256"}
|
| 336 |
+
and type(row["id"]) is str and 0 < len(row["id"]) <= 256
|
| 337 |
+
and all(type(row[key]) is str and native._SHA.fullmatch(row[key]) for key in row if key != "id") for row in rows), "invalid split row")
|
| 338 |
+
_require(len({row["id"] for row in rows}) == len(rows), "duplicate split ID")
|
| 339 |
+
for key in ("id", "source_sha256", "normalized_source_sha256", "embedding_sha256"):
|
| 340 |
+
_require(not {row[key] for row in checkpoint["training_manifest"]} & {row[key] for row in checkpoint["validation_manifest"]}, "checkpoint split overlap")
|
| 341 |
+
options = checkpoint["config"]
|
| 342 |
+
_require(type(options) is dict and set(options) == {"ridges", "embedding_provenance"}
|
| 343 |
+
and type(options["ridges"]) is list and 1 <= len(options["ridges"]) <= 16
|
| 344 |
+
and all(type(value) in (int, float) and math.isfinite(value) and 0 < value <= 100 for value in options["ridges"])
|
| 345 |
+
and options["ridges"] == sorted(set(options["ridges"])) and type(options["embedding_provenance"]) is dict,
|
| 346 |
+
"invalid structured config")
|
| 347 |
+
training = checkpoint["training"]
|
| 348 |
+
_require(type(training) is dict and training.get("selected_ridge") in options["ridges"]
|
| 349 |
+
and training.get("test_used_for_selection") is False and training.get("gradient_training_used") is False,
|
| 350 |
+
"invalid training provenance")
|
| 351 |
+
lineage = checkpoint["lineage"]
|
| 352 |
+
_require(lineage == {"parent_encoder_frozen": True, "projection_tensors_inherited_exactly": list(PROJECTION_KEYS),
|
| 353 |
+
"parent_modified": False, "random_parameters_used": False}, "invalid transfer lineage")
|
| 354 |
+
self.checkpoint = deepcopy(checkpoint)
|
| 355 |
+
self.weights, self.bias = weights, bias
|
| 356 |
+
|
| 357 |
+
def describe(self):
|
| 358 |
+
return {"schema": SCHEMA, "domain_id": self.checkpoint["domain_id"], "dimension": DIMENSION,
|
| 359 |
+
"input_representation": "source_embedding_384", "source_text_is_neural_input": False,
|
| 360 |
+
"output_scope": "fixed_typed_json_schema_and_training_scalar_vocabulary",
|
| 361 |
+
"generation": "independent_learned_scalar_classes_assembled_through_training_consensus_schema",
|
| 362 |
+
"sample_memory_used": False, "whole_target_retrieval": False,
|
| 363 |
+
"head_sha256": self.checkpoint["head_sha256"], "projection_sha256": self.checkpoint["projection_sha256"],
|
| 364 |
+
"zero_projection_ablation": "zero_residual_branch_identity_embedding_retained",
|
| 365 |
+
"shuffle_embeddings_ablation": "cyclic_rotation_of_supplied_embedding_batch",
|
| 366 |
+
"independent_source_fidelity_check_required": True, **FALSE}
|
| 367 |
+
|
| 368 |
+
def infer(self, rows, *, weight_ablation=None):
|
| 369 |
+
rows = shared._rows(self.checkpoint["domain_id"], rows, training=False)
|
| 370 |
+
_require(weight_ablation in (None, "zero_head", "zero_projection", "shuffle_embeddings"), "unknown weight ablation")
|
| 371 |
+
if weight_ablation == "shuffle_embeddings":
|
| 372 |
+
_require(len(rows) > 1, "embedding shuffle requires at least two rows")
|
| 373 |
+
original = [row["embedding"] for row in rows]
|
| 374 |
+
for index, row in enumerate(rows):
|
| 375 |
+
row["embedding"] = original[(index+1) % len(rows)]
|
| 376 |
+
with _numeric() as np:
|
| 377 |
+
projected = _project(np, rows, self.checkpoint["projection_state"], zero_residual=weight_ablation == "zero_projection")
|
| 378 |
+
data, _ = _normalize(np, projected, self.checkpoint["input_transform"])
|
| 379 |
+
scores = (np.zeros((len(rows), len(self.bias))) if weight_ablation == "zero_head" else data @ self.weights + self.bias)
|
| 380 |
+
_require(bool(np.isfinite(scores).all()), "nonfinite classifier scores")
|
| 381 |
+
generated = _assemble(self.checkpoint["domain_id"], scores, self.checkpoint["target_schema"])
|
| 382 |
+
reports = []
|
| 383 |
+
for row, prediction, embedding in zip(rows, generated, projected):
|
| 384 |
+
reports.append({"id": row["id"], "source_sha256": hashlib.sha256(row["source_text"].encode()).hexdigest(),
|
| 385 |
+
**prediction, "status": "unqualified_candidate" if prediction["candidate_ir"] is not None else "fail_open_invalid_output",
|
| 386 |
+
"projected_embedding": embedding.tolist(), "weight_ablation": weight_ablation,
|
| 387 |
+
"head_sha256": self.checkpoint["head_sha256"], "projection_sha256": self.checkpoint["projection_sha256"],
|
| 388 |
+
"target_access": False, "teacher_forcing": False, "continue_planning": True, **FALSE})
|
| 389 |
+
return {"schema": SCHEMA, "domain_id": self.checkpoint["domain_id"], "dimension": DIMENSION, "rows": reports, **FALSE}
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def evaluate(checkpoint, rows, *, weight_ablation=None):
|
| 393 |
+
"""Count every gold row, including targets outside the fitted decoder scope."""
|
| 394 |
+
gold = shared._rows(checkpoint["domain_id"], rows, training=True)
|
| 395 |
+
coverage = []
|
| 396 |
+
with _numeric() as np:
|
| 397 |
+
for row in gold:
|
| 398 |
+
try:
|
| 399 |
+
_targets(np, [row], checkpoint["target_schema"])
|
| 400 |
+
coverage.append((True, None))
|
| 401 |
+
except ValueError as exc:
|
| 402 |
+
coverage.append((False, str(exc)))
|
| 403 |
+
report = Runtime(checkpoint).infer([{key: row[key] for key in ("id", "source_text", "embedding")} for row in gold], weight_ablation=weight_ablation)
|
| 404 |
+
correct = slot_correct = 0
|
| 405 |
+
for actual, expected, (supported, reason) in zip(report["rows"], gold, coverage):
|
| 406 |
+
actual["exact_target"] = actual["candidate_ir"] is not None and _raw(actual["candidate_ir"]) == _raw(expected["target"])
|
| 407 |
+
actual["within_training_coverage"], actual["target_coverage_reason"] = supported, reason
|
| 408 |
+
leaves = _scalar_leaves(expected["target"])
|
| 409 |
+
for slot, predicted in zip(checkpoint["target_schema"]["slots"], actual["predicted_classes"]):
|
| 410 |
+
path = tuple(slot["path"])
|
| 411 |
+
matches = path in leaves and _raw(slot["classes"][predicted]) == _raw(leaves[path])
|
| 412 |
+
slot_correct += matches
|
| 413 |
+
correct += matches and actual["candidate_ir"] is not None
|
| 414 |
+
count = len(gold)*len(checkpoint["target_schema"]["slots"])
|
| 415 |
+
return {**report, "count": len(gold), "exact_targets": sum(row["exact_target"] for row in report["rows"]),
|
| 416 |
+
"valid_candidates": sum(row["candidate_ir"] is not None for row in report["rows"]),
|
| 417 |
+
"within_training_coverage": sum(supported for supported, _ in coverage),
|
| 418 |
+
"outside_training_coverage": sum(not supported for supported, _ in coverage),
|
| 419 |
+
"semantic_leaf_correct": correct, "semantic_leaf_count": count, "semantic_leaf_accuracy": correct/max(count, 1),
|
| 420 |
+
"classifier_slot_correct": slot_correct, "classifier_slot_accuracy": slot_correct/max(count, 1),
|
| 421 |
+
"semantic_metric_scope": "correct_variable_leaves_only_for_native_valid_candidates"}
|
| 422 |
+
|
| 423 |
+
|
| 424 |
+
def load_checkpoint(path, *, expected_sha256, expected_domain):
|
| 425 |
+
path = Path(path)
|
| 426 |
+
_require(path.is_file() and not path.is_symlink() and 0 < path.stat().st_size <= MAX_BYTES, "bounded regular checkpoint required")
|
| 427 |
+
raw = path.read_bytes()
|
| 428 |
+
_require(hashlib.sha256(raw).hexdigest() == expected_sha256, "checkpoint bytes differ")
|
| 429 |
+
checkpoint = native._parse(raw)
|
| 430 |
+
_require(type(checkpoint) is dict and checkpoint.get("domain_id") == expected_domain, "checkpoint belongs to another domain")
|
| 431 |
+
return Runtime(checkpoint)
|
| 432 |
+
|
| 433 |
+
|
| 434 |
+
__all__ = ["SCHEMA", "DOMAINS", "DIMENSION", "RIDGES", "train", "Runtime", "evaluate", "load_checkpoint"]
|
releases/20261004-retained-checkpoints-v1/source/587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d/ipfs_datasets_py/logic/autoformal/tree_pin.py
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fail closed when the legal compiler resolves outside this checkout.
|
| 2 |
+
|
| 3 |
+
The check does not rewrite ``sys.path`` and does not retarget an editable
|
| 4 |
+
install. Callers that need this tree put it on the path themselves.
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import importlib
|
| 10 |
+
from pathlib import Path
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class LogicTreePinError(RuntimeError):
|
| 14 |
+
"""The compiler, decompiler, or parser loaded from a different checkout."""
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def workspace_root() -> Path:
|
| 18 |
+
"""Return ``external/ipfs_datasets`` for this file's checkout."""
|
| 19 |
+
|
| 20 |
+
return Path(__file__).resolve().parents[3]
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
_MODULES = (
|
| 24 |
+
("compiler", "ipfs_datasets_py.logic.legal_ir.canonical_compiler"),
|
| 25 |
+
("decompiler", "ipfs_datasets_py.logic.legal_ir.canonical_decompiler"),
|
| 26 |
+
("parser", "ipfs_datasets_py.logic.deontic.utils.deontic_parser"),
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def require_workspace_logic_tree() -> dict[str, str]:
|
| 31 |
+
"""Import the compiler, decompiler, and parser and require this checkout.
|
| 32 |
+
|
| 33 |
+
Prints one resolved-path line. Raises ``LogicTreePinError`` when any
|
| 34 |
+
module file sits outside ``workspace_root()``.
|
| 35 |
+
"""
|
| 36 |
+
|
| 37 |
+
root = workspace_root()
|
| 38 |
+
resolved: dict[str, str] = {}
|
| 39 |
+
outside: list[str] = []
|
| 40 |
+
for label, name in _MODULES:
|
| 41 |
+
module = importlib.import_module(name)
|
| 42 |
+
raw = getattr(module, "__file__", "") or ""
|
| 43 |
+
path = Path(raw).resolve() if raw else Path()
|
| 44 |
+
resolved[label] = str(path)
|
| 45 |
+
if not path.is_file() or root not in path.parents:
|
| 46 |
+
outside.append(f"{label}={path}")
|
| 47 |
+
if outside:
|
| 48 |
+
raise LogicTreePinError(
|
| 49 |
+
"Legal compiler, decompiler, and parser must load from "
|
| 50 |
+
f"{root}. Resolved outside that tree: {', '.join(outside)}. "
|
| 51 |
+
"Put that tree first on PYTHONPATH, or point the editable install "
|
| 52 |
+
"at it. This check does not rewrite the install."
|
| 53 |
+
)
|
| 54 |
+
print("logic tree pin " + " ".join(f"{label}={path}" for label, path in resolved.items()))
|
| 55 |
+
return resolved
|
releases/20261004-retained-checkpoints-v1/source/66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py
ADDED
|
@@ -0,0 +1,919 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Experimental source-embedding conditioned native IR decoding at 384 dimensions.
|
| 2 |
+
|
| 3 |
+
Reuses modal_latent_formula's residual projection, conditioning layer and GRU.
|
| 4 |
+
A trained Legal checkpoint supplies every recurrent/projection tensor. New
|
| 5 |
+
target-token rows receive trained parent lexical means, never random weights.
|
| 6 |
+
|
| 7 |
+
Generated documents and fragments remain unqualified candidates. Native shape
|
| 8 |
+
validation establishes neither source fidelity nor proof correctness.
|
| 9 |
+
"""
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
from contextlib import contextmanager
|
| 13 |
+
from copy import deepcopy
|
| 14 |
+
from dataclasses import fields
|
| 15 |
+
import hashlib
|
| 16 |
+
import json
|
| 17 |
+
import math
|
| 18 |
+
from pathlib import Path
|
| 19 |
+
import re
|
| 20 |
+
import threading
|
| 21 |
+
import time
|
| 22 |
+
|
| 23 |
+
SCHEMA = "domain-384-typed-autoencoder/v1"
|
| 24 |
+
DIMENSION = 384
|
| 25 |
+
DOMAINS = ("intent_ir", "security_ir", "ui_ux_ir")
|
| 26 |
+
MAX_BYTES = 48 * 1024 * 1024
|
| 27 |
+
SPECIAL = ("<pad>", "<bos>", "<eos>")
|
| 28 |
+
FALSE = {
|
| 29 |
+
"qualified": False,
|
| 30 |
+
"admitted": False,
|
| 31 |
+
"proof_authority": False,
|
| 32 |
+
"source_semantics_verified": False,
|
| 33 |
+
"publication_performed": False,
|
| 34 |
+
}
|
| 35 |
+
_TOKEN = re.compile(
|
| 36 |
+
r'"(?:[^"\\\x00-\x1f]|\\(?:["\\/bfnrt]|u[0-9a-fA-F]{4}))*"'
|
| 37 |
+
r'|-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?'
|
| 38 |
+
r'|true|false|null|[{}\[\],:]'
|
| 39 |
+
)
|
| 40 |
+
_SHA = re.compile(r"[0-9a-f]{64}\Z")
|
| 41 |
+
_CPU_LOCK = threading.RLock()
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _require(condition, message):
|
| 45 |
+
if not condition:
|
| 46 |
+
raise ValueError(message)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _raw(value):
|
| 50 |
+
return json.dumps(
|
| 51 |
+
value, sort_keys=True, separators=(",", ":"),
|
| 52 |
+
ensure_ascii=True, allow_nan=False,
|
| 53 |
+
).encode()
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def digest(value):
|
| 57 |
+
return hashlib.sha256(_raw(value)).hexdigest()
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _parse(raw):
|
| 61 |
+
def unique(pairs):
|
| 62 |
+
result = {}
|
| 63 |
+
for key, value in pairs:
|
| 64 |
+
_require(key not in result, "duplicate JSON key")
|
| 65 |
+
result[key] = value
|
| 66 |
+
return result
|
| 67 |
+
|
| 68 |
+
def invalid(_):
|
| 69 |
+
raise ValueError("nonfinite JSON value")
|
| 70 |
+
|
| 71 |
+
return json.loads(raw, object_pairs_hook=unique, parse_constant=invalid)
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
def _preserved(original, native):
|
| 75 |
+
"""Reject fields silently dropped or coerced by permissive native loaders."""
|
| 76 |
+
if type(original) is dict:
|
| 77 |
+
return (
|
| 78 |
+
type(native) is dict
|
| 79 |
+
and all(k in native and _preserved(v, native[k])
|
| 80 |
+
for k, v in original.items())
|
| 81 |
+
)
|
| 82 |
+
if type(original) is list:
|
| 83 |
+
return (
|
| 84 |
+
type(native) is list
|
| 85 |
+
and len(original) == len(native)
|
| 86 |
+
and all(_preserved(a, b) for a, b in zip(original, native))
|
| 87 |
+
)
|
| 88 |
+
return type(original) is type(native) and original == native
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
def validate_target(domain, target):
|
| 92 |
+
"""Validate a compact native document or explicitly named native fragment.
|
| 93 |
+
|
| 94 |
+
Supported fragment wrappers are ``{kind, document}`` with kinds
|
| 95 |
+
``intent_rich_ast``, ``program_expression`` or ``ui_component``.
|
| 96 |
+
|
| 97 |
+
ProgramExpression validation is local: references still require a complete
|
| 98 |
+
ProgramIR to establish referential and type correctness. Missing defaults
|
| 99 |
+
may be omitted; supplied fields must survive the native loader exactly.
|
| 100 |
+
"""
|
| 101 |
+
_require(
|
| 102 |
+
domain in DOMAINS and type(target) is dict,
|
| 103 |
+
"supported domain and typed target required",
|
| 104 |
+
)
|
| 105 |
+
_require(len(_raw(target)) <= 128 * 1024, "target exceeds bound")
|
| 106 |
+
kind, document = "document", target
|
| 107 |
+
if set(target) == {"kind", "document"}:
|
| 108 |
+
kind, document = target["kind"], target["document"]
|
| 109 |
+
_require(type(document) is dict, "fragment document must be an object")
|
| 110 |
+
|
| 111 |
+
if domain == "intent_ir":
|
| 112 |
+
if kind == "intent_rich_ast":
|
| 113 |
+
from ...logic.intent_ir.formalize.rich_grammar import validate_ast
|
| 114 |
+
native = deepcopy(validate_ast(document))
|
| 115 |
+
else:
|
| 116 |
+
_require(kind == "document", "unsupported Intent fragment")
|
| 117 |
+
from ...logic.intent_ir.decoder import decode_intent_ir
|
| 118 |
+
native = decode_intent_ir(document).to_dict()
|
| 119 |
+
elif domain == "security_ir":
|
| 120 |
+
if kind == "program_expression":
|
| 121 |
+
from ...logic.software_verification.program import ProgramExpression
|
| 122 |
+
native = ProgramExpression.from_dict(document).to_dict()
|
| 123 |
+
else:
|
| 124 |
+
_require(kind == "document", "unsupported Security fragment")
|
| 125 |
+
from ...logic.security_ir.model import SecurityIR
|
| 126 |
+
native = SecurityIR.from_dict(document).to_dict()
|
| 127 |
+
else:
|
| 128 |
+
if kind == "ui_component":
|
| 129 |
+
from ...logic.ui_ux_ir.schema import UIComponent
|
| 130 |
+
_require(
|
| 131 |
+
set(document) <= {field.name for field in fields(UIComponent)},
|
| 132 |
+
"unknown UI component field",
|
| 133 |
+
)
|
| 134 |
+
values = deepcopy(document)
|
| 135 |
+
for key, value in tuple(values.items()):
|
| 136 |
+
if key.endswith("_ids"):
|
| 137 |
+
_require(type(value) is list, "UI ID arrays must be lists")
|
| 138 |
+
values[key] = tuple(value)
|
| 139 |
+
component = UIComponent(**values)
|
| 140 |
+
component.validate()
|
| 141 |
+
native = component.to_dict()
|
| 142 |
+
else:
|
| 143 |
+
_require(kind == "document", "unsupported UI fragment")
|
| 144 |
+
from ...logic.ui_ux_ir.decoder import decode_ui_ir
|
| 145 |
+
native = decode_ui_ir(document).to_dict()
|
| 146 |
+
|
| 147 |
+
_require(
|
| 148 |
+
_preserved(document, native),
|
| 149 |
+
"native decoder dropped, reordered, or coerced target fields",
|
| 150 |
+
)
|
| 151 |
+
return {
|
| 152 |
+
"valid": True,
|
| 153 |
+
"domain_id": domain,
|
| 154 |
+
"kind": kind,
|
| 155 |
+
"canonical_ir": _parse(_raw(target)),
|
| 156 |
+
"native_ir": native,
|
| 157 |
+
"scope": (
|
| 158 |
+
"native_document" if kind == "document"
|
| 159 |
+
else "locally_validated_native_fragment"
|
| 160 |
+
),
|
| 161 |
+
**FALSE,
|
| 162 |
+
}
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _implementation():
|
| 166 |
+
from . import modal_latent_formula
|
| 167 |
+
from ...logic.intent_ir import decoder as intent_decoder, schema as intent_schema
|
| 168 |
+
from ...logic.intent_ir.formalize import rich_grammar
|
| 169 |
+
from ...logic.security_ir import model as security_model
|
| 170 |
+
from ...logic.software_verification import program
|
| 171 |
+
from ...logic.ui_ux_ir import decoder as ui_decoder, schema as ui_schema
|
| 172 |
+
|
| 173 |
+
modules = (
|
| 174 |
+
modal_latent_formula, intent_decoder, intent_schema, rich_grammar,
|
| 175 |
+
security_model, program, ui_decoder, ui_schema,
|
| 176 |
+
)
|
| 177 |
+
return {
|
| 178 |
+
"runtime": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
| 179 |
+
"dependencies": {
|
| 180 |
+
module.__name__: hashlib.sha256(Path(module.__file__).read_bytes()).hexdigest()
|
| 181 |
+
for module in modules
|
| 182 |
+
},
|
| 183 |
+
"scope": "listed_numerical_and_native_validator_modules_only",
|
| 184 |
+
}
|
| 185 |
+
|
| 186 |
+
|
| 187 |
+
@contextmanager
|
| 188 |
+
def _cpu():
|
| 189 |
+
"""Serialize this runtime's thread-count changes and restore caller state."""
|
| 190 |
+
import torch
|
| 191 |
+
with _CPU_LOCK:
|
| 192 |
+
previous = torch.get_num_threads()
|
| 193 |
+
torch.set_num_threads(1)
|
| 194 |
+
try:
|
| 195 |
+
yield torch
|
| 196 |
+
finally:
|
| 197 |
+
torch.set_num_threads(previous)
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _vector(value):
|
| 201 |
+
_require(
|
| 202 |
+
type(value) is list
|
| 203 |
+
and len(value) == DIMENSION
|
| 204 |
+
and all(
|
| 205 |
+
type(number) in (int, float)
|
| 206 |
+
and math.isfinite(number)
|
| 207 |
+
and abs(number) <= 1e6
|
| 208 |
+
for number in value
|
| 209 |
+
),
|
| 210 |
+
"embedding must contain exactly 384 bounded finite numbers",
|
| 211 |
+
)
|
| 212 |
+
|
| 213 |
+
|
| 214 |
+
def _rows(domain, rows, *, training):
|
| 215 |
+
_require(
|
| 216 |
+
type(rows) is list and 1 <= len(rows) <= 4096,
|
| 217 |
+
"bounded nonempty rows required",
|
| 218 |
+
)
|
| 219 |
+
expected = {"id", "source_text", "embedding"} | (
|
| 220 |
+
{"target"} if training else set()
|
| 221 |
+
)
|
| 222 |
+
seen = set()
|
| 223 |
+
for row in rows:
|
| 224 |
+
_require(
|
| 225 |
+
type(row) is dict and set(row) == expected,
|
| 226 |
+
"closed domain row schema required",
|
| 227 |
+
)
|
| 228 |
+
_require(
|
| 229 |
+
type(row["id"]) is str
|
| 230 |
+
and 0 < len(row["id"]) <= 256
|
| 231 |
+
and row["id"] not in seen,
|
| 232 |
+
"unique bounded row ID required",
|
| 233 |
+
)
|
| 234 |
+
_require(
|
| 235 |
+
type(row["source_text"]) is str
|
| 236 |
+
and 0 < len(row["source_text"]) <= 16384
|
| 237 |
+
and row["source_text"].strip(),
|
| 238 |
+
"bounded nonempty source provenance required",
|
| 239 |
+
)
|
| 240 |
+
_vector(row["embedding"])
|
| 241 |
+
if training:
|
| 242 |
+
validate_target(domain, row["target"])
|
| 243 |
+
seen.add(row["id"])
|
| 244 |
+
return deepcopy(rows)
|
| 245 |
+
|
| 246 |
+
|
| 247 |
+
def _tokens(target):
|
| 248 |
+
raw = _raw(target).decode()
|
| 249 |
+
pieces = _TOKEN.findall(raw)
|
| 250 |
+
_require(
|
| 251 |
+
"".join(pieces) == raw and len(pieces) <= 1022,
|
| 252 |
+
"bounded JSON lexical target required",
|
| 253 |
+
)
|
| 254 |
+
return pieces
|
| 255 |
+
|
| 256 |
+
|
| 257 |
+
def _config(options, parent_config):
|
| 258 |
+
defaults = {
|
| 259 |
+
"epochs": 80,
|
| 260 |
+
"max_seconds": 180.0,
|
| 261 |
+
"learning_rate": .003,
|
| 262 |
+
"batch_size": 8,
|
| 263 |
+
"seed": 1729,
|
| 264 |
+
"patience": 12,
|
| 265 |
+
"reconstruction_weight": .1,
|
| 266 |
+
"max_target_tokens": 512,
|
| 267 |
+
"embedding_provenance": {
|
| 268 |
+
"model_id": "caller_supplied",
|
| 269 |
+
"verified_by_runtime": False,
|
| 270 |
+
},
|
| 271 |
+
}
|
| 272 |
+
_require(
|
| 273 |
+
options is None
|
| 274 |
+
or type(options) is dict and set(options) <= set(defaults),
|
| 275 |
+
"unknown training option",
|
| 276 |
+
)
|
| 277 |
+
defaults.update(options or {})
|
| 278 |
+
for name, high in (
|
| 279 |
+
("epochs", 1000), ("batch_size", 64), ("seed", 2**31 - 1),
|
| 280 |
+
("patience", 1000), ("max_target_tokens", 1024),
|
| 281 |
+
):
|
| 282 |
+
value = defaults[name]
|
| 283 |
+
_require(
|
| 284 |
+
type(value) is int
|
| 285 |
+
and (0 if name == "seed" else 1) <= value <= high,
|
| 286 |
+
"invalid " + name,
|
| 287 |
+
)
|
| 288 |
+
for name, high in (
|
| 289 |
+
("max_seconds", 3600),
|
| 290 |
+
("learning_rate", .1),
|
| 291 |
+
("reconstruction_weight", 100),
|
| 292 |
+
):
|
| 293 |
+
value = defaults[name]
|
| 294 |
+
_require(
|
| 295 |
+
type(value) in (int, float)
|
| 296 |
+
and math.isfinite(value)
|
| 297 |
+
and 0 < value <= high,
|
| 298 |
+
"invalid " + name,
|
| 299 |
+
)
|
| 300 |
+
_require(
|
| 301 |
+
type(defaults["embedding_provenance"]) is dict
|
| 302 |
+
and len(_raw(defaults["embedding_provenance"])) <= 16384,
|
| 303 |
+
"bounded embedding provenance required",
|
| 304 |
+
)
|
| 305 |
+
return {
|
| 306 |
+
**defaults,
|
| 307 |
+
**{
|
| 308 |
+
name: parent_config[name]
|
| 309 |
+
for name in ("hidden_size", "token_embedding_dim", "projection_width")
|
| 310 |
+
},
|
| 311 |
+
}
|
| 312 |
+
|
| 313 |
+
|
| 314 |
+
def _transfer(parent, codec, config):
|
| 315 |
+
from . import modal_latent_formula as numerical
|
| 316 |
+
import torch
|
| 317 |
+
|
| 318 |
+
model = numerical._model({"dimension": DIMENSION}, codec, config)
|
| 319 |
+
prior = parent["model_state"]
|
| 320 |
+
old_vocab = parent["codec"]["target_vocabulary"]
|
| 321 |
+
positions = {token: index for index, token in enumerate(old_vocab)}
|
| 322 |
+
lexical = {"target_embedding.weight", "output.weight", "output.bias"}
|
| 323 |
+
transferred, inherited, mapped = {}, [], []
|
| 324 |
+
for name, template in model.state_dict().items():
|
| 325 |
+
_require(name in prior, "parent is missing numerical tensor " + name)
|
| 326 |
+
value = torch.tensor(prior[name], dtype=torch.float32)
|
| 327 |
+
_require(bool(torch.isfinite(value).all()), "nonfinite parent tensor")
|
| 328 |
+
if name in lexical:
|
| 329 |
+
_require(
|
| 330 |
+
value.shape[0] == len(old_vocab)
|
| 331 |
+
and value.shape[1:] == template.shape[1:],
|
| 332 |
+
"parent lexical shape differs",
|
| 333 |
+
)
|
| 334 |
+
mean = value.mean(0)
|
| 335 |
+
value = torch.stack([
|
| 336 |
+
value[positions[token]] if token in positions else mean
|
| 337 |
+
for token in codec["target_vocabulary"]
|
| 338 |
+
])
|
| 339 |
+
mapped.append(name)
|
| 340 |
+
else:
|
| 341 |
+
_require(value.shape == template.shape, "parent architecture differs")
|
| 342 |
+
inherited.append(name)
|
| 343 |
+
transferred[name] = value
|
| 344 |
+
model.load_state_dict(transferred, strict=True)
|
| 345 |
+
return model, {
|
| 346 |
+
"exact_inherited_tensors": sorted(inherited),
|
| 347 |
+
"lexical_mapped_tensors": sorted(mapped),
|
| 348 |
+
"new_token_initialization": "trained_parent_lexical_row_mean",
|
| 349 |
+
"random_parameters_used": False,
|
| 350 |
+
"parent_modified": False,
|
| 351 |
+
"initial_state_sha256": digest({
|
| 352 |
+
name: tensor.tolist() for name, tensor in transferred.items()
|
| 353 |
+
}),
|
| 354 |
+
}
|
| 355 |
+
|
| 356 |
+
|
| 357 |
+
def _batch(torch, rows, vocabulary, max_tokens):
|
| 358 |
+
positions = {token: index for index, token in enumerate(vocabulary)}
|
| 359 |
+
encoded = []
|
| 360 |
+
for row in rows:
|
| 361 |
+
tokens = _tokens(row["target"])
|
| 362 |
+
_require(
|
| 363 |
+
len(tokens) + 2 <= max_tokens,
|
| 364 |
+
"target exceeds configured token limit",
|
| 365 |
+
)
|
| 366 |
+
missing = sorted(set(tokens) - set(positions))
|
| 367 |
+
_require(
|
| 368 |
+
not missing,
|
| 369 |
+
"target token outside training vocabulary: " + str(missing[:3]),
|
| 370 |
+
)
|
| 371 |
+
encoded.append([1] + [positions[token] for token in tokens] + [2])
|
| 372 |
+
width = max(map(len, encoded))
|
| 373 |
+
return (
|
| 374 |
+
torch.tensor([row["embedding"] for row in rows], dtype=torch.float32),
|
| 375 |
+
torch.tensor([
|
| 376 |
+
row + [0] * (width - len(row)) for row in encoded
|
| 377 |
+
], dtype=torch.long),
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
|
| 381 |
+
def _loss(torch, model, data, targets, config):
|
| 382 |
+
projected, logits = model(data, targets[:, :-1])
|
| 383 |
+
ce = torch.nn.functional.cross_entropy(
|
| 384 |
+
logits.reshape(-1, logits.shape[-1]),
|
| 385 |
+
targets[:, 1:].reshape(-1),
|
| 386 |
+
ignore_index=0,
|
| 387 |
+
)
|
| 388 |
+
mse = torch.nn.functional.mse_loss(projected, data)
|
| 389 |
+
return ce + config["reconstruction_weight"] * mse, ce, mse
|
| 390 |
+
|
| 391 |
+
|
| 392 |
+
def _metrics(torch, model, batch, config):
|
| 393 |
+
with torch.inference_mode():
|
| 394 |
+
loss, ce, mse = _loss(torch, model, *batch, config)
|
| 395 |
+
_require(
|
| 396 |
+
all(bool(torch.isfinite(value)) for value in (loss, ce, mse)),
|
| 397 |
+
"nonfinite evaluation",
|
| 398 |
+
)
|
| 399 |
+
return {
|
| 400 |
+
"objective": float(loss),
|
| 401 |
+
"token_cross_entropy": float(ce),
|
| 402 |
+
"embedding_mse": float(mse),
|
| 403 |
+
}
|
| 404 |
+
|
| 405 |
+
|
| 406 |
+
def train(domain, training_rows, validation_rows, *, parent_projection, config=None):
|
| 407 |
+
"""Fork a trained Legal 384D projection into a distinct domain checkpoint.
|
| 408 |
+
|
| 409 |
+
parent_projection is a complete modal-latent-formula checkpoint or its
|
| 410 |
+
{path, sha256} descriptor. Only embeddings condition the neural decoder.
|
| 411 |
+
Validation selects weights; test examples never enter this API.
|
| 412 |
+
"""
|
| 413 |
+
from . import modal_latent_formula as numerical
|
| 414 |
+
|
| 415 |
+
original_parent = None
|
| 416 |
+
if type(parent_projection) is dict and set(parent_projection) == {"path", "sha256"}:
|
| 417 |
+
parent_path = Path(parent_projection["path"])
|
| 418 |
+
_require(
|
| 419 |
+
parent_path.is_file() and parent_path.stat().st_size <= MAX_BYTES,
|
| 420 |
+
"bounded parent file required",
|
| 421 |
+
)
|
| 422 |
+
original_parent = parent_path.read_bytes()
|
| 423 |
+
_require(
|
| 424 |
+
hashlib.sha256(original_parent).hexdigest() == parent_projection["sha256"],
|
| 425 |
+
"parent hash differs",
|
| 426 |
+
)
|
| 427 |
+
parent = _parse(original_parent)
|
| 428 |
+
parent_sha = parent_projection["sha256"]
|
| 429 |
+
else:
|
| 430 |
+
parent = deepcopy(parent_projection)
|
| 431 |
+
parent_sha = digest(parent)
|
| 432 |
+
|
| 433 |
+
with _cpu() as torch:
|
| 434 |
+
numerical.validate_checkpoint(parent)
|
| 435 |
+
_require(
|
| 436 |
+
parent["binding"]["dimension"] == DIMENSION
|
| 437 |
+
and parent["progress"]["optimizer_steps"] > 0,
|
| 438 |
+
"trained 384D Legal parent required",
|
| 439 |
+
)
|
| 440 |
+
train_rows = _rows(domain, training_rows, training=True)
|
| 441 |
+
validation = _rows(domain, validation_rows, training=True)
|
| 442 |
+
keys = (
|
| 443 |
+
lambda row: row["id"],
|
| 444 |
+
lambda row: " ".join(row["source_text"].casefold().split()),
|
| 445 |
+
lambda row: digest(row["embedding"]),
|
| 446 |
+
)
|
| 447 |
+
for key in keys:
|
| 448 |
+
_require(
|
| 449 |
+
not {key(row) for row in train_rows}
|
| 450 |
+
& {key(row) for row in validation},
|
| 451 |
+
"training/validation identity, source, or embedding overlap",
|
| 452 |
+
)
|
| 453 |
+
|
| 454 |
+
options = _config(config, parent["config"])
|
| 455 |
+
vocabulary = [
|
| 456 |
+
*SPECIAL,
|
| 457 |
+
*sorted({
|
| 458 |
+
token
|
| 459 |
+
for row in train_rows
|
| 460 |
+
for token in _tokens(row["target"])
|
| 461 |
+
}),
|
| 462 |
+
]
|
| 463 |
+
_require(len(vocabulary) <= 4096, "training vocabulary exceeds bound")
|
| 464 |
+
codec = {
|
| 465 |
+
"schema": "typed-json-lexical/v1",
|
| 466 |
+
"target_vocabulary": vocabulary,
|
| 467 |
+
}
|
| 468 |
+
data, labels = _batch(
|
| 469 |
+
torch, train_rows, vocabulary, options["max_target_tokens"]
|
| 470 |
+
)
|
| 471 |
+
validation_batch = _batch(
|
| 472 |
+
torch, validation, vocabulary, options["max_target_tokens"]
|
| 473 |
+
)
|
| 474 |
+
model, lineage = _transfer(parent, codec, options)
|
| 475 |
+
optimizer = torch.optim.Adam(
|
| 476 |
+
model.parameters(), lr=options["learning_rate"]
|
| 477 |
+
)
|
| 478 |
+
before = _metrics(torch, model, validation_batch, options)
|
| 479 |
+
best, best_state, selected_epoch = before, deepcopy(model.state_dict()), 0
|
| 480 |
+
generator = torch.Generator().manual_seed(options["seed"])
|
| 481 |
+
started = time.monotonic()
|
| 482 |
+
steps = seen_tokens = examples_seen = stale = 0
|
| 483 |
+
optimizer_seconds = validation_seconds = 0.0
|
| 484 |
+
history, stop = [], "epoch_budget"
|
| 485 |
+
|
| 486 |
+
for epoch in range(options["epochs"]):
|
| 487 |
+
model.train()
|
| 488 |
+
order = torch.randperm(len(train_rows), generator=generator)
|
| 489 |
+
complete = True
|
| 490 |
+
for offset in range(0, len(train_rows), options["batch_size"]):
|
| 491 |
+
if time.monotonic() - started >= options["max_seconds"]:
|
| 492 |
+
complete, stop = False, "deadline"
|
| 493 |
+
break
|
| 494 |
+
step_started = time.monotonic()
|
| 495 |
+
index = order[offset:offset + options["batch_size"]]
|
| 496 |
+
batch_target = labels[index]
|
| 497 |
+
width = int((batch_target != 0).sum(1).max())
|
| 498 |
+
batch_target = batch_target[:, :width]
|
| 499 |
+
optimizer.zero_grad(set_to_none=True)
|
| 500 |
+
loss, _, _ = _loss(
|
| 501 |
+
torch, model, data[index], batch_target, options
|
| 502 |
+
)
|
| 503 |
+
_require(bool(torch.isfinite(loss)), "nonfinite training loss")
|
| 504 |
+
loss.backward()
|
| 505 |
+
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 5.0)
|
| 506 |
+
_require(bool(torch.isfinite(norm)), "nonfinite gradient")
|
| 507 |
+
optimizer.step()
|
| 508 |
+
optimizer_seconds += time.monotonic() - step_started
|
| 509 |
+
steps += 1
|
| 510 |
+
examples_seen += len(index)
|
| 511 |
+
seen_tokens += int((batch_target[:, 1:] != 0).sum())
|
| 512 |
+
if not complete:
|
| 513 |
+
break
|
| 514 |
+
|
| 515 |
+
validation_started = time.monotonic()
|
| 516 |
+
observed = _metrics(torch, model, validation_batch, options)
|
| 517 |
+
validation_seconds += time.monotonic() - validation_started
|
| 518 |
+
# A deadline-truncated epoch cannot become the selected checkpoint.
|
| 519 |
+
selected = (
|
| 520 |
+
time.monotonic() - started < options["max_seconds"]
|
| 521 |
+
and observed["objective"] < best["objective"]
|
| 522 |
+
)
|
| 523 |
+
if selected:
|
| 524 |
+
best = observed
|
| 525 |
+
best_state = deepcopy(model.state_dict())
|
| 526 |
+
selected_epoch, stale = epoch + 1, 0
|
| 527 |
+
else:
|
| 528 |
+
stale += 1
|
| 529 |
+
history.append({
|
| 530 |
+
"epoch": epoch + 1, **observed, "selected": selected,
|
| 531 |
+
})
|
| 532 |
+
if stale >= options["patience"]:
|
| 533 |
+
stop = "validation_patience"
|
| 534 |
+
break
|
| 535 |
+
if time.monotonic() - started >= options["max_seconds"]:
|
| 536 |
+
stop = "deadline"
|
| 537 |
+
break
|
| 538 |
+
|
| 539 |
+
elapsed = time.monotonic() - started
|
| 540 |
+
_require(steps > 0, "no training steps completed")
|
| 541 |
+
model.load_state_dict(best_state)
|
| 542 |
+
weights = {
|
| 543 |
+
name: tensor.detach().tolist()
|
| 544 |
+
for name, tensor in model.state_dict().items()
|
| 545 |
+
}
|
| 546 |
+
|
| 547 |
+
def manifest(rows):
|
| 548 |
+
return [{
|
| 549 |
+
"id": row["id"],
|
| 550 |
+
"source_sha256": hashlib.sha256(row["source_text"].encode()).hexdigest(),
|
| 551 |
+
"embedding_sha256": digest(row["embedding"]),
|
| 552 |
+
"target_sha256": digest(row["target"]),
|
| 553 |
+
} for row in rows]
|
| 554 |
+
|
| 555 |
+
metrics = {
|
| 556 |
+
"before_validation": before,
|
| 557 |
+
"selected_validation": best,
|
| 558 |
+
"selected_epoch": selected_epoch,
|
| 559 |
+
"optimizer_steps": steps,
|
| 560 |
+
"training_tokens": seen_tokens,
|
| 561 |
+
"examples_seen": examples_seen,
|
| 562 |
+
"optimizer_seconds": optimizer_seconds,
|
| 563 |
+
"validation_seconds": validation_seconds,
|
| 564 |
+
"fit_seconds": elapsed,
|
| 565 |
+
"optimizer_tokens_per_second": seen_tokens / max(optimizer_seconds, 1e-9),
|
| 566 |
+
"optimizer_examples_per_second": examples_seen / max(optimizer_seconds, 1e-9),
|
| 567 |
+
"fit_tokens_per_second": seen_tokens / max(elapsed, 1e-9),
|
| 568 |
+
"stopped_reason": stop,
|
| 569 |
+
"history": history,
|
| 570 |
+
"test_used_for_selection": False,
|
| 571 |
+
"training": _metrics(torch, model, (data, labels), options),
|
| 572 |
+
}
|
| 573 |
+
checkpoint = {
|
| 574 |
+
"schema": SCHEMA,
|
| 575 |
+
"domain_id": domain,
|
| 576 |
+
"dimension": DIMENSION,
|
| 577 |
+
"architecture": numerical.ARCHITECTURE,
|
| 578 |
+
"codec": codec,
|
| 579 |
+
"config": options,
|
| 580 |
+
"implementation": _implementation(),
|
| 581 |
+
"parent_sha256": parent_sha,
|
| 582 |
+
"parent_binding": deepcopy(parent["binding"]),
|
| 583 |
+
"lineage": lineage,
|
| 584 |
+
"model_state": weights,
|
| 585 |
+
"weights_sha256": digest(weights),
|
| 586 |
+
"training_manifest": manifest(train_rows),
|
| 587 |
+
"validation_manifest": manifest(validation),
|
| 588 |
+
"training": metrics,
|
| 589 |
+
**FALSE,
|
| 590 |
+
}
|
| 591 |
+
_require(len(_raw(checkpoint)) <= MAX_BYTES, "checkpoint exceeds bound")
|
| 592 |
+
if original_parent is not None:
|
| 593 |
+
_require(
|
| 594 |
+
parent_path.read_bytes() == original_parent,
|
| 595 |
+
"parent changed during training",
|
| 596 |
+
)
|
| 597 |
+
Runtime(checkpoint)
|
| 598 |
+
return {"checkpoint": checkpoint, "metrics": deepcopy(metrics)}
|
| 599 |
+
|
| 600 |
+
|
| 601 |
+
class Runtime:
|
| 602 |
+
"""Inference consumes source embeddings; gold targets are never accepted."""
|
| 603 |
+
|
| 604 |
+
def __init__(self, checkpoint):
|
| 605 |
+
from . import modal_latent_formula as numerical
|
| 606 |
+
|
| 607 |
+
required = {
|
| 608 |
+
"schema", "domain_id", "dimension", "architecture", "codec", "config",
|
| 609 |
+
"implementation", "parent_sha256", "parent_binding", "lineage",
|
| 610 |
+
"model_state", "weights_sha256", "training_manifest",
|
| 611 |
+
"validation_manifest", "training", *FALSE,
|
| 612 |
+
}
|
| 613 |
+
_require(
|
| 614 |
+
type(checkpoint) is dict
|
| 615 |
+
and set(checkpoint) == required
|
| 616 |
+
and checkpoint["schema"] == SCHEMA,
|
| 617 |
+
"closed domain checkpoint required",
|
| 618 |
+
)
|
| 619 |
+
_require(len(_raw(checkpoint)) <= MAX_BYTES, "checkpoint exceeds bound")
|
| 620 |
+
_require(
|
| 621 |
+
checkpoint["domain_id"] in DOMAINS
|
| 622 |
+
and type(checkpoint["dimension"]) is int
|
| 623 |
+
and checkpoint["dimension"] == DIMENSION,
|
| 624 |
+
"checkpoint requires genuine 384D domain binding",
|
| 625 |
+
)
|
| 626 |
+
_require(
|
| 627 |
+
all(checkpoint[key] is False for key in FALSE),
|
| 628 |
+
"checkpoint cannot grant authority",
|
| 629 |
+
)
|
| 630 |
+
_require(
|
| 631 |
+
checkpoint["implementation"] == _implementation(),
|
| 632 |
+
"domain implementation pins differ",
|
| 633 |
+
)
|
| 634 |
+
_require(
|
| 635 |
+
checkpoint["architecture"] == numerical.ARCHITECTURE,
|
| 636 |
+
"numerical architecture differs",
|
| 637 |
+
)
|
| 638 |
+
_require(
|
| 639 |
+
type(checkpoint["parent_binding"]) is dict
|
| 640 |
+
and checkpoint["parent_binding"].get("dimension") == DIMENSION
|
| 641 |
+
and type(checkpoint["parent_sha256"]) is str
|
| 642 |
+
and _SHA.fullmatch(checkpoint["parent_sha256"]),
|
| 643 |
+
"invalid parent binding",
|
| 644 |
+
)
|
| 645 |
+
codec = checkpoint["codec"]
|
| 646 |
+
_require(
|
| 647 |
+
type(codec) is dict
|
| 648 |
+
and set(codec) == {"schema", "target_vocabulary"}
|
| 649 |
+
and codec["schema"] == "typed-json-lexical/v1",
|
| 650 |
+
"invalid target codec",
|
| 651 |
+
)
|
| 652 |
+
vocabulary = codec["target_vocabulary"]
|
| 653 |
+
_require(
|
| 654 |
+
type(vocabulary) is list
|
| 655 |
+
and 4 <= len(vocabulary) <= 4096
|
| 656 |
+
and vocabulary[:3] == list(SPECIAL)
|
| 657 |
+
and all(type(token) is str and 0 < len(token) <= 16384 for token in vocabulary)
|
| 658 |
+
and vocabulary[3:] == sorted(set(vocabulary[3:]))
|
| 659 |
+
and not set(vocabulary[3:]) & set(SPECIAL),
|
| 660 |
+
"invalid training vocabulary",
|
| 661 |
+
)
|
| 662 |
+
_require(
|
| 663 |
+
all(_TOKEN.fullmatch(token) is not None for token in vocabulary[3:]),
|
| 664 |
+
"invalid JSON vocabulary token",
|
| 665 |
+
)
|
| 666 |
+
config = checkpoint["config"]
|
| 667 |
+
config_fields = {
|
| 668 |
+
"epochs", "max_seconds", "learning_rate", "batch_size", "seed",
|
| 669 |
+
"patience", "reconstruction_weight", "max_target_tokens",
|
| 670 |
+
"embedding_provenance", "hidden_size", "token_embedding_dim",
|
| 671 |
+
"projection_width",
|
| 672 |
+
}
|
| 673 |
+
_require(
|
| 674 |
+
type(config) is dict and set(config) == config_fields,
|
| 675 |
+
"closed model configuration required",
|
| 676 |
+
)
|
| 677 |
+
for key, low, high in (
|
| 678 |
+
("hidden_size", 8, 128),
|
| 679 |
+
("token_embedding_dim", 8, 64),
|
| 680 |
+
("projection_width", 1, 64),
|
| 681 |
+
):
|
| 682 |
+
_require(
|
| 683 |
+
type(config[key]) is int and low <= config[key] <= high,
|
| 684 |
+
"invalid model shape",
|
| 685 |
+
)
|
| 686 |
+
options = {
|
| 687 |
+
key: value for key, value in config.items()
|
| 688 |
+
if key not in {"hidden_size", "token_embedding_dim", "projection_width"}
|
| 689 |
+
}
|
| 690 |
+
_require(_config(options, config) == config, "configuration differs")
|
| 691 |
+
_require(
|
| 692 |
+
digest(checkpoint["model_state"]) == checkpoint["weights_sha256"],
|
| 693 |
+
"weight digest differs",
|
| 694 |
+
)
|
| 695 |
+
training = checkpoint["training"]
|
| 696 |
+
_require(
|
| 697 |
+
type(training) is dict
|
| 698 |
+
and type(training.get("optimizer_steps")) is int
|
| 699 |
+
and training["optimizer_steps"] > 0
|
| 700 |
+
and type(training.get("selected_epoch")) is int
|
| 701 |
+
and 0 <= training["selected_epoch"] <= config["epochs"]
|
| 702 |
+
and training.get("test_used_for_selection") is False,
|
| 703 |
+
"invalid training provenance",
|
| 704 |
+
)
|
| 705 |
+
for name in ("training_manifest", "validation_manifest"):
|
| 706 |
+
rows = checkpoint[name]
|
| 707 |
+
_require(
|
| 708 |
+
type(rows) is list and 1 <= len(rows) <= 4096,
|
| 709 |
+
"invalid split manifest",
|
| 710 |
+
)
|
| 711 |
+
seen = set()
|
| 712 |
+
for row in rows:
|
| 713 |
+
_require(
|
| 714 |
+
type(row) is dict
|
| 715 |
+
and set(row) == {
|
| 716 |
+
"id", "source_sha256", "embedding_sha256", "target_sha256"
|
| 717 |
+
}
|
| 718 |
+
and type(row["id"]) is str
|
| 719 |
+
and 0 < len(row["id"]) <= 256
|
| 720 |
+
and row["id"] not in seen,
|
| 721 |
+
"invalid split row",
|
| 722 |
+
)
|
| 723 |
+
_require(
|
| 724 |
+
all(
|
| 725 |
+
type(row[key]) is str and _SHA.fullmatch(row[key])
|
| 726 |
+
for key in ("source_sha256", "embedding_sha256", "target_sha256")
|
| 727 |
+
),
|
| 728 |
+
"invalid split digest",
|
| 729 |
+
)
|
| 730 |
+
seen.add(row["id"])
|
| 731 |
+
for key in ("id", "source_sha256", "embedding_sha256"):
|
| 732 |
+
_require(
|
| 733 |
+
not {row[key] for row in checkpoint["training_manifest"]}
|
| 734 |
+
& {row[key] for row in checkpoint["validation_manifest"]},
|
| 735 |
+
"checkpoint split overlap",
|
| 736 |
+
)
|
| 737 |
+
|
| 738 |
+
with _cpu():
|
| 739 |
+
model = numerical._model({"dimension": DIMENSION}, codec, config)
|
| 740 |
+
state = checkpoint["model_state"]
|
| 741 |
+
_require(
|
| 742 |
+
type(state) is dict and set(state) == set(model.state_dict()),
|
| 743 |
+
"model tensor names differ",
|
| 744 |
+
)
|
| 745 |
+
model.load_state_dict({
|
| 746 |
+
name: numerical._tensor(state[name], template, name)
|
| 747 |
+
for name, template in model.state_dict().items()
|
| 748 |
+
}, strict=True)
|
| 749 |
+
self.checkpoint = deepcopy(checkpoint)
|
| 750 |
+
self.model = model.eval()
|
| 751 |
+
|
| 752 |
+
def describe(self):
|
| 753 |
+
checkpoint = self.checkpoint
|
| 754 |
+
return {
|
| 755 |
+
"schema": SCHEMA,
|
| 756 |
+
"domain_id": checkpoint["domain_id"],
|
| 757 |
+
"dimension": DIMENSION,
|
| 758 |
+
"input_representation": "explicit_source_embedding_384",
|
| 759 |
+
"architecture": checkpoint["architecture"],
|
| 760 |
+
"weights_sha256": checkpoint["weights_sha256"],
|
| 761 |
+
"parent_sha256": checkpoint["parent_sha256"],
|
| 762 |
+
"embedding_provenance": deepcopy(
|
| 763 |
+
checkpoint["config"]["embedding_provenance"]
|
| 764 |
+
),
|
| 765 |
+
"embedding_provenance_verified_by_runtime": False,
|
| 766 |
+
"trained_optimizer_steps": checkpoint["training"]["optimizer_steps"],
|
| 767 |
+
"selected_epoch": checkpoint["training"]["selected_epoch"],
|
| 768 |
+
"output_scope": (
|
| 769 |
+
"native_documents_or_explicit_local_fragments"
|
| 770 |
+
"_in_training_target_vocabulary"
|
| 771 |
+
),
|
| 772 |
+
"source_text_is_neural_input": False,
|
| 773 |
+
"sample_memory_used": False,
|
| 774 |
+
"independent_source_fidelity_check_required": True,
|
| 775 |
+
**FALSE,
|
| 776 |
+
}
|
| 777 |
+
|
| 778 |
+
def infer(self, rows, *, weight_ablation=None):
|
| 779 |
+
rows = _rows(self.checkpoint["domain_id"], rows, training=False)
|
| 780 |
+
_require(
|
| 781 |
+
weight_ablation in (
|
| 782 |
+
None, "zero_projection", "zero_condition", "zero_decoder"
|
| 783 |
+
),
|
| 784 |
+
"unknown weight ablation",
|
| 785 |
+
)
|
| 786 |
+
model = self.model if weight_ablation is None else deepcopy(self.model)
|
| 787 |
+
vocabulary = self.checkpoint["codec"]["target_vocabulary"]
|
| 788 |
+
config = self.checkpoint["config"]
|
| 789 |
+
reports = []
|
| 790 |
+
with _cpu() as torch, torch.inference_mode():
|
| 791 |
+
if weight_ablation:
|
| 792 |
+
for name, parameter in model.named_parameters():
|
| 793 |
+
selected = (
|
| 794 |
+
weight_ablation == "zero_projection"
|
| 795 |
+
and name.startswith("projection_")
|
| 796 |
+
) or (
|
| 797 |
+
weight_ablation == "zero_condition"
|
| 798 |
+
and name.startswith("condition.")
|
| 799 |
+
) or (
|
| 800 |
+
weight_ablation == "zero_decoder"
|
| 801 |
+
and name.startswith(("decoder.", "output."))
|
| 802 |
+
)
|
| 803 |
+
if selected:
|
| 804 |
+
parameter.zero_()
|
| 805 |
+
for row in rows:
|
| 806 |
+
embedded = torch.tensor(
|
| 807 |
+
[row["embedding"]], dtype=torch.float32
|
| 808 |
+
)
|
| 809 |
+
projected = model.project(embedded)
|
| 810 |
+
_require(
|
| 811 |
+
bool(torch.isfinite(projected).all()),
|
| 812 |
+
"nonfinite reconstructed embedding",
|
| 813 |
+
)
|
| 814 |
+
hidden = model.start(projected)
|
| 815 |
+
current = torch.tensor([[1]], dtype=torch.long)
|
| 816 |
+
generated, ended = [], False
|
| 817 |
+
for _ in range(config["max_target_tokens"] - 1):
|
| 818 |
+
logits, hidden = model.next_logits(current, hidden)
|
| 819 |
+
_require(
|
| 820 |
+
bool(torch.isfinite(logits).all())
|
| 821 |
+
and bool(torch.isfinite(hidden).all()),
|
| 822 |
+
"nonfinite generated logits or hidden state",
|
| 823 |
+
)
|
| 824 |
+
index = int(logits[0, -1].argmax())
|
| 825 |
+
if index == 2:
|
| 826 |
+
ended = True
|
| 827 |
+
break
|
| 828 |
+
if index in (0, 1):
|
| 829 |
+
break
|
| 830 |
+
generated.append(vocabulary[index])
|
| 831 |
+
current = torch.tensor([[index]], dtype=torch.long)
|
| 832 |
+
candidate = None
|
| 833 |
+
status, reason = "fail_open_invalid_output", None
|
| 834 |
+
if ended:
|
| 835 |
+
try:
|
| 836 |
+
value = _parse("".join(generated))
|
| 837 |
+
candidate = validate_target(
|
| 838 |
+
self.checkpoint["domain_id"], value
|
| 839 |
+
)["canonical_ir"]
|
| 840 |
+
status = "unqualified_candidate"
|
| 841 |
+
except (
|
| 842 |
+
ValueError, TypeError, KeyError, RecursionError
|
| 843 |
+
) as exc:
|
| 844 |
+
reason = str(exc)[:512]
|
| 845 |
+
reports.append({
|
| 846 |
+
"id": row["id"],
|
| 847 |
+
"source_sha256": hashlib.sha256(
|
| 848 |
+
row["source_text"].encode()
|
| 849 |
+
).hexdigest(),
|
| 850 |
+
"status": status,
|
| 851 |
+
"reason": reason,
|
| 852 |
+
"candidate_ir": candidate,
|
| 853 |
+
"generated_tokens": generated,
|
| 854 |
+
"ended": ended,
|
| 855 |
+
"reconstructed_embedding": projected[0].tolist(),
|
| 856 |
+
"weight_ablation": weight_ablation,
|
| 857 |
+
"weights_sha256": self.checkpoint["weights_sha256"],
|
| 858 |
+
"target_access": False,
|
| 859 |
+
"teacher_forcing": False,
|
| 860 |
+
"continue_planning": True,
|
| 861 |
+
**FALSE,
|
| 862 |
+
})
|
| 863 |
+
return {
|
| 864 |
+
"schema": SCHEMA,
|
| 865 |
+
"domain_id": self.checkpoint["domain_id"],
|
| 866 |
+
"dimension": DIMENSION,
|
| 867 |
+
"rows": reports,
|
| 868 |
+
**FALSE,
|
| 869 |
+
}
|
| 870 |
+
|
| 871 |
+
|
| 872 |
+
def evaluate(checkpoint, rows):
|
| 873 |
+
"""Post-selection evaluation; gold targets never enter numerical inference."""
|
| 874 |
+
runtime = Runtime(checkpoint)
|
| 875 |
+
prepared = _rows(checkpoint["domain_id"], rows, training=True)
|
| 876 |
+
report = runtime.infer([
|
| 877 |
+
{key: row[key] for key in ("id", "source_text", "embedding")}
|
| 878 |
+
for row in prepared
|
| 879 |
+
])
|
| 880 |
+
for actual, gold in zip(report["rows"], prepared):
|
| 881 |
+
actual["exact_target"] = actual["candidate_ir"] == gold["target"]
|
| 882 |
+
report["exact_targets"] = sum(
|
| 883 |
+
row["exact_target"] for row in report["rows"]
|
| 884 |
+
)
|
| 885 |
+
report["valid_candidates"] = sum(
|
| 886 |
+
row["candidate_ir"] is not None for row in report["rows"]
|
| 887 |
+
)
|
| 888 |
+
report["count"] = len(prepared)
|
| 889 |
+
return report
|
| 890 |
+
|
| 891 |
+
|
| 892 |
+
def load_checkpoint(path, *, expected_sha256, expected_domain):
|
| 893 |
+
"""Load bounded inert JSON with an explicit digest and expected domain."""
|
| 894 |
+
path = Path(path)
|
| 895 |
+
_require(
|
| 896 |
+
path.is_file()
|
| 897 |
+
and not path.is_symlink()
|
| 898 |
+
and 0 < path.stat().st_size <= MAX_BYTES,
|
| 899 |
+
"bounded regular checkpoint required",
|
| 900 |
+
)
|
| 901 |
+
raw = path.read_bytes()
|
| 902 |
+
_require(
|
| 903 |
+
len(raw) <= MAX_BYTES
|
| 904 |
+
and hashlib.sha256(raw).hexdigest() == expected_sha256,
|
| 905 |
+
"checkpoint bytes differ",
|
| 906 |
+
)
|
| 907 |
+
checkpoint = _parse(raw)
|
| 908 |
+
_require(
|
| 909 |
+
type(checkpoint) is dict
|
| 910 |
+
and checkpoint.get("domain_id") == expected_domain,
|
| 911 |
+
"checkpoint belongs to another domain",
|
| 912 |
+
)
|
| 913 |
+
return Runtime(checkpoint)
|
| 914 |
+
|
| 915 |
+
|
| 916 |
+
__all__ = [
|
| 917 |
+
"SCHEMA", "DIMENSION", "DOMAINS", "Runtime", "train", "evaluate",
|
| 918 |
+
"validate_target", "load_checkpoint", "digest",
|
| 919 |
+
]
|
releases/20261004-retained-checkpoints-v1/source/6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py
ADDED
|
@@ -0,0 +1,209 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Versioned bounded Intent syntax; training labels and post-inference checks.
|
| 2 |
+
|
| 3 |
+
This parser is never a replacement for learned predictions. Its explicit
|
| 4 |
+
source grammar supplies weak training supervision and checks complete model
|
| 5 |
+
outputs after inference. No parser slots are passed to the neural encoder.
|
| 6 |
+
"""
|
| 7 |
+
from __future__ import annotations
|
| 8 |
+
|
| 9 |
+
import re
|
| 10 |
+
|
| 11 |
+
SCHEMA = "intent-rich-grammar/v1"
|
| 12 |
+
MODALS = {"intended":"intends to", "required":"must", "prohibited":"must not",
|
| 13 |
+
"permitted":"may", "recommended":"should"}
|
| 14 |
+
SURFACES = {"intends to":"intended", "must":"required", "shall":"required",
|
| 15 |
+
"must not":"prohibited", "shall not":"prohibited", "do not":"prohibited", "never":"prohibited",
|
| 16 |
+
"may":"permitted", "should":"recommended", "is required to":"required",
|
| 17 |
+
"is forbidden to":"prohibited", "is allowed to":"permitted"}
|
| 18 |
+
_ATOM = r"[A-Za-z][A-Za-z0-9_-]*"
|
| 19 |
+
_WORD = re.compile(_ATOM + r"\Z")
|
| 20 |
+
_SLOT = re.compile(r"[A-Za-z0-9_./:`-]+(?: [A-Za-z0-9_./:`-]+)*\Z")
|
| 21 |
+
_UNSUPPORTED = frozenset("unless until before after while once whenever wherever assuming provided given because whether whereas since notwithstanding except without otherwise meanwhile subsequently finally each every all any either neither both none no some a an only always eventually exactly least most whose which whom".split())
|
| 22 |
+
_REFERENCES = frozenset("i me my mine myself you your yours yourself yourselves we us our ours ourselves he him his himself she her hers herself it its itself they them their theirs themselves this that these those former latter above below previous same such here there".split())
|
| 23 |
+
_GRAMMAR_WORDS = frozenset("and or then if must shall may should not never intends is are was were be been being has have had does did can could would will to".split())
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _slot(value, maximum=160, words=16):
|
| 27 |
+
if (type(value) is not str or not 0 < len(value) <= maximum or len(value.split()) > words
|
| 28 |
+
or not _SLOT.fullmatch(value) or " " in value or value.count('`') % 2):
|
| 29 |
+
raise ValueError("bounded case-preserving lexical slot required")
|
| 30 |
+
return value
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def validate_ast(ast):
|
| 34 |
+
if type(ast) is not dict:
|
| 35 |
+
raise ValueError("closed rich Intent AST required")
|
| 36 |
+
kind = ast.get("kind")
|
| 37 |
+
if type(kind) is not str:
|
| 38 |
+
raise ValueError("declared rich constructor required")
|
| 39 |
+
if kind == "atom" and set(ast) == {"kind","actor","action","object","modality"}:
|
| 40 |
+
_slot(ast["actor"], words=4); _slot(ast["object"])
|
| 41 |
+
if (type(ast['action']) is not str or not _WORD.fullmatch(ast["action"])
|
| 42 |
+
or ast["action"] != ast["action"].lower() or type(ast['modality']) is not str or ast["modality"] not in MODALS):
|
| 43 |
+
raise ValueError("stable action and declared modality required")
|
| 44 |
+
elif kind in {"and","or","then"} and set(ast) == {"kind","left","right"}:
|
| 45 |
+
for key in ("left","right"):
|
| 46 |
+
if type(ast[key]) is not dict or ast[key].get("kind") != "atom":
|
| 47 |
+
raise ValueError("first rich grammar permits only two atomic branches")
|
| 48 |
+
validate_ast(ast[key])
|
| 49 |
+
elif kind == "if" and set(ast) == {"kind","guard","body"}:
|
| 50 |
+
guard = ast["guard"]
|
| 51 |
+
if (type(guard) is not dict or set(guard) != {"subject","property","negated"}
|
| 52 |
+
or type(guard["negated"]) is not bool):
|
| 53 |
+
raise ValueError("closed atomic condition required")
|
| 54 |
+
_slot(guard["subject"], words=4)
|
| 55 |
+
if (type(guard["property"]) is not str or not _WORD.fullmatch(guard["property"])
|
| 56 |
+
or guard['property'].lower() in _GRAMMAR_WORDS | _UNSUPPORTED | _REFERENCES):
|
| 57 |
+
raise ValueError("atomic guard property required")
|
| 58 |
+
if type(ast['body']) is not dict or ast["body"].get("kind") != "atom":
|
| 59 |
+
raise ValueError("one guarded atomic norm required")
|
| 60 |
+
validate_ast(ast["body"])
|
| 61 |
+
else:
|
| 62 |
+
raise ValueError("unsupported rich Intent constructor or fields")
|
| 63 |
+
return ast
|
| 64 |
+
|
| 65 |
+
|
| 66 |
+
def ast_to_sequence(ast):
|
| 67 |
+
validate_ast(ast)
|
| 68 |
+
kind = ast["kind"]
|
| 69 |
+
if kind == "atom":
|
| 70 |
+
return " ".join(f"<{key}> {ast[key]}" for key in ("actor","action","object","modality"))
|
| 71 |
+
if kind in {"and","or","then"}:
|
| 72 |
+
return f"<{kind}> {ast_to_sequence(ast['left'])} <next> {ast_to_sequence(ast['right'])}"
|
| 73 |
+
guard = ast["guard"]
|
| 74 |
+
return (f"<if> {guard['subject']} <property> {guard['property']} "
|
| 75 |
+
f"<polarity> {'negative' if guard['negated'] else 'positive'} <body> {ast_to_sequence(ast['body'])}")
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _unspace(value):
|
| 79 |
+
value = " ".join(value.split())
|
| 80 |
+
value = re.sub(r"\s*([./:_-])\s*",r"\1",value)
|
| 81 |
+
return re.sub(r"`\s*([^`]+?)\s*`", lambda m:'`'+m[1]+'`',value)
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def sequence_to_ast(text):
|
| 85 |
+
if type(text) is not str or not 0 < len(text) <= 4096:
|
| 86 |
+
raise ValueError("bounded predicted rich sequence required")
|
| 87 |
+
text = text.strip()
|
| 88 |
+
binary = re.fullmatch(r"<(and|or|then)>\s+(.+?)\s+<next>\s+(.+)",text)
|
| 89 |
+
guard = re.fullmatch(r"<if>\s+([^<>]+?)\s+<property>\s+([^<>]+?)\s+<polarity>\s+(positive|negative)\s+<body>\s+(.+)",text)
|
| 90 |
+
if binary:
|
| 91 |
+
value = {"kind":binary[1],"left":sequence_to_ast(binary[2]),"right":sequence_to_ast(binary[3])}
|
| 92 |
+
elif guard:
|
| 93 |
+
value = {"kind":"if","guard":{"subject":_unspace(guard[1]),"property":_unspace(guard[2]),
|
| 94 |
+
"negated":guard[3]=="negative"},"body":sequence_to_ast(guard[4])}
|
| 95 |
+
else:
|
| 96 |
+
match = re.fullmatch(r"<actor>\s+([^<>]+?)\s+<action>\s+([^<>]+?)\s+<object>\s+([^<>]+?)\s+<modality>\s+([^<>]+?)",text)
|
| 97 |
+
if not match:
|
| 98 |
+
raise ValueError("invalid rich decoder production sequence")
|
| 99 |
+
value = {"kind":"atom",**{key:_unspace(item) for key,item in zip(("actor","action","object","modality"),match.groups())}}
|
| 100 |
+
return validate_ast(value)
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def ast_to_text(ast):
|
| 104 |
+
validate_ast(ast)
|
| 105 |
+
kind = ast["kind"]
|
| 106 |
+
if kind == "atom":
|
| 107 |
+
return f"{ast['actor']} {MODALS[ast['modality']]} {ast['action']} {ast['object']}."
|
| 108 |
+
if kind in {"and","or","then"}:
|
| 109 |
+
return ast_to_text(ast['left'])[:-1]+" "+kind+" "+ast_to_text(ast['right'])
|
| 110 |
+
g = ast['guard']
|
| 111 |
+
return f"if {g['subject']} is {'not ' if g['negated'] else ''}{g['property']}, {ast_to_text(ast['body'])}"
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
def _without_article(value):
|
| 115 |
+
return value[4:] if value.startswith("the ") else value
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _leaf(text, *, normalized_inverse=False):
|
| 119 |
+
from .instruction_scope import _BARE_ACTIONS
|
| 120 |
+
actor, modality, body = "unspecified", "intended", text
|
| 121 |
+
modal_alts = "|".join(re.escape(x) for x in sorted(SURFACES,key=len,reverse=True))
|
| 122 |
+
explicit = re.fullmatch(r"(.+?) ("+modal_alts+r") (.+)",text)
|
| 123 |
+
if explicit:
|
| 124 |
+
actor, modal, body = explicit.groups()
|
| 125 |
+
actor = _without_article(actor)
|
| 126 |
+
modality = SURFACES[modal]
|
| 127 |
+
_slot(actor, words=4)
|
| 128 |
+
if set(actor.lower().split()) & (_UNSUPPORTED | _REFERENCES | _GRAMMAR_WORDS):
|
| 129 |
+
raise ValueError("unresolved actor scope")
|
| 130 |
+
else:
|
| 131 |
+
if normalized_inverse:
|
| 132 |
+
raise ValueError("inverse must state actor and modality")
|
| 133 |
+
if text.startswith("please "):
|
| 134 |
+
body = text[7:]
|
| 135 |
+
for modal in sorted(SURFACES,key=len,reverse=True):
|
| 136 |
+
if body.startswith(modal+" "):
|
| 137 |
+
modality, body = SURFACES[modal], body[len(modal)+1:]
|
| 138 |
+
break
|
| 139 |
+
parts = body.split(" ",1)
|
| 140 |
+
if len(parts)!=2:
|
| 141 |
+
raise ValueError("complete action and object required")
|
| 142 |
+
action, obj = parts[0].lower(), _without_article(parts[1])
|
| 143 |
+
reserved_actions = _UNSUPPORTED | _REFERENCES | _GRAMMAR_WORDS
|
| 144 |
+
if (not _WORD.fullmatch(action) or action in reserved_actions
|
| 145 |
+
or (action not in _BARE_ACTIONS and explicit is None)):
|
| 146 |
+
raise ValueError("unclassified action")
|
| 147 |
+
words = set(obj.lower().replace('`','').split())
|
| 148 |
+
if words & (_UNSUPPORTED | _REFERENCES | {"and","or","then","if","must","shall","may","should","not","to","is","are","was","were","be","been","being","has","have","had","come","analyzed"}):
|
| 149 |
+
raise ValueError("object contains unsupported scope or predication")
|
| 150 |
+
# These are noun fragments in the source corpus; requesting that they be
|
| 151 |
+
# forced through the decoder would create spurious imperative intent.
|
| 152 |
+
if action == "benchmark" and obj.lower().startswith("suite for "):
|
| 153 |
+
raise ValueError("ambiguous descriptive noun phrase")
|
| 154 |
+
return validate_ast({"kind":"atom","actor":actor,"action":action,"object":obj,"modality":modality})
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def parse_instruction(instruction, *, normalized_inverse=False):
|
| 158 |
+
"""Whole-input bounded grammar, for weak labels and independent agreement."""
|
| 159 |
+
if (type(instruction) is not str or not instruction.strip() or len(instruction)>4096
|
| 160 |
+
or not instruction.isascii() or any(c in instruction for c in "\n\r<>?!;()[]{}")):
|
| 161 |
+
raise ValueError("source outside bounded rich grammar")
|
| 162 |
+
text = " ".join(instruction.strip().split()).removesuffix(".")
|
| 163 |
+
if re.search(r"\.\s+",text):
|
| 164 |
+
raise ValueError("multiple sentences require document routing")
|
| 165 |
+
# Only initial grammatical capitalization is normalized. Slot case survives.
|
| 166 |
+
for lead in ("The ","If ","Please ","Do not ","Never ","Must ","Should ","May "):
|
| 167 |
+
if text.startswith(lead):
|
| 168 |
+
text = lead[0].lower()+text[1:]
|
| 169 |
+
break
|
| 170 |
+
conditional = re.fullmatch(r"if (.+?) is (not )?("+_ATOM+r"), (.+)",text)
|
| 171 |
+
if conditional:
|
| 172 |
+
subject, negative, prop, body = conditional.groups()
|
| 173 |
+
subject = _without_article(subject)
|
| 174 |
+
if set(subject.lower().split()) & (_UNSUPPORTED | _REFERENCES | _GRAMMAR_WORDS):
|
| 175 |
+
raise ValueError("unresolved guard subject")
|
| 176 |
+
return validate_ast({"kind":"if","guard":{"subject":subject,"property":prop,"negated":bool(negative)},
|
| 177 |
+
"body":_leaf(body,normalized_inverse=normalized_inverse)})
|
| 178 |
+
if text.startswith('if ') or ',' in text:
|
| 179 |
+
raise ValueError("unsupported conditional or list scope")
|
| 180 |
+
for surface, kind in ((" and then ","then"),(" then ","then"),(" and ","and"),(" or ","or")):
|
| 181 |
+
if surface in text:
|
| 182 |
+
left, right = text.split(surface,1)
|
| 183 |
+
a, b = _leaf(left,normalized_inverse=normalized_inverse), _leaf(right,normalized_inverse=normalized_inverse)
|
| 184 |
+
if a['actor']!='unspecified' and b['actor']=='unspecified':
|
| 185 |
+
raise ValueError("implicit shared actor or modal scope requires explicit branches")
|
| 186 |
+
if (a['modality']!='intended' and b['actor']=='unspecified'
|
| 187 |
+
and not any(right.startswith(m+' ') for m in SURFACES)):
|
| 188 |
+
raise ValueError("shared leading modality requires explicit branch scope")
|
| 189 |
+
return validate_ast({"kind":kind,"left":a,"right":b})
|
| 190 |
+
return _leaf(text,normalized_inverse=normalized_inverse)
|
| 191 |
+
|
| 192 |
+
|
| 193 |
+
def model_input(instruction):
|
| 194 |
+
"""Normalize initial grammar capitalization while retaining every slot byte.
|
| 195 |
+
|
| 196 |
+
Predicate/identifier case is untouched. This transform exports no semantic
|
| 197 |
+
slots and is applied equally to training and numerical source inference.
|
| 198 |
+
"""
|
| 199 |
+
from .instruction_scope import _BARE_ACTIONS
|
| 200 |
+
text=' '.join(instruction.split())
|
| 201 |
+
first,separator,rest=text.partition(' ')
|
| 202 |
+
cues={'the','if','please','do','never','must','shall','should','may'}
|
| 203 |
+
explicit_actor=any(' '+surface+' ' in text for surface in SURFACES)
|
| 204 |
+
if first.lower() in cues or (first.lower() in _BARE_ACTIONS and not explicit_actor):
|
| 205 |
+
first=first.lower()
|
| 206 |
+
return first+separator+rest
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
__all__ = ["SCHEMA","MODALS","validate_ast","ast_to_sequence","sequence_to_ast","ast_to_text","parse_instruction"]
|
releases/20261004-retained-checkpoints-v1/source/7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257/ipfs_datasets_py/logic/intent_ir/decoder.py
ADDED
|
@@ -0,0 +1,721 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Fail-closed decoding and explicit v0.1-to-v1 migration for Intent IR."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
import math
|
| 7 |
+
from dataclasses import dataclass
|
| 8 |
+
from enum import Enum
|
| 9 |
+
from typing import Any, Mapping, TypeVar
|
| 10 |
+
|
| 11 |
+
from ..ir_core.schema_registry import (
|
| 12 |
+
IRSchemaRegistry,
|
| 13 |
+
MigrationLoss,
|
| 14 |
+
MigrationOutcome,
|
| 15 |
+
MigrationReceipt,
|
| 16 |
+
MigrationSpec,
|
| 17 |
+
SchemaSpec,
|
| 18 |
+
)
|
| 19 |
+
from .schema import (
|
| 20 |
+
INTENT_IR_SCHEMA_VERSION,
|
| 21 |
+
LEGACY_INTENT_IR_SCHEMA_VERSION,
|
| 22 |
+
ControlEdgeKind,
|
| 23 |
+
IntentAction,
|
| 24 |
+
IntentControlEdge,
|
| 25 |
+
IntentIRDocument,
|
| 26 |
+
IntentIRValidationError,
|
| 27 |
+
IntentKind,
|
| 28 |
+
IntentModality,
|
| 29 |
+
IntentStatement,
|
| 30 |
+
NodeGrounding,
|
| 31 |
+
ReviewStatus,
|
| 32 |
+
SourceRef,
|
| 33 |
+
SourceSpan,
|
| 34 |
+
StatementKind,
|
| 35 |
+
validate_intent_ir,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
INTENT_IR_V0_1_TO_V1_MIGRATION_ID = "intent-ir-v0.1-to-v1"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class IntentIRDecodeError(IntentIRValidationError):
|
| 42 |
+
"""Raised when an untrusted wire document cannot be decoded exactly."""
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
class MigrationSeverity(str, Enum):
|
| 46 |
+
"""Machine-readable importance of a migration diagnostic."""
|
| 47 |
+
|
| 48 |
+
INFO = "info"
|
| 49 |
+
WARNING = "warning"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@dataclass(frozen=True, slots=True)
|
| 53 |
+
class MigrationDiagnostic:
|
| 54 |
+
"""One explicit transformation performed while migrating a document."""
|
| 55 |
+
|
| 56 |
+
code: str
|
| 57 |
+
path: str
|
| 58 |
+
message: str
|
| 59 |
+
severity: MigrationSeverity = MigrationSeverity.INFO
|
| 60 |
+
lossy: bool = False
|
| 61 |
+
|
| 62 |
+
def to_dict(self) -> dict[str, Any]:
|
| 63 |
+
return {
|
| 64 |
+
"code": self.code,
|
| 65 |
+
"lossy": self.lossy,
|
| 66 |
+
"message": self.message,
|
| 67 |
+
"path": self.path,
|
| 68 |
+
"severity": self.severity.value,
|
| 69 |
+
}
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
@dataclass(frozen=True, slots=True)
|
| 73 |
+
class IntentIRMigrationResult:
|
| 74 |
+
"""A decoded v1 document plus an immutable migration audit trail."""
|
| 75 |
+
|
| 76 |
+
document: IntentIRDocument
|
| 77 |
+
source_version: str
|
| 78 |
+
target_version: str
|
| 79 |
+
diagnostics: tuple[MigrationDiagnostic, ...] = ()
|
| 80 |
+
receipt: MigrationReceipt | None = None
|
| 81 |
+
|
| 82 |
+
@property
|
| 83 |
+
def loss_diagnostics(self) -> tuple[MigrationDiagnostic, ...]:
|
| 84 |
+
return tuple(item for item in self.diagnostics if item.lossy)
|
| 85 |
+
|
| 86 |
+
@property
|
| 87 |
+
def is_lossless(self) -> bool:
|
| 88 |
+
return not self.loss_diagnostics
|
| 89 |
+
|
| 90 |
+
|
| 91 |
+
_DOCUMENT_FIELDS = {
|
| 92 |
+
"schema_version",
|
| 93 |
+
"document_id",
|
| 94 |
+
"title",
|
| 95 |
+
"intent_kind",
|
| 96 |
+
"sources",
|
| 97 |
+
"statements",
|
| 98 |
+
"actions",
|
| 99 |
+
"control_edges",
|
| 100 |
+
"entry_action_ids",
|
| 101 |
+
"terminal_action_ids",
|
| 102 |
+
"tags",
|
| 103 |
+
}
|
| 104 |
+
_SOURCE_FIELDS = {
|
| 105 |
+
"ref_id",
|
| 106 |
+
"source_uri",
|
| 107 |
+
"source_id",
|
| 108 |
+
"source_revision",
|
| 109 |
+
"content_sha256",
|
| 110 |
+
"container_uri",
|
| 111 |
+
"container_sha256",
|
| 112 |
+
"content_cid",
|
| 113 |
+
"license_expression",
|
| 114 |
+
"review_status",
|
| 115 |
+
"span",
|
| 116 |
+
}
|
| 117 |
+
_STATEMENT_FIELDS = {
|
| 118 |
+
"statement_id",
|
| 119 |
+
"kind",
|
| 120 |
+
"modality",
|
| 121 |
+
"normalized_text",
|
| 122 |
+
"source_ref_ids",
|
| 123 |
+
"predicate",
|
| 124 |
+
"arguments",
|
| 125 |
+
"confidence",
|
| 126 |
+
"review_status",
|
| 127 |
+
"grounding",
|
| 128 |
+
}
|
| 129 |
+
_ACTION_FIELDS = {
|
| 130 |
+
"action_id",
|
| 131 |
+
"actor",
|
| 132 |
+
"verb",
|
| 133 |
+
"object_refs",
|
| 134 |
+
"source_ref_ids",
|
| 135 |
+
"tool_refs",
|
| 136 |
+
"input_refs",
|
| 137 |
+
"output_refs",
|
| 138 |
+
"precondition_ids",
|
| 139 |
+
"effect_ids",
|
| 140 |
+
"verification_ids",
|
| 141 |
+
"grounding",
|
| 142 |
+
}
|
| 143 |
+
_EDGE_FIELDS = {
|
| 144 |
+
"edge_id",
|
| 145 |
+
"source_action_id",
|
| 146 |
+
"target_action_id",
|
| 147 |
+
"kind",
|
| 148 |
+
"guard_statement_id",
|
| 149 |
+
"source_ref_ids",
|
| 150 |
+
"grounding",
|
| 151 |
+
}
|
| 152 |
+
_SPAN_FIELDS = {"start_char", "end_char"}
|
| 153 |
+
|
| 154 |
+
_DOCUMENT_REQUIRED = {
|
| 155 |
+
"schema_version",
|
| 156 |
+
"document_id",
|
| 157 |
+
"title",
|
| 158 |
+
"intent_kind",
|
| 159 |
+
"sources",
|
| 160 |
+
"statements",
|
| 161 |
+
}
|
| 162 |
+
_SOURCE_REQUIRED = {
|
| 163 |
+
"ref_id",
|
| 164 |
+
"source_uri",
|
| 165 |
+
"source_id",
|
| 166 |
+
"source_revision",
|
| 167 |
+
"content_sha256",
|
| 168 |
+
}
|
| 169 |
+
_STATEMENT_REQUIRED = {
|
| 170 |
+
"statement_id",
|
| 171 |
+
"kind",
|
| 172 |
+
"modality",
|
| 173 |
+
"normalized_text",
|
| 174 |
+
"source_ref_ids",
|
| 175 |
+
"grounding",
|
| 176 |
+
}
|
| 177 |
+
_ACTION_REQUIRED = {
|
| 178 |
+
"action_id",
|
| 179 |
+
"actor",
|
| 180 |
+
"verb",
|
| 181 |
+
"object_refs",
|
| 182 |
+
"source_ref_ids",
|
| 183 |
+
"grounding",
|
| 184 |
+
}
|
| 185 |
+
_EDGE_REQUIRED = {
|
| 186 |
+
"edge_id",
|
| 187 |
+
"source_action_id",
|
| 188 |
+
"target_action_id",
|
| 189 |
+
"grounding",
|
| 190 |
+
}
|
| 191 |
+
|
| 192 |
+
_LEGACY_STATEMENT_FIELDS = _STATEMENT_FIELDS - {"grounding"}
|
| 193 |
+
_LEGACY_ACTION_FIELDS = _ACTION_FIELDS - {"grounding"}
|
| 194 |
+
_LEGACY_EDGE_FIELDS = _EDGE_FIELDS - {"grounding"}
|
| 195 |
+
|
| 196 |
+
_E = TypeVar("_E", bound=Enum)
|
| 197 |
+
|
| 198 |
+
|
| 199 |
+
def decode_intent_ir(
|
| 200 |
+
payload: Mapping[str, Any] | str | bytes | bytearray,
|
| 201 |
+
) -> IntentIRDocument:
|
| 202 |
+
"""Decode one exact v1 wire document into immutable typed records.
|
| 203 |
+
|
| 204 |
+
The decoder rejects missing or unknown versions, unknown object fields,
|
| 205 |
+
duplicate JSON keys, non-JSON values, untyped enum values, duplicate
|
| 206 |
+
members of set-like collections, and every dangling internal reference.
|
| 207 |
+
It never retains mutable collections from the caller.
|
| 208 |
+
"""
|
| 209 |
+
|
| 210 |
+
raw = _load_payload(payload)
|
| 211 |
+
version = raw.get("schema_version")
|
| 212 |
+
if version != INTENT_IR_SCHEMA_VERSION:
|
| 213 |
+
raise IntentIRDecodeError(
|
| 214 |
+
f"Unsupported Intent IR schema_version: {version!r}; "
|
| 215 |
+
f"expected {INTENT_IR_SCHEMA_VERSION!r}"
|
| 216 |
+
)
|
| 217 |
+
return _decode_v1(raw)
|
| 218 |
+
|
| 219 |
+
|
| 220 |
+
def migrate_intent_ir(
|
| 221 |
+
payload: Mapping[str, Any] | str | bytes | bytearray,
|
| 222 |
+
*,
|
| 223 |
+
allow_lossy: bool = True,
|
| 224 |
+
) -> IntentIRMigrationResult:
|
| 225 |
+
"""Decode v1 or migrate the sole supported legacy version, v0.1.
|
| 226 |
+
|
| 227 |
+
Because v0.1 did not record node grounding, every legacy migration reports
|
| 228 |
+
that unrecoverable distinction as a loss. Duplicate members in legacy
|
| 229 |
+
set-like arrays are also removed and reported. Set ``allow_lossy=False`` to
|
| 230 |
+
fail closed instead. No unknown version, field, or internal reference is
|
| 231 |
+
accepted.
|
| 232 |
+
"""
|
| 233 |
+
|
| 234 |
+
raw = _load_payload(payload)
|
| 235 |
+
version = raw.get("schema_version")
|
| 236 |
+
if version == INTENT_IR_SCHEMA_VERSION:
|
| 237 |
+
return IntentIRMigrationResult(
|
| 238 |
+
document=_decode_v1(raw),
|
| 239 |
+
source_version=INTENT_IR_SCHEMA_VERSION,
|
| 240 |
+
target_version=INTENT_IR_SCHEMA_VERSION,
|
| 241 |
+
)
|
| 242 |
+
if version != LEGACY_INTENT_IR_SCHEMA_VERSION:
|
| 243 |
+
raise IntentIRDecodeError(
|
| 244 |
+
f"Unsupported Intent IR schema_version: {version!r}; supported "
|
| 245 |
+
f"versions are {LEGACY_INTENT_IR_SCHEMA_VERSION!r} and "
|
| 246 |
+
f"{INTENT_IR_SCHEMA_VERSION!r}"
|
| 247 |
+
)
|
| 248 |
+
|
| 249 |
+
pre_migrated, diagnostics = _migrate_v0_1(raw)
|
| 250 |
+
_decode_v1(pre_migrated)
|
| 251 |
+
losses = tuple(item for item in diagnostics if item.lossy)
|
| 252 |
+
if losses and not allow_lossy:
|
| 253 |
+
paths = ", ".join(item.path for item in losses)
|
| 254 |
+
raise IntentIRDecodeError(f"Intent IR migration would be lossy at: {paths}")
|
| 255 |
+
registry_result = INTENT_IR_SCHEMA_REGISTRY.migrate(
|
| 256 |
+
raw,
|
| 257 |
+
source_schema_id=LEGACY_INTENT_IR_SCHEMA_VERSION,
|
| 258 |
+
destination_schema_id=INTENT_IR_SCHEMA_VERSION,
|
| 259 |
+
)
|
| 260 |
+
migrated = _thaw_registry_json(registry_result.payload)
|
| 261 |
+
if not isinstance(migrated, dict): # Registry payloads are always objects.
|
| 262 |
+
raise IntentIRDecodeError("Intent IR migration returned a non-object")
|
| 263 |
+
return IntentIRMigrationResult(
|
| 264 |
+
document=_decode_v1(migrated),
|
| 265 |
+
source_version=LEGACY_INTENT_IR_SCHEMA_VERSION,
|
| 266 |
+
target_version=INTENT_IR_SCHEMA_VERSION,
|
| 267 |
+
diagnostics=tuple(diagnostics),
|
| 268 |
+
receipt=registry_result.receipt,
|
| 269 |
+
)
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
def decode_intent_ir_with_migration(
|
| 273 |
+
payload: Mapping[str, Any] | str | bytes | bytearray,
|
| 274 |
+
*,
|
| 275 |
+
allow_lossy: bool = True,
|
| 276 |
+
) -> IntentIRMigrationResult:
|
| 277 |
+
"""Named alias for callers that want migration diagnostics at decode time."""
|
| 278 |
+
|
| 279 |
+
return migrate_intent_ir(payload, allow_lossy=allow_lossy)
|
| 280 |
+
|
| 281 |
+
|
| 282 |
+
def _decode_v1(raw: Mapping[str, Any]) -> IntentIRDocument:
|
| 283 |
+
_check_fields(raw, _DOCUMENT_FIELDS, _DOCUMENT_REQUIRED, "$")
|
| 284 |
+
document = IntentIRDocument(
|
| 285 |
+
schema_version=_string(raw["schema_version"], "$.schema_version"),
|
| 286 |
+
document_id=_string(raw["document_id"], "$.document_id"),
|
| 287 |
+
title=_string(raw["title"], "$.title"),
|
| 288 |
+
intent_kind=_enum(IntentKind, raw["intent_kind"], "$.intent_kind"),
|
| 289 |
+
sources=tuple(
|
| 290 |
+
_decode_source(item, f"$.sources[{index}]")
|
| 291 |
+
for index, item in enumerate(_array(raw["sources"], "$.sources"))
|
| 292 |
+
),
|
| 293 |
+
statements=tuple(
|
| 294 |
+
_decode_statement(item, f"$.statements[{index}]")
|
| 295 |
+
for index, item in enumerate(_array(raw["statements"], "$.statements"))
|
| 296 |
+
),
|
| 297 |
+
actions=tuple(
|
| 298 |
+
_decode_action(item, f"$.actions[{index}]")
|
| 299 |
+
for index, item in enumerate(_array(raw.get("actions", []), "$.actions"))
|
| 300 |
+
),
|
| 301 |
+
control_edges=tuple(
|
| 302 |
+
_decode_edge(item, f"$.control_edges[{index}]")
|
| 303 |
+
for index, item in enumerate(_array(raw.get("control_edges", []), "$.control_edges"))
|
| 304 |
+
),
|
| 305 |
+
entry_action_ids=_string_tuple(raw.get("entry_action_ids", []), "$.entry_action_ids"),
|
| 306 |
+
terminal_action_ids=_string_tuple(
|
| 307 |
+
raw.get("terminal_action_ids", []), "$.terminal_action_ids"
|
| 308 |
+
),
|
| 309 |
+
tags=_string_tuple(raw.get("tags", []), "$.tags"),
|
| 310 |
+
)
|
| 311 |
+
try:
|
| 312 |
+
return validate_intent_ir(document)
|
| 313 |
+
except IntentIRDecodeError:
|
| 314 |
+
raise
|
| 315 |
+
except IntentIRValidationError as exc:
|
| 316 |
+
raise IntentIRDecodeError(str(exc)) from exc
|
| 317 |
+
|
| 318 |
+
|
| 319 |
+
def _decode_source(value: Any, path: str) -> SourceRef:
|
| 320 |
+
raw = _object(value, path)
|
| 321 |
+
_check_fields(raw, _SOURCE_FIELDS, _SOURCE_REQUIRED, path)
|
| 322 |
+
span_value = raw.get("span")
|
| 323 |
+
span = None
|
| 324 |
+
if span_value is not None:
|
| 325 |
+
span_raw = _object(span_value, f"{path}.span")
|
| 326 |
+
_check_fields(span_raw, _SPAN_FIELDS, _SPAN_FIELDS, f"{path}.span")
|
| 327 |
+
span = SourceSpan(
|
| 328 |
+
start_char=_integer(span_raw["start_char"], f"{path}.span.start_char"),
|
| 329 |
+
end_char=_integer(span_raw["end_char"], f"{path}.span.end_char"),
|
| 330 |
+
)
|
| 331 |
+
return SourceRef(
|
| 332 |
+
ref_id=_string(raw["ref_id"], f"{path}.ref_id"),
|
| 333 |
+
source_uri=_string(raw["source_uri"], f"{path}.source_uri"),
|
| 334 |
+
source_id=_string(raw["source_id"], f"{path}.source_id"),
|
| 335 |
+
source_revision=_string(raw["source_revision"], f"{path}.source_revision"),
|
| 336 |
+
content_sha256=_string(raw["content_sha256"], f"{path}.content_sha256"),
|
| 337 |
+
container_uri=_string(raw.get("container_uri", ""), f"{path}.container_uri"),
|
| 338 |
+
container_sha256=_string(raw.get("container_sha256", ""), f"{path}.container_sha256"),
|
| 339 |
+
content_cid=_string(raw.get("content_cid", ""), f"{path}.content_cid"),
|
| 340 |
+
license_expression=_string(raw.get("license_expression", ""), f"{path}.license_expression"),
|
| 341 |
+
review_status=_enum(
|
| 342 |
+
ReviewStatus,
|
| 343 |
+
raw.get("review_status", ReviewStatus.UNREVIEWED.value),
|
| 344 |
+
f"{path}.review_status",
|
| 345 |
+
),
|
| 346 |
+
span=span,
|
| 347 |
+
)
|
| 348 |
+
|
| 349 |
+
|
| 350 |
+
def _decode_statement(value: Any, path: str) -> IntentStatement:
|
| 351 |
+
raw = _object(value, path)
|
| 352 |
+
_check_fields(raw, _STATEMENT_FIELDS, _STATEMENT_REQUIRED, path)
|
| 353 |
+
return IntentStatement(
|
| 354 |
+
statement_id=_string(raw["statement_id"], f"{path}.statement_id"),
|
| 355 |
+
kind=_enum(StatementKind, raw["kind"], f"{path}.kind"),
|
| 356 |
+
modality=_enum(IntentModality, raw["modality"], f"{path}.modality"),
|
| 357 |
+
normalized_text=_string(raw["normalized_text"], f"{path}.normalized_text"),
|
| 358 |
+
source_ref_ids=_string_tuple(raw["source_ref_ids"], f"{path}.source_ref_ids"),
|
| 359 |
+
predicate=_string(raw.get("predicate", ""), f"{path}.predicate"),
|
| 360 |
+
arguments=_string_tuple(raw.get("arguments", []), f"{path}.arguments"),
|
| 361 |
+
confidence=_number(raw.get("confidence", 1.0), f"{path}.confidence"),
|
| 362 |
+
review_status=_enum(
|
| 363 |
+
ReviewStatus,
|
| 364 |
+
raw.get("review_status", ReviewStatus.MACHINE_EXTRACTED.value),
|
| 365 |
+
f"{path}.review_status",
|
| 366 |
+
),
|
| 367 |
+
grounding=_enum(NodeGrounding, raw["grounding"], f"{path}.grounding"),
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
|
| 371 |
+
def _decode_action(value: Any, path: str) -> IntentAction:
|
| 372 |
+
raw = _object(value, path)
|
| 373 |
+
_check_fields(raw, _ACTION_FIELDS, _ACTION_REQUIRED, path)
|
| 374 |
+
return IntentAction(
|
| 375 |
+
action_id=_string(raw["action_id"], f"{path}.action_id"),
|
| 376 |
+
actor=_string(raw["actor"], f"{path}.actor"),
|
| 377 |
+
verb=_string(raw["verb"], f"{path}.verb"),
|
| 378 |
+
object_refs=_string_tuple(raw["object_refs"], f"{path}.object_refs"),
|
| 379 |
+
source_ref_ids=_string_tuple(raw["source_ref_ids"], f"{path}.source_ref_ids"),
|
| 380 |
+
tool_refs=_string_tuple(raw.get("tool_refs", []), f"{path}.tool_refs"),
|
| 381 |
+
input_refs=_string_tuple(raw.get("input_refs", []), f"{path}.input_refs"),
|
| 382 |
+
output_refs=_string_tuple(raw.get("output_refs", []), f"{path}.output_refs"),
|
| 383 |
+
precondition_ids=_string_tuple(raw.get("precondition_ids", []), f"{path}.precondition_ids"),
|
| 384 |
+
effect_ids=_string_tuple(raw.get("effect_ids", []), f"{path}.effect_ids"),
|
| 385 |
+
verification_ids=_string_tuple(raw.get("verification_ids", []), f"{path}.verification_ids"),
|
| 386 |
+
grounding=_enum(NodeGrounding, raw["grounding"], f"{path}.grounding"),
|
| 387 |
+
)
|
| 388 |
+
|
| 389 |
+
|
| 390 |
+
def _decode_edge(value: Any, path: str) -> IntentControlEdge:
|
| 391 |
+
raw = _object(value, path)
|
| 392 |
+
_check_fields(raw, _EDGE_FIELDS, _EDGE_REQUIRED, path)
|
| 393 |
+
return IntentControlEdge(
|
| 394 |
+
edge_id=_string(raw["edge_id"], f"{path}.edge_id"),
|
| 395 |
+
source_action_id=_string(raw["source_action_id"], f"{path}.source_action_id"),
|
| 396 |
+
target_action_id=_string(raw["target_action_id"], f"{path}.target_action_id"),
|
| 397 |
+
kind=_enum(
|
| 398 |
+
ControlEdgeKind,
|
| 399 |
+
raw.get("kind", ControlEdgeKind.NEXT.value),
|
| 400 |
+
f"{path}.kind",
|
| 401 |
+
),
|
| 402 |
+
guard_statement_id=_string(raw.get("guard_statement_id", ""), f"{path}.guard_statement_id"),
|
| 403 |
+
source_ref_ids=_string_tuple(raw.get("source_ref_ids", []), f"{path}.source_ref_ids"),
|
| 404 |
+
grounding=_enum(NodeGrounding, raw["grounding"], f"{path}.grounding"),
|
| 405 |
+
)
|
| 406 |
+
|
| 407 |
+
|
| 408 |
+
def _migrate_v0_1(
|
| 409 |
+
raw: Mapping[str, Any],
|
| 410 |
+
) -> tuple[dict[str, Any], list[MigrationDiagnostic]]:
|
| 411 |
+
_check_fields(raw, _DOCUMENT_FIELDS, _DOCUMENT_REQUIRED, "$")
|
| 412 |
+
migrated = _plain_object(raw, "$")
|
| 413 |
+
diagnostics: list[MigrationDiagnostic] = []
|
| 414 |
+
|
| 415 |
+
for collection_name, allowed, required in (
|
| 416 |
+
("sources", _SOURCE_FIELDS, _SOURCE_REQUIRED),
|
| 417 |
+
(
|
| 418 |
+
"statements",
|
| 419 |
+
_LEGACY_STATEMENT_FIELDS,
|
| 420 |
+
_STATEMENT_REQUIRED - {"grounding"},
|
| 421 |
+
),
|
| 422 |
+
(
|
| 423 |
+
"actions",
|
| 424 |
+
_LEGACY_ACTION_FIELDS,
|
| 425 |
+
_ACTION_REQUIRED - {"grounding"},
|
| 426 |
+
),
|
| 427 |
+
(
|
| 428 |
+
"control_edges",
|
| 429 |
+
_LEGACY_EDGE_FIELDS,
|
| 430 |
+
_EDGE_REQUIRED - {"grounding"},
|
| 431 |
+
),
|
| 432 |
+
):
|
| 433 |
+
for index, item in enumerate(
|
| 434 |
+
_array(migrated.get(collection_name, []), f"$.{collection_name}")
|
| 435 |
+
):
|
| 436 |
+
item_path = f"$.{collection_name}[{index}]"
|
| 437 |
+
_check_fields(_object(item, item_path), allowed, required, item_path)
|
| 438 |
+
|
| 439 |
+
set_paths: list[tuple[dict[str, Any], str, str]] = [
|
| 440 |
+
(migrated, "entry_action_ids", "$.entry_action_ids"),
|
| 441 |
+
(migrated, "terminal_action_ids", "$.terminal_action_ids"),
|
| 442 |
+
(migrated, "tags", "$.tags"),
|
| 443 |
+
]
|
| 444 |
+
for index, item in enumerate(migrated.get("statements", [])):
|
| 445 |
+
set_paths.append((item, "source_ref_ids", f"$.statements[{index}].source_ref_ids"))
|
| 446 |
+
for index, item in enumerate(migrated.get("actions", [])):
|
| 447 |
+
for name in (
|
| 448 |
+
"object_refs",
|
| 449 |
+
"source_ref_ids",
|
| 450 |
+
"tool_refs",
|
| 451 |
+
"input_refs",
|
| 452 |
+
"output_refs",
|
| 453 |
+
"precondition_ids",
|
| 454 |
+
"effect_ids",
|
| 455 |
+
"verification_ids",
|
| 456 |
+
):
|
| 457 |
+
set_paths.append((item, name, f"$.actions[{index}].{name}"))
|
| 458 |
+
for index, item in enumerate(migrated.get("control_edges", [])):
|
| 459 |
+
set_paths.append((item, "source_ref_ids", f"$.control_edges[{index}].source_ref_ids"))
|
| 460 |
+
|
| 461 |
+
for owner, name, path in set_paths:
|
| 462 |
+
if name not in owner:
|
| 463 |
+
continue
|
| 464 |
+
original = _array(owner[name], path)
|
| 465 |
+
unique: list[Any] = []
|
| 466 |
+
for value in original:
|
| 467 |
+
if value not in unique:
|
| 468 |
+
unique.append(value)
|
| 469 |
+
if len(unique) != len(original):
|
| 470 |
+
owner[name] = unique
|
| 471 |
+
diagnostics.append(
|
| 472 |
+
MigrationDiagnostic(
|
| 473 |
+
code="duplicate_set_members_removed",
|
| 474 |
+
path=path,
|
| 475 |
+
message=(
|
| 476 |
+
f"Removed {len(original) - len(unique)} duplicate "
|
| 477 |
+
"member(s) from a set-like collection"
|
| 478 |
+
),
|
| 479 |
+
severity=MigrationSeverity.WARNING,
|
| 480 |
+
lossy=True,
|
| 481 |
+
)
|
| 482 |
+
)
|
| 483 |
+
|
| 484 |
+
for collection_name in ("statements", "actions", "control_edges"):
|
| 485 |
+
for index, item in enumerate(migrated.get(collection_name, [])):
|
| 486 |
+
path = f"$.{collection_name}[{index}].grounding"
|
| 487 |
+
if collection_name == "control_edges" and not item.get("source_ref_ids", []):
|
| 488 |
+
grounding = NodeGrounding.INFERRED.value
|
| 489 |
+
message = "Classified a legacy edge without source references as inferred"
|
| 490 |
+
else:
|
| 491 |
+
grounding = NodeGrounding.GROUNDED.value
|
| 492 |
+
message = "Classified a legacy source-referenced node as grounded"
|
| 493 |
+
item["grounding"] = grounding
|
| 494 |
+
diagnostics.append(
|
| 495 |
+
MigrationDiagnostic(
|
| 496 |
+
code="node_grounding_classified",
|
| 497 |
+
path=path,
|
| 498 |
+
message=message,
|
| 499 |
+
)
|
| 500 |
+
)
|
| 501 |
+
|
| 502 |
+
diagnostics.append(
|
| 503 |
+
MigrationDiagnostic(
|
| 504 |
+
code="legacy_grounding_ambiguity",
|
| 505 |
+
path="$.statements|actions|control_edges",
|
| 506 |
+
message=(
|
| 507 |
+
"v0.1 did not encode grounded-versus-inferred status; v1 "
|
| 508 |
+
"classification is deterministic but cannot recover that "
|
| 509 |
+
"missing authorial distinction"
|
| 510 |
+
),
|
| 511 |
+
severity=MigrationSeverity.WARNING,
|
| 512 |
+
lossy=True,
|
| 513 |
+
)
|
| 514 |
+
)
|
| 515 |
+
migrated["schema_version"] = INTENT_IR_SCHEMA_VERSION
|
| 516 |
+
diagnostics.append(
|
| 517 |
+
MigrationDiagnostic(
|
| 518 |
+
code="schema_version_upgraded",
|
| 519 |
+
path="$.schema_version",
|
| 520 |
+
message=(f"Upgraded {LEGACY_INTENT_IR_SCHEMA_VERSION} to {INTENT_IR_SCHEMA_VERSION}"),
|
| 521 |
+
)
|
| 522 |
+
)
|
| 523 |
+
return migrated, diagnostics
|
| 524 |
+
|
| 525 |
+
|
| 526 |
+
def _registry_migrate_v0_1(
|
| 527 |
+
payload: Mapping[str, Any],
|
| 528 |
+
) -> MigrationOutcome:
|
| 529 |
+
"""Shared-registry transform with content-bound loss evidence."""
|
| 530 |
+
|
| 531 |
+
thawed = _thaw_registry_json(payload)
|
| 532 |
+
if not isinstance(thawed, dict):
|
| 533 |
+
raise IntentIRDecodeError("Legacy Intent IR payload must be an object")
|
| 534 |
+
migrated, diagnostics = _migrate_v0_1(thawed)
|
| 535 |
+
canonical = _decode_v1(migrated).to_dict()
|
| 536 |
+
losses = tuple(
|
| 537 |
+
MigrationLoss(
|
| 538 |
+
code=item.code.replace("_", "-"),
|
| 539 |
+
field_path=item.path,
|
| 540 |
+
message=item.message,
|
| 541 |
+
)
|
| 542 |
+
for item in diagnostics
|
| 543 |
+
if item.lossy
|
| 544 |
+
)
|
| 545 |
+
return MigrationOutcome(canonical, losses)
|
| 546 |
+
|
| 547 |
+
|
| 548 |
+
def _load_payload(
|
| 549 |
+
payload: Mapping[str, Any] | str | bytes | bytearray,
|
| 550 |
+
) -> dict[str, Any]:
|
| 551 |
+
if isinstance(payload, (bytes, bytearray)):
|
| 552 |
+
try:
|
| 553 |
+
payload = bytes(payload).decode("utf-8")
|
| 554 |
+
except UnicodeDecodeError as exc:
|
| 555 |
+
raise IntentIRDecodeError("Intent IR bytes must be UTF-8") from exc
|
| 556 |
+
if isinstance(payload, str):
|
| 557 |
+
try:
|
| 558 |
+
value = json.loads(
|
| 559 |
+
payload,
|
| 560 |
+
object_pairs_hook=_reject_duplicate_json_keys,
|
| 561 |
+
parse_constant=_reject_non_finite_json_number,
|
| 562 |
+
)
|
| 563 |
+
except (json.JSONDecodeError, IntentIRDecodeError) as exc:
|
| 564 |
+
if isinstance(exc, IntentIRDecodeError):
|
| 565 |
+
raise
|
| 566 |
+
raise IntentIRDecodeError(f"Invalid Intent IR JSON: {exc.msg}") from exc
|
| 567 |
+
else:
|
| 568 |
+
value = payload
|
| 569 |
+
return _plain_object(_object(value, "$"), "$")
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
def _reject_duplicate_json_keys(pairs: list[tuple[str, Any]]) -> dict[str, Any]:
|
| 573 |
+
result: dict[str, Any] = {}
|
| 574 |
+
for key, value in pairs:
|
| 575 |
+
if key in result:
|
| 576 |
+
raise IntentIRDecodeError(f"Duplicate JSON object key: {key!r}")
|
| 577 |
+
result[key] = value
|
| 578 |
+
return result
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def _reject_non_finite_json_number(value: str) -> None:
|
| 582 |
+
raise IntentIRDecodeError(f"Non-finite JSON number is not allowed: {value}")
|
| 583 |
+
|
| 584 |
+
|
| 585 |
+
def _plain_object(value: Mapping[str, Any], path: str) -> dict[str, Any]:
|
| 586 |
+
return {
|
| 587 |
+
key: _plain_json(item, f"{path}.{key}")
|
| 588 |
+
for key, item in value.items()
|
| 589 |
+
if _validate_key(key, path)
|
| 590 |
+
}
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def _plain_json(value: Any, path: str) -> Any:
|
| 594 |
+
if isinstance(value, Mapping):
|
| 595 |
+
return _plain_object(value, path)
|
| 596 |
+
if isinstance(value, list):
|
| 597 |
+
return [_plain_json(item, f"{path}[{index}]") for index, item in enumerate(value)]
|
| 598 |
+
if value is None or isinstance(value, (str, bool, int)):
|
| 599 |
+
return value
|
| 600 |
+
if isinstance(value, float) and math.isfinite(value):
|
| 601 |
+
return value
|
| 602 |
+
raise IntentIRDecodeError(f"{path} contains a non-JSON value")
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def _thaw_registry_json(value: Any) -> Any:
|
| 606 |
+
if isinstance(value, Mapping):
|
| 607 |
+
return {str(key): _thaw_registry_json(item) for key, item in value.items()}
|
| 608 |
+
if isinstance(value, (list, tuple)):
|
| 609 |
+
return [_thaw_registry_json(item) for item in value]
|
| 610 |
+
return value
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
def _validate_key(key: Any, path: str) -> bool:
|
| 614 |
+
if not isinstance(key, str):
|
| 615 |
+
raise IntentIRDecodeError(f"{path} contains a non-string object key")
|
| 616 |
+
return True
|
| 617 |
+
|
| 618 |
+
|
| 619 |
+
def _object(value: Any, path: str) -> Mapping[str, Any]:
|
| 620 |
+
if not isinstance(value, Mapping):
|
| 621 |
+
raise IntentIRDecodeError(f"{path} must be an object")
|
| 622 |
+
return value
|
| 623 |
+
|
| 624 |
+
|
| 625 |
+
def _array(value: Any, path: str) -> list[Any]:
|
| 626 |
+
if not isinstance(value, list):
|
| 627 |
+
raise IntentIRDecodeError(f"{path} must be an array")
|
| 628 |
+
return value
|
| 629 |
+
|
| 630 |
+
|
| 631 |
+
def _string(value: Any, path: str) -> str:
|
| 632 |
+
if not isinstance(value, str):
|
| 633 |
+
raise IntentIRDecodeError(f"{path} must be a string")
|
| 634 |
+
return value
|
| 635 |
+
|
| 636 |
+
|
| 637 |
+
def _integer(value: Any, path: str) -> int:
|
| 638 |
+
if isinstance(value, bool) or not isinstance(value, int):
|
| 639 |
+
raise IntentIRDecodeError(f"{path} must be an integer")
|
| 640 |
+
return value
|
| 641 |
+
|
| 642 |
+
|
| 643 |
+
def _number(value: Any, path: str) -> float:
|
| 644 |
+
if (
|
| 645 |
+
isinstance(value, bool)
|
| 646 |
+
or not isinstance(value, (int, float))
|
| 647 |
+
or not math.isfinite(float(value))
|
| 648 |
+
):
|
| 649 |
+
raise IntentIRDecodeError(f"{path} must be a finite number")
|
| 650 |
+
return float(value)
|
| 651 |
+
|
| 652 |
+
|
| 653 |
+
def _string_tuple(value: Any, path: str) -> tuple[str, ...]:
|
| 654 |
+
return tuple(
|
| 655 |
+
_string(item, f"{path}[{index}]") for index, item in enumerate(_array(value, path))
|
| 656 |
+
)
|
| 657 |
+
|
| 658 |
+
|
| 659 |
+
def _enum(enum_type: type[_E], value: Any, path: str) -> _E:
|
| 660 |
+
value = _string(value, path)
|
| 661 |
+
try:
|
| 662 |
+
return enum_type(value)
|
| 663 |
+
except ValueError as exc:
|
| 664 |
+
allowed = ", ".join(repr(item.value) for item in enum_type)
|
| 665 |
+
raise IntentIRDecodeError(
|
| 666 |
+
f"{path} has unknown value {value!r}; expected one of {allowed}"
|
| 667 |
+
) from exc
|
| 668 |
+
|
| 669 |
+
|
| 670 |
+
def _check_fields(
|
| 671 |
+
value: Mapping[str, Any],
|
| 672 |
+
allowed: set[str],
|
| 673 |
+
required: set[str],
|
| 674 |
+
path: str,
|
| 675 |
+
) -> None:
|
| 676 |
+
unknown = sorted(set(value) - allowed)
|
| 677 |
+
if unknown:
|
| 678 |
+
raise IntentIRDecodeError(f"{path} contains unknown fields: {', '.join(unknown)}")
|
| 679 |
+
missing = sorted(required - set(value))
|
| 680 |
+
if missing:
|
| 681 |
+
raise IntentIRDecodeError(f"{path} is missing required fields: {', '.join(missing)}")
|
| 682 |
+
|
| 683 |
+
|
| 684 |
+
INTENT_IR_SCHEMA_REGISTRY = IRSchemaRegistry(
|
| 685 |
+
schemas=(
|
| 686 |
+
SchemaSpec(
|
| 687 |
+
LEGACY_INTENT_IR_SCHEMA_VERSION,
|
| 688 |
+
"Legacy Intent IR scaffold without explicit node grounding",
|
| 689 |
+
),
|
| 690 |
+
SchemaSpec(
|
| 691 |
+
INTENT_IR_SCHEMA_VERSION,
|
| 692 |
+
"Closed Intent IR v1 wire contract",
|
| 693 |
+
),
|
| 694 |
+
),
|
| 695 |
+
migrations=(
|
| 696 |
+
MigrationSpec(
|
| 697 |
+
migration_id=INTENT_IR_V0_1_TO_V1_MIGRATION_ID,
|
| 698 |
+
source_schema_id=LEGACY_INTENT_IR_SCHEMA_VERSION,
|
| 699 |
+
destination_schema_id=INTENT_IR_SCHEMA_VERSION,
|
| 700 |
+
transform=_registry_migrate_v0_1,
|
| 701 |
+
lossy=True,
|
| 702 |
+
description=(
|
| 703 |
+
"Classify legacy node grounding and canonicalize declared "
|
| 704 |
+
"set-like collections with explicit losses"
|
| 705 |
+
),
|
| 706 |
+
),
|
| 707 |
+
),
|
| 708 |
+
)
|
| 709 |
+
|
| 710 |
+
|
| 711 |
+
__all__ = [
|
| 712 |
+
"INTENT_IR_SCHEMA_REGISTRY",
|
| 713 |
+
"INTENT_IR_V0_1_TO_V1_MIGRATION_ID",
|
| 714 |
+
"IntentIRDecodeError",
|
| 715 |
+
"IntentIRMigrationResult",
|
| 716 |
+
"MigrationDiagnostic",
|
| 717 |
+
"MigrationSeverity",
|
| 718 |
+
"decode_intent_ir",
|
| 719 |
+
"decode_intent_ir_with_migration",
|
| 720 |
+
"migrate_intent_ir",
|
| 721 |
+
]
|
releases/20261004-retained-checkpoints-v1/source/8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855/ipfs_datasets_py/logic/ui_ux_ir/schema.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
releases/20261004-retained-checkpoints-v1/source/8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py
ADDED
|
@@ -0,0 +1,512 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Shared experimental 384D source-to-typed-IR training and batched inference.
|
| 2 |
+
|
| 3 |
+
The baseline and semantic strategies share transferred Legal weights, vocabulary,
|
| 4 |
+
input transformation and batching. Semantic selection uses free-running tuning
|
| 5 |
+
predictions. Native validation is local shape evidence, never semantic proof.
|
| 6 |
+
Published v1 implementations and checkpoints are intentionally untouched.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
from copy import deepcopy
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
import math
|
| 14 |
+
from pathlib import Path
|
| 15 |
+
import time
|
| 16 |
+
|
| 17 |
+
from ....optimizers.logic_theorem_optimizer import domain_384_autoencoder as native
|
| 18 |
+
from ....optimizers.logic_theorem_optimizer import modal_latent_formula as numerical
|
| 19 |
+
from ....optimizers.logic_theorem_optimizer import legal_formula_codec as legal_codec
|
| 20 |
+
|
| 21 |
+
SCHEMA = "shared-source-384-autoencoder/v2"
|
| 22 |
+
DOMAINS = (*native.DOMAINS, "legal_ir")
|
| 23 |
+
DIMENSION = 384
|
| 24 |
+
MAX_BYTES = native.MAX_BYTES
|
| 25 |
+
FALSE = native.FALSE
|
| 26 |
+
_require, _raw, digest = native._require, native._raw, native.digest
|
| 27 |
+
_MISSING = object()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def validate_target(domain, target):
|
| 31 |
+
if domain != "legal_ir":
|
| 32 |
+
return native.validate_target(domain, target)
|
| 33 |
+
legal_codec._rule(target)
|
| 34 |
+
return {"valid": True, "domain_id": domain, "kind": "canonical_deontic_rule",
|
| 35 |
+
"canonical_ir": deepcopy(target), "scope": "one_canonical_deontic_rule", **FALSE}
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _implementation():
|
| 39 |
+
return {"runtime_sha256": hashlib.sha256(Path(__file__).read_bytes()).hexdigest(),
|
| 40 |
+
"native": native._implementation(), "numerical": numerical._implementation(),
|
| 41 |
+
"legal_codec_sha256": hashlib.sha256(Path(legal_codec.__file__).read_bytes()).hexdigest()}
|
| 42 |
+
|
| 43 |
+
|
| 44 |
+
def _rows(domain, rows, *, training):
|
| 45 |
+
_require(domain in DOMAINS, "unsupported source decoder domain")
|
| 46 |
+
# Reuse the closed provenance and numerical row checks without invoking a
|
| 47 |
+
# different domain's target validator for Legal.
|
| 48 |
+
if domain in native.DOMAINS:
|
| 49 |
+
return native._rows(domain, rows, training=training)
|
| 50 |
+
_require(type(rows) is list and 1 <= len(rows) <= 4096, "bounded nonempty rows required")
|
| 51 |
+
fields = {"id", "source_text", "embedding"} | ({"target"} if training else set())
|
| 52 |
+
_require(all(type(row) is dict and set(row) == fields for row in rows), "closed domain row schema required")
|
| 53 |
+
native._rows("intent_ir", [{key: row[key] for key in ("id", "source_text", "embedding")} for row in rows], training=False)
|
| 54 |
+
if training:
|
| 55 |
+
for row in rows:
|
| 56 |
+
validate_target(domain, row["target"])
|
| 57 |
+
return deepcopy(rows)
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
def _leaves(value, path=()):
|
| 61 |
+
if type(value) in (dict, list) and not value:
|
| 62 |
+
return {path: value}
|
| 63 |
+
if type(value) is dict:
|
| 64 |
+
return {item: leaf for key in sorted(value) for item, leaf in _leaves(value[key], (*path, key)).items()}
|
| 65 |
+
if type(value) is list:
|
| 66 |
+
return {item: leaf for index, child in enumerate(value) for item, leaf in _leaves(child, (*path, index)).items()}
|
| 67 |
+
return {path: value}
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _token_records(value, path=()):
|
| 71 |
+
"""Canonical JSON tokens with exact paths; keys never count as leaf values."""
|
| 72 |
+
if type(value) is dict:
|
| 73 |
+
if not value:
|
| 74 |
+
return [("{", "leaf", path), ("}", "leaf", path)]
|
| 75 |
+
result = [("{", "structure", path)]
|
| 76 |
+
for index, key in enumerate(sorted(value)):
|
| 77 |
+
if index:
|
| 78 |
+
result.append((",", "structure", path))
|
| 79 |
+
result.extend([(_raw(key).decode(), "key", path), (":", "structure", path)])
|
| 80 |
+
result.extend(_token_records(value[key], (*path, key)))
|
| 81 |
+
return result + [("}", "structure", path)]
|
| 82 |
+
if type(value) is list:
|
| 83 |
+
if not value:
|
| 84 |
+
return [("[", "leaf", path), ("]", "leaf", path)]
|
| 85 |
+
result = [("[", "structure", path)]
|
| 86 |
+
for index, child in enumerate(value):
|
| 87 |
+
if index:
|
| 88 |
+
result.append((",", "structure", path))
|
| 89 |
+
result.extend(_token_records(child, (*path, index)))
|
| 90 |
+
return result + [("]", "structure", path)]
|
| 91 |
+
return [(_raw(value).decode(), "leaf", path)]
|
| 92 |
+
|
| 93 |
+
|
| 94 |
+
def _varying_paths(rows):
|
| 95 |
+
leaves = [_leaves(row["target"]) for row in rows]
|
| 96 |
+
paths = set().union(*(row.keys() for row in leaves))
|
| 97 |
+
# None tags an absent path; real JSON null is encoded as b"null".
|
| 98 |
+
return sorted((list(path) for path in paths if len({
|
| 99 |
+
_raw(row[path]) if path in row else None for row in leaves}) > 1), key=_raw)
|
| 100 |
+
|
| 101 |
+
|
| 102 |
+
def _same_leaf(actual, expected):
|
| 103 |
+
if actual is _MISSING or expected is _MISSING:
|
| 104 |
+
return actual is expected
|
| 105 |
+
return _raw(actual) == _raw(expected)
|
| 106 |
+
|
| 107 |
+
|
| 108 |
+
def _config(options, parent):
|
| 109 |
+
defaults = dict(strategy="semantic_v2", epochs=500, max_seconds=180., learning_rate=.003,
|
| 110 |
+
batch_size=32, seed=1729, patience=30, max_optimizer_steps=None, reconstruction_weight=.1,
|
| 111 |
+
max_target_tokens=512, validation_interval=5, semantic_weight=4.,
|
| 112 |
+
constant_weight=1., structure_weight=.25, input_normalization="center_rms",
|
| 113 |
+
embedding_provenance={"model_id": "caller_supplied", "verified_by_runtime": False})
|
| 114 |
+
_require(options is None or type(options) is dict and set(options) <= set(defaults), "unknown training option")
|
| 115 |
+
defaults.update(options or {})
|
| 116 |
+
_require(defaults["strategy"] in ("reference_ce", "semantic_v2"), "unknown training strategy")
|
| 117 |
+
_require(defaults["input_normalization"] in ("none", "center_rms"), "unknown input normalization")
|
| 118 |
+
for name, low, high in (("epochs", 1, 2000), ("batch_size", 1, 256), ("seed", 0, 2**31-1),
|
| 119 |
+
("patience", 0, 2000), ("max_target_tokens", 4, 1024), ("validation_interval", 1, 1000)):
|
| 120 |
+
value = defaults[name]
|
| 121 |
+
_require(type(value) is int and low <= value <= high, "invalid " + name)
|
| 122 |
+
_require(defaults["max_optimizer_steps"] is None or type(defaults["max_optimizer_steps"]) is int
|
| 123 |
+
and 1 <= defaults["max_optimizer_steps"] <= 1000000, "invalid optimizer step budget")
|
| 124 |
+
for name, high in (("max_seconds", 3600), ("learning_rate", .1), ("reconstruction_weight", 100),
|
| 125 |
+
("semantic_weight", 100), ("constant_weight", 100), ("structure_weight", 100)):
|
| 126 |
+
value = defaults[name]
|
| 127 |
+
_require(type(value) in (int, float) and math.isfinite(value) and 0 < value <= high, "invalid " + name)
|
| 128 |
+
_require(type(defaults["embedding_provenance"]) is dict and len(_raw(defaults["embedding_provenance"])) <= 16384,
|
| 129 |
+
"bounded embedding provenance required")
|
| 130 |
+
return {**defaults, **{key: parent[key] for key in ("hidden_size", "token_embedding_dim", "projection_width")}}
|
| 131 |
+
|
| 132 |
+
|
| 133 |
+
def _transform(torch, rows, mode):
|
| 134 |
+
data = torch.tensor([row["embedding"] for row in rows], dtype=torch.float32)
|
| 135 |
+
if mode == "none":
|
| 136 |
+
return {"mode": mode, "mean": [0.] * DIMENSION, "scale": 1., "origin": "training_only"}
|
| 137 |
+
mean = data.mean(0)
|
| 138 |
+
# One scale preserves angles and relative coordinate scales. A floor avoids
|
| 139 |
+
# division by an almost-zero empirical spread in a degenerate corpus.
|
| 140 |
+
scale = max(float((data - mean).square().sum(1).mean().sqrt()), .01)
|
| 141 |
+
return {"mode": mode, "mean": mean.tolist(), "scale": scale, "origin": "training_only"}
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
def _encoded(torch, rows, vocabulary, varying_paths, config, transform):
|
| 145 |
+
positions = {token: index for index, token in enumerate(vocabulary)}
|
| 146 |
+
varying = {tuple(path) for path in varying_paths}
|
| 147 |
+
encoded, weights = [], []
|
| 148 |
+
for row in rows:
|
| 149 |
+
records = _token_records(row["target"])
|
| 150 |
+
_require(len(records) + 2 <= config["max_target_tokens"], "target exceeds configured token limit")
|
| 151 |
+
_require(all(token in positions for token, _, _ in records), "target token outside training vocabulary")
|
| 152 |
+
encoded.append([1] + [positions[token] for token, _, _ in records] + [2])
|
| 153 |
+
weights.append([0.] + [1. if config["strategy"] == "reference_ce" else
|
| 154 |
+
config["semantic_weight"] if role == "leaf" and path in varying else
|
| 155 |
+
config["constant_weight"] if role == "leaf" else config["structure_weight"]
|
| 156 |
+
for _, role, path in records] + [1.])
|
| 157 |
+
width = max(map(len, encoded))
|
| 158 |
+
labels = torch.tensor([row + [0] * (width-len(row)) for row in encoded], dtype=torch.long)
|
| 159 |
+
weight = torch.tensor([row + [0.] * (width-len(row)) for row in weights], dtype=torch.float32)
|
| 160 |
+
raw = torch.tensor([row["embedding"] for row in rows], dtype=torch.float32)
|
| 161 |
+
normalized = (raw - torch.tensor(transform["mean"])) / transform["scale"]
|
| 162 |
+
return normalized, labels, weight
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _loss(torch, model, data, labels, weights, config):
|
| 166 |
+
projected, logits = model(data, labels[:, :-1])
|
| 167 |
+
ce = torch.nn.functional.cross_entropy(logits.flatten(0, 1), labels[:, 1:].reshape(-1),
|
| 168 |
+
ignore_index=0, reduction="none").reshape(labels.shape[0], -1)
|
| 169 |
+
mask = labels[:, 1:] != 0
|
| 170 |
+
token_ce = ce.sum() / mask.sum()
|
| 171 |
+
weighted = (ce * weights[:, 1:]).sum() / weights[:, 1:].sum()
|
| 172 |
+
# Report and optimize reconstruction in the original embedding coordinates.
|
| 173 |
+
mse = (projected - data).square().mean() * config["_input_scale"]**2
|
| 174 |
+
return weighted + config["reconstruction_weight"] * mse, token_ce, weighted, mse
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _greedy(torch, model, data, max_tokens):
|
| 178 |
+
"""One recurrent step per batch, with no target strings or candidate memory."""
|
| 179 |
+
projected = model.project(data)
|
| 180 |
+
hidden = model.start(projected)
|
| 181 |
+
_require(bool(torch.isfinite(projected).all()), "nonfinite reconstructed embedding")
|
| 182 |
+
current = torch.ones((len(data), 1), dtype=torch.long)
|
| 183 |
+
active = torch.ones(len(data), dtype=torch.bool)
|
| 184 |
+
sequences, ended = [[] for _ in range(len(data))], [False] * len(data)
|
| 185 |
+
for _ in range(max_tokens - 1):
|
| 186 |
+
logits, hidden = model.next_logits(current, hidden)
|
| 187 |
+
_require(bool(torch.isfinite(logits).all()) and bool(torch.isfinite(hidden).all()), "nonfinite generated state")
|
| 188 |
+
indices = logits[:, -1].argmax(-1)
|
| 189 |
+
for index, token in enumerate(indices.tolist()):
|
| 190 |
+
if not active[index]:
|
| 191 |
+
continue
|
| 192 |
+
if token == 2:
|
| 193 |
+
ended[index] = True
|
| 194 |
+
active[index] = False
|
| 195 |
+
elif token in (0, 1):
|
| 196 |
+
active[index] = False
|
| 197 |
+
else:
|
| 198 |
+
sequences[index].append(token)
|
| 199 |
+
if not bool(active.any()):
|
| 200 |
+
break
|
| 201 |
+
current = indices.unsqueeze(1)
|
| 202 |
+
return projected, sequences, ended
|
| 203 |
+
|
| 204 |
+
|
| 205 |
+
def _candidate(domain, indices, ended, vocabulary):
|
| 206 |
+
tokens = [vocabulary[index] for index in indices]
|
| 207 |
+
candidate, reason = None, None
|
| 208 |
+
if ended:
|
| 209 |
+
try:
|
| 210 |
+
value = native._parse("".join(tokens))
|
| 211 |
+
candidate = validate_target(domain, value)["canonical_ir"]
|
| 212 |
+
except (ValueError, TypeError, KeyError, RecursionError) as exc:
|
| 213 |
+
reason = str(exc)[:512]
|
| 214 |
+
return candidate, tokens, reason
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def _validation(torch, model, batch, rows, vocabulary, paths, domain, config):
|
| 218 |
+
model.eval()
|
| 219 |
+
with torch.inference_mode():
|
| 220 |
+
objective, ce, weighted, mse = _loss(torch, model, *batch, config)
|
| 221 |
+
_require(all(bool(torch.isfinite(value)) for value in (objective, ce, weighted, mse)), "nonfinite validation")
|
| 222 |
+
_, sequences, ended = _greedy(torch, model, batch[0], config["max_target_tokens"])
|
| 223 |
+
exact = valid = leaf_correct = leaf_count = 0
|
| 224 |
+
for row, sequence, end in zip(rows, sequences, ended):
|
| 225 |
+
candidate, _, _ = _candidate(domain, sequence, end, vocabulary)
|
| 226 |
+
exact += candidate is not None and _raw(candidate) == _raw(row["target"])
|
| 227 |
+
valid += candidate is not None
|
| 228 |
+
actual = _leaves(candidate) if candidate is not None else {}
|
| 229 |
+
gold = _leaves(row["target"])
|
| 230 |
+
# Score train-derived varying paths, even when generation is malformed.
|
| 231 |
+
for path in map(tuple, paths):
|
| 232 |
+
leaf_count += 1
|
| 233 |
+
leaf_correct += candidate is not None and _same_leaf(actual.get(path, _MISSING), gold.get(path, _MISSING))
|
| 234 |
+
return dict(objective=float(objective), token_cross_entropy=float(ce), weighted_cross_entropy=float(weighted),
|
| 235 |
+
embedding_mse=float(mse), exact_targets=int(exact), valid_candidates=int(valid), count=len(rows),
|
| 236 |
+
semantic_leaf_correct=int(leaf_correct), semantic_leaf_count=leaf_count,
|
| 237 |
+
semantic_leaf_accuracy=leaf_correct / max(leaf_count, 1),
|
| 238 |
+
teacher_forcing_for_selection=True, free_running_metrics_teacher_forced=False,
|
| 239 |
+
teacher_forcing_selection_role=("primary_objective" if config["strategy"] == "reference_ce" else "tertiary_tiebreaker"))
|
| 240 |
+
|
| 241 |
+
|
| 242 |
+
def _selection(observed, strategy):
|
| 243 |
+
if strategy == "reference_ce":
|
| 244 |
+
return (-observed["objective"],)
|
| 245 |
+
return (observed["exact_targets"], observed["semantic_leaf_accuracy"], -observed["objective"])
|
| 246 |
+
|
| 247 |
+
|
| 248 |
+
def _parent(parent_projection):
|
| 249 |
+
if type(parent_projection) is dict and set(parent_projection) == {"path", "sha256"}:
|
| 250 |
+
path = Path(parent_projection["path"])
|
| 251 |
+
_require(path.is_file() and 0 < path.stat().st_size <= MAX_BYTES, "bounded parent required")
|
| 252 |
+
raw = path.read_bytes()
|
| 253 |
+
_require(hashlib.sha256(raw).hexdigest() == parent_projection["sha256"], "parent hash differs")
|
| 254 |
+
return native._parse(raw), parent_projection["sha256"], (path, raw)
|
| 255 |
+
return deepcopy(parent_projection), digest(parent_projection), None
|
| 256 |
+
|
| 257 |
+
|
| 258 |
+
def _length_buckets(torch, lengths, batch_size, generator):
|
| 259 |
+
# Shuffle before a stable length sort so identical target lengths never
|
| 260 |
+
# retain source-order composition groups across epochs.
|
| 261 |
+
order = torch.randperm(len(lengths), generator=generator)
|
| 262 |
+
order = order[lengths[order].argsort(stable=True)]
|
| 263 |
+
buckets = [order[offset:offset+batch_size] for offset in range(0, len(order), batch_size)]
|
| 264 |
+
return [buckets[index] for index in torch.randperm(len(buckets), generator=generator).tolist()]
|
| 265 |
+
|
| 266 |
+
|
| 267 |
+
def train(domain, training_rows, validation_rows, *, parent_projection, config=None):
|
| 268 |
+
"""Train an isolated candidate; validation selects weights, no test API exists."""
|
| 269 |
+
started = time.monotonic()
|
| 270 |
+
parent, parent_sha, parent_file = _parent(parent_projection)
|
| 271 |
+
training = _rows(domain, training_rows, training=True)
|
| 272 |
+
validation = _rows(domain, validation_rows, training=True)
|
| 273 |
+
for key in (lambda row: row["id"], lambda row: " ".join(row["source_text"].casefold().split()),
|
| 274 |
+
lambda row: digest(row["embedding"])):
|
| 275 |
+
_require(not {key(row) for row in training} & {key(row) for row in validation},
|
| 276 |
+
"training/validation identity, source, or embedding overlap")
|
| 277 |
+
options = _config(config, parent["config"])
|
| 278 |
+
paths = _varying_paths(training)
|
| 279 |
+
vocabulary = [*native.SPECIAL, *sorted({token for row in training for token, _, _ in _token_records(row["target"])})]
|
| 280 |
+
_require(len(vocabulary) <= 4096, "training vocabulary exceeds bound")
|
| 281 |
+
codec = {"schema": "typed-json-lexical/v1", "target_vocabulary": vocabulary}
|
| 282 |
+
with native._cpu() as torch:
|
| 283 |
+
numerical.validate_checkpoint(parent)
|
| 284 |
+
_require(parent["binding"]["dimension"] == DIMENSION and parent["progress"]["optimizer_steps"] > 0,
|
| 285 |
+
"trained 384D Legal parent required")
|
| 286 |
+
transform = _transform(torch, training, options["input_normalization"])
|
| 287 |
+
settings = {**options, "_input_scale": transform["scale"]}
|
| 288 |
+
batch = _encoded(torch, training, vocabulary, paths, options, transform)
|
| 289 |
+
tuning = _encoded(torch, validation, vocabulary, paths, options, transform)
|
| 290 |
+
model, lineage = native._transfer(parent, codec, options)
|
| 291 |
+
optimizer = torch.optim.Adam(model.parameters(), lr=options["learning_rate"])
|
| 292 |
+
before = _validation(torch, model, tuning, validation, vocabulary, paths, domain, settings)
|
| 293 |
+
best, best_state = before, deepcopy(model.state_dict())
|
| 294 |
+
selected_epoch = selected_steps = steps = examples_seen = tokens_seen = stale = last_validated_steps = 0
|
| 295 |
+
selected_epoch_complete = True
|
| 296 |
+
optimizer_seconds = validation_seconds = 0.
|
| 297 |
+
history, stop = [], "epoch_budget"
|
| 298 |
+
generator = torch.Generator().manual_seed(options["seed"])
|
| 299 |
+
lengths = (batch[1] != 0).sum(1)
|
| 300 |
+
fit_started = time.monotonic()
|
| 301 |
+
for epoch in range(1, options["epochs"] + 1):
|
| 302 |
+
model.train()
|
| 303 |
+
completed = True
|
| 304 |
+
for index in _length_buckets(torch, lengths, options["batch_size"], generator):
|
| 305 |
+
if options["max_optimizer_steps"] is not None and steps >= options["max_optimizer_steps"]:
|
| 306 |
+
completed, stop = False, "optimizer_step_budget"
|
| 307 |
+
break
|
| 308 |
+
if time.monotonic() - fit_started >= options["max_seconds"]:
|
| 309 |
+
completed, stop = False, "deadline"
|
| 310 |
+
break
|
| 311 |
+
tick = time.monotonic()
|
| 312 |
+
width = int((batch[1][index] != 0).sum(1).max())
|
| 313 |
+
values = (batch[0][index], batch[1][index, :width], batch[2][index, :width])
|
| 314 |
+
optimizer.zero_grad(set_to_none=True)
|
| 315 |
+
loss, _, _, _ = _loss(torch, model, *values, settings)
|
| 316 |
+
_require(bool(torch.isfinite(loss)), "nonfinite training objective")
|
| 317 |
+
loss.backward()
|
| 318 |
+
norm = torch.nn.utils.clip_grad_norm_(model.parameters(), 5.)
|
| 319 |
+
_require(bool(torch.isfinite(norm)), "nonfinite gradient")
|
| 320 |
+
optimizer.step()
|
| 321 |
+
optimizer_seconds += time.monotonic() - tick
|
| 322 |
+
steps += 1
|
| 323 |
+
examples_seen += len(index)
|
| 324 |
+
tokens_seen += int((values[1][:, 1:] != 0).sum())
|
| 325 |
+
if not completed and steps == last_validated_steps:
|
| 326 |
+
break
|
| 327 |
+
reached_steps = options["max_optimizer_steps"] is not None and steps >= options["max_optimizer_steps"]
|
| 328 |
+
if completed and epoch % options["validation_interval"] and epoch != options["epochs"] and not reached_steps:
|
| 329 |
+
continue
|
| 330 |
+
tick = time.monotonic()
|
| 331 |
+
observed = _validation(torch, model, tuning, validation, vocabulary, paths, domain, settings)
|
| 332 |
+
validation_seconds += time.monotonic() - tick
|
| 333 |
+
last_validated_steps = steps
|
| 334 |
+
# A final tuning pass can finish after the optimizer deadline. The
|
| 335 |
+
# actual elapsed time includes it; every selected state was checked.
|
| 336 |
+
selected = _selection(observed, options["strategy"]) > _selection(best, options["strategy"])
|
| 337 |
+
if selected:
|
| 338 |
+
best, best_state, selected_epoch, stale = observed, deepcopy(model.state_dict()), epoch, 0
|
| 339 |
+
selected_steps, selected_epoch_complete = steps, completed
|
| 340 |
+
else:
|
| 341 |
+
stale += 1
|
| 342 |
+
history.append({"epoch": epoch, "epoch_complete": completed, "optimizer_steps": steps, **observed, "selected": selected})
|
| 343 |
+
if not completed:
|
| 344 |
+
break
|
| 345 |
+
if reached_steps:
|
| 346 |
+
stop = "optimizer_step_budget"
|
| 347 |
+
break
|
| 348 |
+
if options["patience"] and stale >= options["patience"]:
|
| 349 |
+
stop = "validation_patience"
|
| 350 |
+
break
|
| 351 |
+
if time.monotonic() - fit_started >= options["max_seconds"]:
|
| 352 |
+
stop = "deadline"
|
| 353 |
+
break
|
| 354 |
+
_require(steps > 0, "no training steps completed")
|
| 355 |
+
fit_seconds = time.monotonic() - fit_started
|
| 356 |
+
model.load_state_dict(best_state)
|
| 357 |
+
weights = {name: tensor.detach().tolist() for name, tensor in model.state_dict().items()}
|
| 358 |
+
def manifest(rows):
|
| 359 |
+
return [{"id": row["id"], "source_sha256": hashlib.sha256(row["source_text"].encode()).hexdigest(),
|
| 360 |
+
"normalized_source_sha256": hashlib.sha256(" ".join(row["source_text"].casefold().split()).encode()).hexdigest(),
|
| 361 |
+
"embedding_sha256": digest(row["embedding"]), "target_sha256": digest(row["target"])} for row in rows]
|
| 362 |
+
metrics = dict(before_validation=before, selected_validation=best, selected_epoch=selected_epoch,
|
| 363 |
+
optimizer_steps=steps, selected_optimizer_steps=selected_steps, selected_epoch_complete=selected_epoch_complete,
|
| 364 |
+
examples_seen=examples_seen, training_tokens=tokens_seen,
|
| 365 |
+
optimizer_seconds=optimizer_seconds, validation_seconds=validation_seconds, fit_seconds=fit_seconds,
|
| 366 |
+
optimizer_tokens_per_second=tokens_seen/max(optimizer_seconds, 1e-9),
|
| 367 |
+
optimizer_examples_per_second=examples_seen/max(optimizer_seconds, 1e-9),
|
| 368 |
+
fit_tokens_per_second=tokens_seen/max(fit_seconds, 1e-9),
|
| 369 |
+
fit_examples_per_second=examples_seen/max(fit_seconds, 1e-9),
|
| 370 |
+
pre_checkpoint_seconds=time.monotonic()-started, stopped_reason=stop, history=history,
|
| 371 |
+
test_used_for_selection=False, selection=("weighted_teacher_forced_objective" if options["strategy"] == "reference_ce"
|
| 372 |
+
else "free_running_exact_then_train_variable_leaves_then_weighted_objective"))
|
| 373 |
+
checkpoint = dict(schema=SCHEMA, domain_id=domain, dimension=DIMENSION, architecture=numerical.ARCHITECTURE,
|
| 374 |
+
codec=codec, config=options, implementation=_implementation(), parent_sha256=parent_sha,
|
| 375 |
+
parent_binding=deepcopy(parent["binding"]), lineage=lineage, model_state=weights,
|
| 376 |
+
weights_sha256=digest(weights), input_transform=transform, semantic_paths=paths,
|
| 377 |
+
training_manifest=manifest(training), validation_manifest=manifest(validation), training=metrics, **FALSE)
|
| 378 |
+
_require(len(_raw(checkpoint)) <= MAX_BYTES, "checkpoint exceeds bound")
|
| 379 |
+
if parent_file:
|
| 380 |
+
_require(parent_file[0].read_bytes() == parent_file[1], "parent changed during training")
|
| 381 |
+
Runtime(checkpoint)
|
| 382 |
+
return {"checkpoint": checkpoint, "metrics": deepcopy(metrics)}
|
| 383 |
+
|
| 384 |
+
|
| 385 |
+
class Runtime:
|
| 386 |
+
"""Frozen shared numerical inference without target access or source parsing."""
|
| 387 |
+
def __init__(self, checkpoint):
|
| 388 |
+
fields = {"schema", "domain_id", "dimension", "architecture", "codec", "config", "implementation",
|
| 389 |
+
"parent_sha256", "parent_binding", "lineage", "model_state", "weights_sha256", "input_transform",
|
| 390 |
+
"semantic_paths", "training_manifest", "validation_manifest", "training", *FALSE}
|
| 391 |
+
_require(type(checkpoint) is dict and set(checkpoint) == fields and checkpoint["schema"] == SCHEMA,
|
| 392 |
+
"closed source v2 checkpoint required")
|
| 393 |
+
_require(len(_raw(checkpoint)) <= MAX_BYTES, "checkpoint exceeds bound")
|
| 394 |
+
_require(checkpoint["domain_id"] in DOMAINS and type(checkpoint["dimension"]) is int and checkpoint["dimension"] == DIMENSION,
|
| 395 |
+
"checkpoint requires genuine 384D domain")
|
| 396 |
+
_require(all(checkpoint[key] is False for key in FALSE), "checkpoint cannot grant authority")
|
| 397 |
+
_require(checkpoint["implementation"] == _implementation(), "implementation pins differ")
|
| 398 |
+
_require(checkpoint["architecture"] == numerical.ARCHITECTURE, "architecture differs")
|
| 399 |
+
config = checkpoint["config"]
|
| 400 |
+
shape = {name: config[name] for name in ("hidden_size", "token_embedding_dim", "projection_width")}
|
| 401 |
+
for name, low, high in (("hidden_size", 8, 128), ("token_embedding_dim", 8, 64), ("projection_width", 1, 64)):
|
| 402 |
+
_require(type(shape[name]) is int and low <= shape[name] <= high, "invalid model shape")
|
| 403 |
+
_require(_config({key: value for key, value in config.items() if key not in shape}, shape) == config,
|
| 404 |
+
"configuration differs")
|
| 405 |
+
codec = checkpoint["codec"]
|
| 406 |
+
_require(type(codec) is dict and set(codec) == {"schema", "target_vocabulary"} and codec["schema"] == "typed-json-lexical/v1", "invalid codec")
|
| 407 |
+
vocabulary = codec["target_vocabulary"]
|
| 408 |
+
_require(type(vocabulary) is list and 4 <= len(vocabulary) <= 4096 and vocabulary[:3] == list(native.SPECIAL)
|
| 409 |
+
and all(type(token) is str and len(token) <= 16384 and native._TOKEN.fullmatch(token) for token in vocabulary[3:])
|
| 410 |
+
and vocabulary[3:] == sorted(set(vocabulary[3:])), "invalid training vocabulary")
|
| 411 |
+
_require(digest(checkpoint["model_state"]) == checkpoint["weights_sha256"], "weight digest differs")
|
| 412 |
+
transform = checkpoint["input_transform"]
|
| 413 |
+
_require(type(transform) is dict and set(transform) == {"mode", "mean", "scale", "origin"}
|
| 414 |
+
and transform["mode"] == config["input_normalization"] and transform["origin"] == "training_only", "invalid input transform")
|
| 415 |
+
native._vector(transform["mean"])
|
| 416 |
+
_require(type(transform["scale"]) in (int, float) and math.isfinite(transform["scale"]) and .01 <= transform["scale"] <= 1e8,
|
| 417 |
+
"invalid input scale")
|
| 418 |
+
if transform["mode"] == "none":
|
| 419 |
+
_require(transform["mean"] == [0.]*DIMENSION and transform["scale"] == 1., "identity transform differs")
|
| 420 |
+
paths = checkpoint["semantic_paths"]
|
| 421 |
+
_require(type(paths) is list and len(paths) <= 4096 and all(type(path) is list and len(path) <= 128
|
| 422 |
+
and all(type(part) in (int, str) for part in path) for path in paths)
|
| 423 |
+
and paths == sorted(paths, key=_raw) and len({_raw(path) for path in paths}) == len(paths), "invalid semantic paths")
|
| 424 |
+
for name in ("training_manifest", "validation_manifest"):
|
| 425 |
+
rows = checkpoint[name]
|
| 426 |
+
_require(type(rows) is list and 1 <= len(rows) <= 4096, "invalid split manifest")
|
| 427 |
+
_require(all(type(row) is dict and set(row) == {"id", "source_sha256", "normalized_source_sha256", "embedding_sha256", "target_sha256"}
|
| 428 |
+
and type(row["id"]) is str and 0 < len(row["id"]) <= 256
|
| 429 |
+
and all(type(row[key]) is str and native._SHA.fullmatch(row[key]) for key in row if key != "id") for row in rows), "invalid split row")
|
| 430 |
+
_require(len({row["id"] for row in rows}) == len(rows), "duplicate split ID")
|
| 431 |
+
for key in ("id", "source_sha256", "normalized_source_sha256", "embedding_sha256"):
|
| 432 |
+
_require(not {row[key] for row in checkpoint["training_manifest"]} & {row[key] for row in checkpoint["validation_manifest"]}, "checkpoint split overlap")
|
| 433 |
+
training = checkpoint["training"]
|
| 434 |
+
_require(type(training) is dict and type(training.get("optimizer_steps")) is int and training["optimizer_steps"] > 0
|
| 435 |
+
and type(training.get("selected_epoch")) is int and 0 <= training["selected_epoch"] <= config["epochs"]
|
| 436 |
+
and training.get("test_used_for_selection") is False, "invalid training provenance")
|
| 437 |
+
_require(type(checkpoint["parent_sha256"]) is str and native._SHA.fullmatch(checkpoint["parent_sha256"])
|
| 438 |
+
and type(checkpoint["parent_binding"]) is dict and checkpoint["parent_binding"].get("dimension") == DIMENSION,
|
| 439 |
+
"invalid parent binding")
|
| 440 |
+
with native._cpu():
|
| 441 |
+
model = numerical._model({"dimension": DIMENSION}, codec, config)
|
| 442 |
+
state = checkpoint["model_state"]
|
| 443 |
+
_require(type(state) is dict and set(state) == set(model.state_dict()), "model tensor names differ")
|
| 444 |
+
model.load_state_dict({name: numerical._tensor(state[name], template, name)
|
| 445 |
+
for name, template in model.state_dict().items()}, strict=True)
|
| 446 |
+
self.checkpoint, self.model = deepcopy(checkpoint), model.eval()
|
| 447 |
+
|
| 448 |
+
def describe(self):
|
| 449 |
+
return dict(schema=SCHEMA, domain_id=self.checkpoint["domain_id"], dimension=DIMENSION,
|
| 450 |
+
weights_sha256=self.checkpoint["weights_sha256"], strategy=self.checkpoint["config"]["strategy"],
|
| 451 |
+
source_text_is_neural_input=False, input_representation="source_embedding_384",
|
| 452 |
+
sample_memory_used=False, independent_source_fidelity_check_required=True,
|
| 453 |
+
zero_projection_ablation="zero_residual_branch_identity_embedding_retained", **FALSE)
|
| 454 |
+
|
| 455 |
+
def infer(self, rows, *, weight_ablation=None):
|
| 456 |
+
rows = _rows(self.checkpoint["domain_id"], rows, training=False)
|
| 457 |
+
_require(weight_ablation in (None, "zero_projection", "zero_condition", "zero_decoder"), "unknown weight ablation")
|
| 458 |
+
model = self.model if weight_ablation is None else deepcopy(self.model)
|
| 459 |
+
config, transform = self.checkpoint["config"], self.checkpoint["input_transform"]
|
| 460 |
+
vocabulary = self.checkpoint["codec"]["target_vocabulary"]
|
| 461 |
+
reports = []
|
| 462 |
+
with native._cpu() as torch, torch.inference_mode():
|
| 463 |
+
if weight_ablation:
|
| 464 |
+
for name, parameter in model.named_parameters():
|
| 465 |
+
if (weight_ablation == "zero_projection" and name.startswith("projection_")) or (
|
| 466 |
+
weight_ablation == "zero_condition" and name.startswith("condition.")) or (
|
| 467 |
+
weight_ablation == "zero_decoder" and name.startswith(("decoder.", "output."))):
|
| 468 |
+
parameter.zero_()
|
| 469 |
+
for offset in range(0, len(rows), config["batch_size"]):
|
| 470 |
+
part = rows[offset:offset+config["batch_size"]]
|
| 471 |
+
raw = torch.tensor([row["embedding"] for row in part], dtype=torch.float32)
|
| 472 |
+
data = (raw - torch.tensor(transform["mean"])) / transform["scale"]
|
| 473 |
+
projected, sequences, ended = _greedy(torch, model, data, config["max_target_tokens"])
|
| 474 |
+
reconstructed = projected * transform["scale"] + torch.tensor(transform["mean"])
|
| 475 |
+
for row, sequence, end, embedding in zip(part, sequences, ended, reconstructed):
|
| 476 |
+
candidate, tokens, reason = _candidate(self.checkpoint["domain_id"], sequence, end, vocabulary)
|
| 477 |
+
reports.append(dict(id=row["id"], source_sha256=hashlib.sha256(row["source_text"].encode()).hexdigest(),
|
| 478 |
+
status="unqualified_candidate" if candidate is not None else "fail_open_invalid_output", reason=reason,
|
| 479 |
+
candidate_ir=candidate, generated_tokens=tokens, ended=end, reconstructed_embedding=embedding.tolist(),
|
| 480 |
+
weight_ablation=weight_ablation, weights_sha256=self.checkpoint["weights_sha256"],
|
| 481 |
+
target_access=False, teacher_forcing=False, continue_planning=True, **FALSE))
|
| 482 |
+
return dict(schema=SCHEMA, domain_id=self.checkpoint["domain_id"], dimension=DIMENSION, rows=reports, **FALSE)
|
| 483 |
+
|
| 484 |
+
|
| 485 |
+
def evaluate(checkpoint, rows):
|
| 486 |
+
gold = _rows(checkpoint["domain_id"], rows, training=True)
|
| 487 |
+
report = Runtime(checkpoint).infer([{key: row[key] for key in ("id", "source_text", "embedding")} for row in gold])
|
| 488 |
+
correct = total = 0
|
| 489 |
+
for actual, expected in zip(report["rows"], gold):
|
| 490 |
+
actual["exact_target"] = actual["candidate_ir"] is not None and _raw(actual["candidate_ir"]) == _raw(expected["target"])
|
| 491 |
+
leaves = _leaves(actual["candidate_ir"]) if actual["candidate_ir"] is not None else {}
|
| 492 |
+
targets = _leaves(expected["target"])
|
| 493 |
+
for path in map(tuple, checkpoint["semantic_paths"]):
|
| 494 |
+
total += 1
|
| 495 |
+
correct += actual["candidate_ir"] is not None and _same_leaf(leaves.get(path, _MISSING), targets.get(path, _MISSING))
|
| 496 |
+
return {**report, "exact_targets": sum(row["exact_target"] for row in report["rows"]),
|
| 497 |
+
"valid_candidates": sum(row["candidate_ir"] is not None for row in report["rows"]),
|
| 498 |
+
"count": len(gold), "semantic_leaf_correct": correct, "semantic_leaf_count": total,
|
| 499 |
+
"semantic_leaf_accuracy": correct/max(total, 1)}
|
| 500 |
+
|
| 501 |
+
|
| 502 |
+
def load_checkpoint(path, *, expected_sha256, expected_domain):
|
| 503 |
+
path = Path(path)
|
| 504 |
+
_require(path.is_file() and not path.is_symlink() and 0 < path.stat().st_size <= MAX_BYTES, "bounded regular checkpoint required")
|
| 505 |
+
raw = path.read_bytes()
|
| 506 |
+
_require(hashlib.sha256(raw).hexdigest() == expected_sha256, "checkpoint bytes differ")
|
| 507 |
+
checkpoint = native._parse(raw)
|
| 508 |
+
_require(type(checkpoint) is dict and checkpoint.get("domain_id") == expected_domain, "checkpoint belongs to another domain")
|
| 509 |
+
return Runtime(checkpoint)
|
| 510 |
+
|
| 511 |
+
|
| 512 |
+
__all__ = ["SCHEMA", "DOMAINS", "DIMENSION", "train", "Runtime", "evaluate", "load_checkpoint", "validate_target"]
|
releases/20261004-retained-checkpoints-v1/source/93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56/ipfs_datasets_py/logic/intent_ir/schema.py
ADDED
|
@@ -0,0 +1,699 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Canonical, source-grounded Intent IR schema.
|
| 2 |
+
|
| 3 |
+
Intent IR models what a skill is trying to accomplish and the procedure it
|
| 4 |
+
describes. It does not authorize or execute the procedure. Raw source bodies,
|
| 5 |
+
GraphRAG indexes, embeddings, model responses, and proof artifacts live in
|
| 6 |
+
separate content-addressed artifacts and are joined through identifiers.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
from dataclasses import dataclass
|
| 13 |
+
from enum import Enum
|
| 14 |
+
from types import MappingProxyType
|
| 15 |
+
from typing import Any, Iterable, Mapping
|
| 16 |
+
|
| 17 |
+
from ..ir_core.canonical import CollectionSchema, CollectionSemantics
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
INTENT_IR_SCHEMA_VERSION = "intent-ir/v1"
|
| 21 |
+
LEGACY_INTENT_IR_SCHEMA_VERSION = "intent-ir/v0.1"
|
| 22 |
+
_IDENTIFIER_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$")
|
| 23 |
+
_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class IntentIRValidationError(ValueError):
|
| 27 |
+
"""Raised when an Intent IR document violates its canonical contract."""
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ReviewStatus(str, Enum):
|
| 31 |
+
"""Human/machine review state; never infer trust from source popularity."""
|
| 32 |
+
|
| 33 |
+
UNREVIEWED = "unreviewed"
|
| 34 |
+
MACHINE_EXTRACTED = "machine_extracted"
|
| 35 |
+
HUMAN_REVIEWED = "human_reviewed"
|
| 36 |
+
TRUSTED_FIXTURE = "trusted_fixture"
|
| 37 |
+
QUARANTINED = "quarantined"
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
class IntentKind(str, Enum):
|
| 41 |
+
"""Top-level semantic shape of an intent document."""
|
| 42 |
+
|
| 43 |
+
PROCEDURE = "procedure"
|
| 44 |
+
CAPABILITY = "capability"
|
| 45 |
+
POLICY = "policy"
|
| 46 |
+
DECLARATIVE = "declarative"
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class IntentModality(str, Enum):
|
| 50 |
+
"""Force attached to a normalized statement."""
|
| 51 |
+
|
| 52 |
+
ASSERTED = "asserted"
|
| 53 |
+
INTENDED = "intended"
|
| 54 |
+
REQUIRED = "required"
|
| 55 |
+
RECOMMENDED = "recommended"
|
| 56 |
+
PERMITTED = "permitted"
|
| 57 |
+
PROHIBITED = "prohibited"
|
| 58 |
+
|
| 59 |
+
|
| 60 |
+
class StatementKind(str, Enum):
|
| 61 |
+
"""Role of a normalized statement in the action contract."""
|
| 62 |
+
|
| 63 |
+
GOAL = "goal"
|
| 64 |
+
PRECONDITION = "precondition"
|
| 65 |
+
POSTCONDITION = "postcondition"
|
| 66 |
+
INVARIANT = "invariant"
|
| 67 |
+
GUARD = "guard"
|
| 68 |
+
EFFECT = "effect"
|
| 69 |
+
ASSUMPTION = "assumption"
|
| 70 |
+
FAILURE = "failure"
|
| 71 |
+
VERIFICATION = "verification"
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
class ControlEdgeKind(str, Enum):
|
| 75 |
+
"""Control-flow relationship between two actions."""
|
| 76 |
+
|
| 77 |
+
NEXT = "next"
|
| 78 |
+
ON_SUCCESS = "on_success"
|
| 79 |
+
ON_FAILURE = "on_failure"
|
| 80 |
+
CONDITIONAL = "conditional"
|
| 81 |
+
RETRY = "retry"
|
| 82 |
+
PARALLEL = "parallel"
|
| 83 |
+
JOIN = "join"
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
class NodeGrounding(str, Enum):
|
| 87 |
+
"""Whether a semantic node is stated by evidence or derived from it."""
|
| 88 |
+
|
| 89 |
+
GROUNDED = "grounded"
|
| 90 |
+
INFERRED = "inferred"
|
| 91 |
+
|
| 92 |
+
|
| 93 |
+
# Alias retained for callers that describe this dimension as a "kind".
|
| 94 |
+
GroundingKind = NodeGrounding
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
# Every collection in the v1 wire contract has declared semantics. Set-like
|
| 98 |
+
# collections are unique and canonicalized by value or stable node identifier;
|
| 99 |
+
# ordered collections retain their input order and may contain repeated values.
|
| 100 |
+
INTENT_IR_COLLECTION_SEMANTICS: Mapping[str, CollectionSemantics] = MappingProxyType(
|
| 101 |
+
{
|
| 102 |
+
"IntentIRDocument.sources": CollectionSemantics.SET_LIKE,
|
| 103 |
+
"IntentIRDocument.statements": CollectionSemantics.SET_LIKE,
|
| 104 |
+
"IntentIRDocument.actions": CollectionSemantics.SET_LIKE,
|
| 105 |
+
"IntentIRDocument.control_edges": CollectionSemantics.SET_LIKE,
|
| 106 |
+
"IntentIRDocument.entry_action_ids": CollectionSemantics.SET_LIKE,
|
| 107 |
+
"IntentIRDocument.terminal_action_ids": CollectionSemantics.SET_LIKE,
|
| 108 |
+
"IntentIRDocument.tags": CollectionSemantics.SET_LIKE,
|
| 109 |
+
"IntentStatement.arguments": CollectionSemantics.ORDERED,
|
| 110 |
+
"IntentStatement.source_ref_ids": CollectionSemantics.SET_LIKE,
|
| 111 |
+
"IntentAction.object_refs": CollectionSemantics.SET_LIKE,
|
| 112 |
+
"IntentAction.source_ref_ids": CollectionSemantics.SET_LIKE,
|
| 113 |
+
"IntentAction.tool_refs": CollectionSemantics.SET_LIKE,
|
| 114 |
+
"IntentAction.input_refs": CollectionSemantics.SET_LIKE,
|
| 115 |
+
"IntentAction.output_refs": CollectionSemantics.SET_LIKE,
|
| 116 |
+
"IntentAction.precondition_ids": CollectionSemantics.SET_LIKE,
|
| 117 |
+
"IntentAction.effect_ids": CollectionSemantics.SET_LIKE,
|
| 118 |
+
"IntentAction.verification_ids": CollectionSemantics.SET_LIKE,
|
| 119 |
+
"IntentControlEdge.source_ref_ids": CollectionSemantics.SET_LIKE,
|
| 120 |
+
}
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
# Machine-consumable JSON-pointer rules for the shared canonical identity
|
| 124 |
+
# profile. Wildcards cover each node in the set-like top-level collections.
|
| 125 |
+
INTENT_IR_COLLECTION_SCHEMA = CollectionSchema(
|
| 126 |
+
{
|
| 127 |
+
"/sources": CollectionSemantics.SET_LIKE,
|
| 128 |
+
"/statements": CollectionSemantics.SET_LIKE,
|
| 129 |
+
"/statements/*/arguments": CollectionSemantics.ORDERED,
|
| 130 |
+
"/statements/*/source_ref_ids": CollectionSemantics.SET_LIKE,
|
| 131 |
+
"/actions": CollectionSemantics.SET_LIKE,
|
| 132 |
+
"/actions/*/object_refs": CollectionSemantics.SET_LIKE,
|
| 133 |
+
"/actions/*/source_ref_ids": CollectionSemantics.SET_LIKE,
|
| 134 |
+
"/actions/*/tool_refs": CollectionSemantics.SET_LIKE,
|
| 135 |
+
"/actions/*/input_refs": CollectionSemantics.SET_LIKE,
|
| 136 |
+
"/actions/*/output_refs": CollectionSemantics.SET_LIKE,
|
| 137 |
+
"/actions/*/precondition_ids": CollectionSemantics.SET_LIKE,
|
| 138 |
+
"/actions/*/effect_ids": CollectionSemantics.SET_LIKE,
|
| 139 |
+
"/actions/*/verification_ids": CollectionSemantics.SET_LIKE,
|
| 140 |
+
"/control_edges": CollectionSemantics.SET_LIKE,
|
| 141 |
+
"/control_edges/*/source_ref_ids": CollectionSemantics.SET_LIKE,
|
| 142 |
+
"/entry_action_ids": CollectionSemantics.SET_LIKE,
|
| 143 |
+
"/terminal_action_ids": CollectionSemantics.SET_LIKE,
|
| 144 |
+
"/tags": CollectionSemantics.SET_LIKE,
|
| 145 |
+
},
|
| 146 |
+
require_declared=True,
|
| 147 |
+
)
|
| 148 |
+
|
| 149 |
+
|
| 150 |
+
@dataclass(frozen=True, slots=True)
|
| 151 |
+
class SourceSpan:
|
| 152 |
+
"""Character span in a separately stored source artifact."""
|
| 153 |
+
|
| 154 |
+
start_char: int
|
| 155 |
+
end_char: int
|
| 156 |
+
|
| 157 |
+
def validate(self) -> None:
|
| 158 |
+
if isinstance(self.start_char, bool) or not isinstance(self.start_char, int):
|
| 159 |
+
raise IntentIRValidationError("SourceSpan.start_char must be an integer")
|
| 160 |
+
if isinstance(self.end_char, bool) or not isinstance(self.end_char, int):
|
| 161 |
+
raise IntentIRValidationError("SourceSpan.end_char must be an integer")
|
| 162 |
+
if self.start_char < 0 or self.end_char < self.start_char:
|
| 163 |
+
raise IntentIRValidationError("SourceSpan must satisfy 0 <= start_char <= end_char")
|
| 164 |
+
|
| 165 |
+
def to_dict(self) -> dict[str, int]:
|
| 166 |
+
return {"end_char": self.end_char, "start_char": self.start_char}
|
| 167 |
+
|
| 168 |
+
|
| 169 |
+
@dataclass(frozen=True, slots=True)
|
| 170 |
+
class SourceRef:
|
| 171 |
+
"""Immutable reference to evidence used by one Intent IR document.
|
| 172 |
+
|
| 173 |
+
``source_uri`` identifies the original source when available, while
|
| 174 |
+
``container_uri`` identifies the pinned corpus artifact that supplied the
|
| 175 |
+
bytes. ``content_sha256`` always binds the exact normalized source body.
|
| 176 |
+
"""
|
| 177 |
+
|
| 178 |
+
ref_id: str
|
| 179 |
+
source_uri: str
|
| 180 |
+
source_id: str
|
| 181 |
+
source_revision: str
|
| 182 |
+
content_sha256: str
|
| 183 |
+
container_uri: str = ""
|
| 184 |
+
container_sha256: str = ""
|
| 185 |
+
content_cid: str = ""
|
| 186 |
+
license_expression: str = ""
|
| 187 |
+
review_status: ReviewStatus = ReviewStatus.UNREVIEWED
|
| 188 |
+
span: SourceSpan | None = None
|
| 189 |
+
|
| 190 |
+
def validate(self) -> None:
|
| 191 |
+
_validate_identifier("SourceRef.ref_id", self.ref_id)
|
| 192 |
+
_validate_enum("SourceRef.review_status", self.review_status, ReviewStatus)
|
| 193 |
+
for name in ("source_uri", "source_id", "source_revision"):
|
| 194 |
+
_validate_non_empty_string(f"SourceRef.{name}", getattr(self, name))
|
| 195 |
+
for name in (
|
| 196 |
+
"container_uri",
|
| 197 |
+
"content_cid",
|
| 198 |
+
"license_expression",
|
| 199 |
+
):
|
| 200 |
+
_validate_string(f"SourceRef.{name}", getattr(self, name))
|
| 201 |
+
_validate_sha256("SourceRef.content_sha256", self.content_sha256)
|
| 202 |
+
_validate_string("SourceRef.container_sha256", self.container_sha256)
|
| 203 |
+
if self.container_sha256:
|
| 204 |
+
_validate_sha256("SourceRef.container_sha256", self.container_sha256)
|
| 205 |
+
if self.span is not None and not isinstance(self.span, SourceSpan):
|
| 206 |
+
raise IntentIRValidationError("SourceRef.span must be a SourceSpan or None")
|
| 207 |
+
if self.span is not None:
|
| 208 |
+
self.span.validate()
|
| 209 |
+
|
| 210 |
+
def to_dict(self) -> dict[str, Any]:
|
| 211 |
+
return {
|
| 212 |
+
"container_sha256": self.container_sha256,
|
| 213 |
+
"container_uri": self.container_uri,
|
| 214 |
+
"content_cid": self.content_cid,
|
| 215 |
+
"content_sha256": self.content_sha256,
|
| 216 |
+
"license_expression": self.license_expression,
|
| 217 |
+
"ref_id": self.ref_id,
|
| 218 |
+
"review_status": self.review_status.value,
|
| 219 |
+
"source_id": self.source_id,
|
| 220 |
+
"source_revision": self.source_revision,
|
| 221 |
+
"source_uri": self.source_uri,
|
| 222 |
+
"span": self.span.to_dict() if self.span else None,
|
| 223 |
+
}
|
| 224 |
+
|
| 225 |
+
|
| 226 |
+
@dataclass(frozen=True, slots=True)
|
| 227 |
+
class IntentStatement:
|
| 228 |
+
"""One normalized, source-grounded semantic statement."""
|
| 229 |
+
|
| 230 |
+
statement_id: str
|
| 231 |
+
kind: StatementKind
|
| 232 |
+
modality: IntentModality
|
| 233 |
+
normalized_text: str
|
| 234 |
+
source_ref_ids: tuple[str, ...]
|
| 235 |
+
predicate: str = ""
|
| 236 |
+
arguments: tuple[str, ...] = ()
|
| 237 |
+
confidence: float = 1.0
|
| 238 |
+
review_status: ReviewStatus = ReviewStatus.MACHINE_EXTRACTED
|
| 239 |
+
grounding: NodeGrounding = NodeGrounding.GROUNDED
|
| 240 |
+
|
| 241 |
+
def validate(self) -> None:
|
| 242 |
+
_validate_identifier("IntentStatement.statement_id", self.statement_id)
|
| 243 |
+
_validate_enum("IntentStatement.kind", self.kind, StatementKind)
|
| 244 |
+
_validate_enum("IntentStatement.modality", self.modality, IntentModality)
|
| 245 |
+
_validate_enum("IntentStatement.review_status", self.review_status, ReviewStatus)
|
| 246 |
+
_validate_enum("IntentStatement.grounding", self.grounding, NodeGrounding)
|
| 247 |
+
_validate_non_empty_string(
|
| 248 |
+
f"IntentStatement {self.statement_id!r}.normalized_text",
|
| 249 |
+
self.normalized_text,
|
| 250 |
+
)
|
| 251 |
+
if self.grounding is NodeGrounding.GROUNDED and not self.source_ref_ids:
|
| 252 |
+
raise IntentIRValidationError(
|
| 253 |
+
f"Grounded IntentStatement {self.statement_id!r} requires source_ref_ids"
|
| 254 |
+
)
|
| 255 |
+
_validate_confidence(f"IntentStatement {self.statement_id!r}.confidence", self.confidence)
|
| 256 |
+
_validate_string(f"IntentStatement {self.statement_id!r}.predicate", self.predicate)
|
| 257 |
+
if self.predicate and not _IDENTIFIER_RE.fullmatch(self.predicate):
|
| 258 |
+
raise IntentIRValidationError(
|
| 259 |
+
f"IntentStatement {self.statement_id!r}.predicate is not a stable identifier"
|
| 260 |
+
)
|
| 261 |
+
|
| 262 |
+
def to_dict(self) -> dict[str, Any]:
|
| 263 |
+
return {
|
| 264 |
+
"arguments": list(self.arguments),
|
| 265 |
+
"confidence": self.confidence,
|
| 266 |
+
"grounding": self.grounding.value,
|
| 267 |
+
"kind": self.kind.value,
|
| 268 |
+
"modality": self.modality.value,
|
| 269 |
+
"normalized_text": self.normalized_text,
|
| 270 |
+
"predicate": self.predicate,
|
| 271 |
+
"review_status": self.review_status.value,
|
| 272 |
+
"source_ref_ids": sorted(set(self.source_ref_ids)),
|
| 273 |
+
"statement_id": self.statement_id,
|
| 274 |
+
}
|
| 275 |
+
|
| 276 |
+
|
| 277 |
+
@dataclass(frozen=True, slots=True)
|
| 278 |
+
class IntentAction:
|
| 279 |
+
"""One action node in an intent procedure."""
|
| 280 |
+
|
| 281 |
+
action_id: str
|
| 282 |
+
actor: str
|
| 283 |
+
verb: str
|
| 284 |
+
object_refs: tuple[str, ...]
|
| 285 |
+
source_ref_ids: tuple[str, ...]
|
| 286 |
+
tool_refs: tuple[str, ...] = ()
|
| 287 |
+
input_refs: tuple[str, ...] = ()
|
| 288 |
+
output_refs: tuple[str, ...] = ()
|
| 289 |
+
precondition_ids: tuple[str, ...] = ()
|
| 290 |
+
effect_ids: tuple[str, ...] = ()
|
| 291 |
+
verification_ids: tuple[str, ...] = ()
|
| 292 |
+
grounding: NodeGrounding = NodeGrounding.GROUNDED
|
| 293 |
+
|
| 294 |
+
def validate(self) -> None:
|
| 295 |
+
_validate_identifier("IntentAction.action_id", self.action_id)
|
| 296 |
+
_validate_enum("IntentAction.grounding", self.grounding, NodeGrounding)
|
| 297 |
+
_validate_non_empty_string(f"IntentAction {self.action_id!r}.actor", self.actor)
|
| 298 |
+
_validate_non_empty_string(f"IntentAction {self.action_id!r}.verb", self.verb)
|
| 299 |
+
if self.grounding is NodeGrounding.GROUNDED and not self.source_ref_ids:
|
| 300 |
+
raise IntentIRValidationError(
|
| 301 |
+
f"Grounded IntentAction {self.action_id!r} requires source_ref_ids"
|
| 302 |
+
)
|
| 303 |
+
|
| 304 |
+
def to_dict(self) -> dict[str, Any]:
|
| 305 |
+
return {
|
| 306 |
+
"action_id": self.action_id,
|
| 307 |
+
"actor": self.actor,
|
| 308 |
+
"effect_ids": sorted(set(self.effect_ids)),
|
| 309 |
+
"grounding": self.grounding.value,
|
| 310 |
+
"input_refs": sorted(set(self.input_refs)),
|
| 311 |
+
"object_refs": sorted(set(self.object_refs)),
|
| 312 |
+
"output_refs": sorted(set(self.output_refs)),
|
| 313 |
+
"precondition_ids": sorted(set(self.precondition_ids)),
|
| 314 |
+
"source_ref_ids": sorted(set(self.source_ref_ids)),
|
| 315 |
+
"tool_refs": sorted(set(self.tool_refs)),
|
| 316 |
+
"verb": self.verb,
|
| 317 |
+
"verification_ids": sorted(set(self.verification_ids)),
|
| 318 |
+
}
|
| 319 |
+
|
| 320 |
+
|
| 321 |
+
@dataclass(frozen=True, slots=True)
|
| 322 |
+
class IntentControlEdge:
|
| 323 |
+
"""Directed control-flow edge between action nodes."""
|
| 324 |
+
|
| 325 |
+
edge_id: str
|
| 326 |
+
source_action_id: str
|
| 327 |
+
target_action_id: str
|
| 328 |
+
kind: ControlEdgeKind = ControlEdgeKind.NEXT
|
| 329 |
+
guard_statement_id: str = ""
|
| 330 |
+
source_ref_ids: tuple[str, ...] = ()
|
| 331 |
+
grounding: NodeGrounding = NodeGrounding.GROUNDED
|
| 332 |
+
|
| 333 |
+
def validate(self) -> None:
|
| 334 |
+
_validate_identifier("IntentControlEdge.edge_id", self.edge_id)
|
| 335 |
+
_validate_enum("IntentControlEdge.kind", self.kind, ControlEdgeKind)
|
| 336 |
+
_validate_enum("IntentControlEdge.grounding", self.grounding, NodeGrounding)
|
| 337 |
+
_validate_identifier("IntentControlEdge.source_action_id", self.source_action_id)
|
| 338 |
+
_validate_identifier("IntentControlEdge.target_action_id", self.target_action_id)
|
| 339 |
+
_validate_string("IntentControlEdge.guard_statement_id", self.guard_statement_id)
|
| 340 |
+
if self.guard_statement_id:
|
| 341 |
+
_validate_identifier(
|
| 342 |
+
"IntentControlEdge.guard_statement_id",
|
| 343 |
+
self.guard_statement_id,
|
| 344 |
+
)
|
| 345 |
+
if (
|
| 346 |
+
self.source_action_id == self.target_action_id
|
| 347 |
+
and self.kind is not ControlEdgeKind.RETRY
|
| 348 |
+
):
|
| 349 |
+
raise IntentIRValidationError(
|
| 350 |
+
f"IntentControlEdge {self.edge_id!r} self-cycle must be a retry"
|
| 351 |
+
)
|
| 352 |
+
if self.grounding is NodeGrounding.GROUNDED and not self.source_ref_ids:
|
| 353 |
+
raise IntentIRValidationError(
|
| 354 |
+
f"Grounded IntentControlEdge {self.edge_id!r} requires source_ref_ids"
|
| 355 |
+
)
|
| 356 |
+
|
| 357 |
+
def to_dict(self) -> dict[str, Any]:
|
| 358 |
+
return {
|
| 359 |
+
"edge_id": self.edge_id,
|
| 360 |
+
"guard_statement_id": self.guard_statement_id,
|
| 361 |
+
"grounding": self.grounding.value,
|
| 362 |
+
"kind": self.kind.value,
|
| 363 |
+
"source_action_id": self.source_action_id,
|
| 364 |
+
"source_ref_ids": sorted(set(self.source_ref_ids)),
|
| 365 |
+
"target_action_id": self.target_action_id,
|
| 366 |
+
}
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
@dataclass(frozen=True, slots=True)
|
| 370 |
+
class IntentIRDocument:
|
| 371 |
+
"""Canonical semantic IR for one skill or source-grounded intent."""
|
| 372 |
+
|
| 373 |
+
document_id: str
|
| 374 |
+
title: str
|
| 375 |
+
intent_kind: IntentKind
|
| 376 |
+
sources: tuple[SourceRef, ...]
|
| 377 |
+
statements: tuple[IntentStatement, ...]
|
| 378 |
+
actions: tuple[IntentAction, ...] = ()
|
| 379 |
+
control_edges: tuple[IntentControlEdge, ...] = ()
|
| 380 |
+
entry_action_ids: tuple[str, ...] = ()
|
| 381 |
+
terminal_action_ids: tuple[str, ...] = ()
|
| 382 |
+
tags: tuple[str, ...] = ()
|
| 383 |
+
schema_version: str = INTENT_IR_SCHEMA_VERSION
|
| 384 |
+
|
| 385 |
+
def validate(self) -> None:
|
| 386 |
+
validate_intent_ir(self)
|
| 387 |
+
|
| 388 |
+
def to_dict(self) -> dict[str, Any]:
|
| 389 |
+
return {
|
| 390 |
+
"actions": [
|
| 391 |
+
item.to_dict() for item in sorted(self.actions, key=lambda item: item.action_id)
|
| 392 |
+
],
|
| 393 |
+
"control_edges": [
|
| 394 |
+
item.to_dict() for item in sorted(self.control_edges, key=lambda item: item.edge_id)
|
| 395 |
+
],
|
| 396 |
+
"document_id": self.document_id,
|
| 397 |
+
"entry_action_ids": sorted(set(self.entry_action_ids)),
|
| 398 |
+
"intent_kind": self.intent_kind.value,
|
| 399 |
+
"schema_version": self.schema_version,
|
| 400 |
+
"sources": [
|
| 401 |
+
item.to_dict() for item in sorted(self.sources, key=lambda item: item.ref_id)
|
| 402 |
+
],
|
| 403 |
+
"statements": [
|
| 404 |
+
item.to_dict()
|
| 405 |
+
for item in sorted(self.statements, key=lambda item: item.statement_id)
|
| 406 |
+
],
|
| 407 |
+
"tags": sorted(set(self.tags)),
|
| 408 |
+
"terminal_action_ids": sorted(set(self.terminal_action_ids)),
|
| 409 |
+
"title": self.title,
|
| 410 |
+
}
|
| 411 |
+
|
| 412 |
+
|
| 413 |
+
def validate_intent_ir(
|
| 414 |
+
document: IntentIRDocument | Mapping[str, Any],
|
| 415 |
+
) -> IntentIRDocument:
|
| 416 |
+
"""Validate and return an :class:`IntentIRDocument`.
|
| 417 |
+
|
| 418 |
+
Mappings must pass through :mod:`intent_ir.decoder`; accepting them here
|
| 419 |
+
would let untrusted JSON bypass exact field and type validation.
|
| 420 |
+
"""
|
| 421 |
+
|
| 422 |
+
if not isinstance(document, IntentIRDocument):
|
| 423 |
+
raise IntentIRValidationError("Intent IR mappings require an explicit versioned decoder")
|
| 424 |
+
if document.schema_version != INTENT_IR_SCHEMA_VERSION:
|
| 425 |
+
raise IntentIRValidationError(
|
| 426 |
+
f"Unsupported Intent IR schema_version: {document.schema_version!r}"
|
| 427 |
+
)
|
| 428 |
+
_validate_identifier("IntentIRDocument.document_id", document.document_id)
|
| 429 |
+
_validate_enum("IntentIRDocument.intent_kind", document.intent_kind, IntentKind)
|
| 430 |
+
_validate_non_empty_string("IntentIRDocument.title", document.title)
|
| 431 |
+
if not document.sources:
|
| 432 |
+
raise IntentIRValidationError("IntentIRDocument.sources must not be empty")
|
| 433 |
+
if not document.statements:
|
| 434 |
+
raise IntentIRValidationError("IntentIRDocument.statements must not be empty")
|
| 435 |
+
|
| 436 |
+
_validate_record_collection("IntentIRDocument.sources", document.sources, SourceRef)
|
| 437 |
+
_validate_record_collection("IntentIRDocument.statements", document.statements, IntentStatement)
|
| 438 |
+
_validate_record_collection("IntentIRDocument.actions", document.actions, IntentAction)
|
| 439 |
+
_validate_record_collection(
|
| 440 |
+
"IntentIRDocument.control_edges",
|
| 441 |
+
document.control_edges,
|
| 442 |
+
IntentControlEdge,
|
| 443 |
+
)
|
| 444 |
+
_require_unique((item.ref_id for item in document.sources), "source ref")
|
| 445 |
+
_require_unique((item.statement_id for item in document.statements), "statement")
|
| 446 |
+
_require_unique((item.action_id for item in document.actions), "action")
|
| 447 |
+
_require_unique((item.edge_id for item in document.control_edges), "control edge")
|
| 448 |
+
_validate_document_collections(document)
|
| 449 |
+
|
| 450 |
+
for source in document.sources:
|
| 451 |
+
source.validate()
|
| 452 |
+
for statement in document.statements:
|
| 453 |
+
statement.validate()
|
| 454 |
+
for action in document.actions:
|
| 455 |
+
action.validate()
|
| 456 |
+
for edge in document.control_edges:
|
| 457 |
+
edge.validate()
|
| 458 |
+
|
| 459 |
+
source_ids = {item.ref_id for item in document.sources}
|
| 460 |
+
statements = {item.statement_id: item for item in document.statements}
|
| 461 |
+
action_ids = {item.action_id for item in document.actions}
|
| 462 |
+
|
| 463 |
+
for statement in document.statements:
|
| 464 |
+
_require_known_refs(
|
| 465 |
+
statement.source_ref_ids,
|
| 466 |
+
source_ids,
|
| 467 |
+
f"IntentStatement {statement.statement_id!r}.source_ref_ids",
|
| 468 |
+
)
|
| 469 |
+
for action in document.actions:
|
| 470 |
+
_require_known_refs(
|
| 471 |
+
action.source_ref_ids,
|
| 472 |
+
source_ids,
|
| 473 |
+
f"IntentAction {action.action_id!r}.source_ref_ids",
|
| 474 |
+
)
|
| 475 |
+
_require_statement_kinds(
|
| 476 |
+
action.precondition_ids,
|
| 477 |
+
statements,
|
| 478 |
+
{StatementKind.PRECONDITION, StatementKind.GUARD, StatementKind.ASSUMPTION},
|
| 479 |
+
f"IntentAction {action.action_id!r}.precondition_ids",
|
| 480 |
+
)
|
| 481 |
+
_require_statement_kinds(
|
| 482 |
+
action.effect_ids,
|
| 483 |
+
statements,
|
| 484 |
+
{StatementKind.EFFECT, StatementKind.POSTCONDITION},
|
| 485 |
+
f"IntentAction {action.action_id!r}.effect_ids",
|
| 486 |
+
)
|
| 487 |
+
_require_statement_kinds(
|
| 488 |
+
action.verification_ids,
|
| 489 |
+
statements,
|
| 490 |
+
{StatementKind.VERIFICATION, StatementKind.INVARIANT},
|
| 491 |
+
f"IntentAction {action.action_id!r}.verification_ids",
|
| 492 |
+
)
|
| 493 |
+
for edge in document.control_edges:
|
| 494 |
+
_require_known_refs(
|
| 495 |
+
(edge.source_action_id, edge.target_action_id),
|
| 496 |
+
action_ids,
|
| 497 |
+
f"IntentControlEdge {edge.edge_id!r}",
|
| 498 |
+
)
|
| 499 |
+
_require_known_refs(
|
| 500 |
+
edge.source_ref_ids,
|
| 501 |
+
source_ids,
|
| 502 |
+
f"IntentControlEdge {edge.edge_id!r}.source_ref_ids",
|
| 503 |
+
)
|
| 504 |
+
if edge.guard_statement_id:
|
| 505 |
+
_require_statement_kinds(
|
| 506 |
+
(edge.guard_statement_id,),
|
| 507 |
+
statements,
|
| 508 |
+
{StatementKind.GUARD, StatementKind.PRECONDITION},
|
| 509 |
+
f"IntentControlEdge {edge.edge_id!r}.guard_statement_id",
|
| 510 |
+
)
|
| 511 |
+
|
| 512 |
+
_require_known_refs(
|
| 513 |
+
document.entry_action_ids,
|
| 514 |
+
action_ids,
|
| 515 |
+
"IntentIRDocument.entry_action_ids",
|
| 516 |
+
)
|
| 517 |
+
_require_known_refs(
|
| 518 |
+
document.terminal_action_ids,
|
| 519 |
+
action_ids,
|
| 520 |
+
"IntentIRDocument.terminal_action_ids",
|
| 521 |
+
)
|
| 522 |
+
if document.intent_kind is IntentKind.PROCEDURE:
|
| 523 |
+
if not document.actions:
|
| 524 |
+
raise IntentIRValidationError("Procedure Intent IR requires at least one action")
|
| 525 |
+
if not document.entry_action_ids or not document.terminal_action_ids:
|
| 526 |
+
raise IntentIRValidationError(
|
| 527 |
+
"Procedure Intent IR requires entry_action_ids and terminal_action_ids"
|
| 528 |
+
)
|
| 529 |
+
if not any(statement.kind is StatementKind.GOAL for statement in document.statements):
|
| 530 |
+
raise IntentIRValidationError("IntentIRDocument requires at least one goal statement")
|
| 531 |
+
return document
|
| 532 |
+
|
| 533 |
+
|
| 534 |
+
def _validate_document_collections(document: IntentIRDocument) -> None:
|
| 535 |
+
"""Enforce the immutable and declared collection contract."""
|
| 536 |
+
|
| 537 |
+
_require_tuple("IntentIRDocument.sources", document.sources)
|
| 538 |
+
_require_tuple("IntentIRDocument.statements", document.statements)
|
| 539 |
+
_require_tuple("IntentIRDocument.actions", document.actions)
|
| 540 |
+
_require_tuple("IntentIRDocument.control_edges", document.control_edges)
|
| 541 |
+
|
| 542 |
+
set_collections: tuple[tuple[str, tuple[Any, ...]], ...] = (
|
| 543 |
+
("IntentIRDocument.entry_action_ids", document.entry_action_ids),
|
| 544 |
+
("IntentIRDocument.terminal_action_ids", document.terminal_action_ids),
|
| 545 |
+
("IntentIRDocument.tags", document.tags),
|
| 546 |
+
)
|
| 547 |
+
for statement in document.statements:
|
| 548 |
+
_require_tuple(
|
| 549 |
+
f"IntentStatement {statement.statement_id!r}.arguments",
|
| 550 |
+
statement.arguments,
|
| 551 |
+
)
|
| 552 |
+
_validate_string_items(
|
| 553 |
+
f"IntentStatement {statement.statement_id!r}.arguments",
|
| 554 |
+
statement.arguments,
|
| 555 |
+
)
|
| 556 |
+
set_collections += (
|
| 557 |
+
(
|
| 558 |
+
f"IntentStatement {statement.statement_id!r}.source_ref_ids",
|
| 559 |
+
statement.source_ref_ids,
|
| 560 |
+
),
|
| 561 |
+
)
|
| 562 |
+
for action in document.actions:
|
| 563 |
+
for field_name in (
|
| 564 |
+
"object_refs",
|
| 565 |
+
"source_ref_ids",
|
| 566 |
+
"tool_refs",
|
| 567 |
+
"input_refs",
|
| 568 |
+
"output_refs",
|
| 569 |
+
"precondition_ids",
|
| 570 |
+
"effect_ids",
|
| 571 |
+
"verification_ids",
|
| 572 |
+
):
|
| 573 |
+
set_collections += (
|
| 574 |
+
(
|
| 575 |
+
f"IntentAction {action.action_id!r}.{field_name}",
|
| 576 |
+
getattr(action, field_name),
|
| 577 |
+
),
|
| 578 |
+
)
|
| 579 |
+
for edge in document.control_edges:
|
| 580 |
+
set_collections += (
|
| 581 |
+
(
|
| 582 |
+
f"IntentControlEdge {edge.edge_id!r}.source_ref_ids",
|
| 583 |
+
edge.source_ref_ids,
|
| 584 |
+
),
|
| 585 |
+
)
|
| 586 |
+
|
| 587 |
+
for name, values in set_collections:
|
| 588 |
+
_require_tuple(name, values)
|
| 589 |
+
_validate_string_items(name, values)
|
| 590 |
+
_require_unique(values, f"{name} member")
|
| 591 |
+
|
| 592 |
+
|
| 593 |
+
def _validate_record_collection(name: str, value: Any, item_type: type[Any]) -> None:
|
| 594 |
+
_require_tuple(name, value)
|
| 595 |
+
for index, item in enumerate(value):
|
| 596 |
+
if not isinstance(item, item_type):
|
| 597 |
+
raise IntentIRValidationError(f"{name}[{index}] must be a {item_type.__name__}")
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
def _validate_identifier(name: str, value: str) -> None:
|
| 601 |
+
if not isinstance(value, str) or not _IDENTIFIER_RE.fullmatch(value):
|
| 602 |
+
raise IntentIRValidationError(f"{name} is not a stable identifier")
|
| 603 |
+
|
| 604 |
+
|
| 605 |
+
def _validate_string(name: str, value: Any) -> None:
|
| 606 |
+
if not isinstance(value, str):
|
| 607 |
+
raise IntentIRValidationError(f"{name} must be a string")
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
def _validate_non_empty_string(name: str, value: Any) -> None:
|
| 611 |
+
_validate_string(name, value)
|
| 612 |
+
if not value.strip():
|
| 613 |
+
raise IntentIRValidationError(f"{name} must not be empty")
|
| 614 |
+
|
| 615 |
+
|
| 616 |
+
def _validate_string_items(name: str, values: Iterable[Any]) -> None:
|
| 617 |
+
for index, value in enumerate(values):
|
| 618 |
+
_validate_non_empty_string(f"{name}[{index}]", value)
|
| 619 |
+
|
| 620 |
+
|
| 621 |
+
def _require_tuple(name: str, value: Any) -> None:
|
| 622 |
+
if not isinstance(value, tuple):
|
| 623 |
+
raise IntentIRValidationError(
|
| 624 |
+
f"{name} must be an immutable tuple with "
|
| 625 |
+
f"{INTENT_IR_COLLECTION_SEMANTICS.get(name, 'declared')} semantics"
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
def _validate_sha256(name: str, value: str) -> None:
|
| 630 |
+
if not isinstance(value, str) or not _SHA256_RE.fullmatch(value):
|
| 631 |
+
raise IntentIRValidationError(f"{name} must be a lowercase 64-character SHA-256")
|
| 632 |
+
|
| 633 |
+
|
| 634 |
+
def _validate_enum(name: str, value: Any, enum_type: type[Enum]) -> None:
|
| 635 |
+
if not isinstance(value, enum_type):
|
| 636 |
+
raise IntentIRValidationError(f"{name} must be a {enum_type.__name__} value")
|
| 637 |
+
|
| 638 |
+
|
| 639 |
+
def _validate_confidence(name: str, value: float) -> None:
|
| 640 |
+
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
| 641 |
+
raise IntentIRValidationError(f"{name} must be numeric")
|
| 642 |
+
if not 0.0 <= float(value) <= 1.0:
|
| 643 |
+
raise IntentIRValidationError(f"{name} must be between 0 and 1")
|
| 644 |
+
|
| 645 |
+
|
| 646 |
+
def _require_unique(values: Iterable[str], label: str) -> None:
|
| 647 |
+
seen: set[str] = set()
|
| 648 |
+
for value in values:
|
| 649 |
+
if value in seen:
|
| 650 |
+
raise IntentIRValidationError(f"Duplicate {label} id: {value}")
|
| 651 |
+
seen.add(value)
|
| 652 |
+
|
| 653 |
+
|
| 654 |
+
def _require_known_refs(values: Iterable[str], known: set[str], label: str) -> None:
|
| 655 |
+
missing = sorted({value for value in values if value not in known})
|
| 656 |
+
if missing:
|
| 657 |
+
raise IntentIRValidationError(f"{label} references unknown ids: {', '.join(missing)}")
|
| 658 |
+
|
| 659 |
+
|
| 660 |
+
def _require_statement_kinds(
|
| 661 |
+
values: Iterable[str],
|
| 662 |
+
statements: Mapping[str, IntentStatement],
|
| 663 |
+
allowed: set[StatementKind],
|
| 664 |
+
label: str,
|
| 665 |
+
) -> None:
|
| 666 |
+
_require_known_refs(values, set(statements), label)
|
| 667 |
+
invalid = sorted(
|
| 668 |
+
statement_id for statement_id in values if statements[statement_id].kind not in allowed
|
| 669 |
+
)
|
| 670 |
+
if invalid:
|
| 671 |
+
allowed_values = ", ".join(sorted(item.value for item in allowed))
|
| 672 |
+
raise IntentIRValidationError(
|
| 673 |
+
f"{label} has incompatible statement kinds for {', '.join(invalid)}; "
|
| 674 |
+
f"allowed: {allowed_values}"
|
| 675 |
+
)
|
| 676 |
+
|
| 677 |
+
|
| 678 |
+
__all__ = [
|
| 679 |
+
"CollectionSemantics",
|
| 680 |
+
"INTENT_IR_COLLECTION_SCHEMA",
|
| 681 |
+
"INTENT_IR_SCHEMA_VERSION",
|
| 682 |
+
"INTENT_IR_COLLECTION_SEMANTICS",
|
| 683 |
+
"LEGACY_INTENT_IR_SCHEMA_VERSION",
|
| 684 |
+
"ControlEdgeKind",
|
| 685 |
+
"GroundingKind",
|
| 686 |
+
"IntentAction",
|
| 687 |
+
"IntentControlEdge",
|
| 688 |
+
"IntentIRDocument",
|
| 689 |
+
"IntentIRValidationError",
|
| 690 |
+
"IntentKind",
|
| 691 |
+
"IntentModality",
|
| 692 |
+
"IntentStatement",
|
| 693 |
+
"NodeGrounding",
|
| 694 |
+
"ReviewStatus",
|
| 695 |
+
"SourceRef",
|
| 696 |
+
"SourceSpan",
|
| 697 |
+
"StatementKind",
|
| 698 |
+
"validate_intent_ir",
|
| 699 |
+
]
|
releases/20261004-retained-checkpoints-v1/source/abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39/ipfs_datasets_py/logic/security_ir/model.py
ADDED
|
@@ -0,0 +1,1017 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Immutable, declaration-only Security IR v1.
|
| 2 |
+
|
| 3 |
+
The records in this module describe a security model. Verification attempts,
|
| 4 |
+
solver verdicts, runtime traces, counterexamples, and release decisions are
|
| 5 |
+
deliberately not fields of :class:`SecurityIR`; those are observations about a
|
| 6 |
+
declaration and must bind its identity from a separate result record.
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
import re
|
| 12 |
+
from collections.abc import Mapping, Sequence
|
| 13 |
+
from dataclasses import dataclass, field
|
| 14 |
+
from enum import Enum
|
| 15 |
+
from types import MappingProxyType
|
| 16 |
+
from typing import Any, ClassVar, Final
|
| 17 |
+
|
| 18 |
+
from ..ir_core.canonical import (
|
| 19 |
+
CollectionSchema,
|
| 20 |
+
CollectionSemantics,
|
| 21 |
+
canonical_json_bytes,
|
| 22 |
+
)
|
| 23 |
+
from ..ir_core.identity import CanonicalIdentity, canonical_identity
|
| 24 |
+
from ..ir_core.provenance import (
|
| 25 |
+
ProvenanceValidationError,
|
| 26 |
+
freeze_json,
|
| 27 |
+
freeze_json_mapping,
|
| 28 |
+
thaw_json,
|
| 29 |
+
)
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
SECURITY_IR_SCHEMA_VERSION: Final = "security-ir/v1"
|
| 33 |
+
SECURITY_IR_V1_SCHEMA_VERSION: Final = SECURITY_IR_SCHEMA_VERSION
|
| 34 |
+
SECURITY_IR_IDENTITY_DOMAIN: Final = "security-ir"
|
| 35 |
+
_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$")
|
| 36 |
+
_SHA256_RE = re.compile(r"^[0-9a-f]{64}$")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
class SecurityIRValidationError(ValueError):
|
| 40 |
+
"""Raised when a Security IR declaration is malformed."""
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class PolicyEffect(str, Enum):
|
| 44 |
+
"""The declarative effect of a security policy."""
|
| 45 |
+
|
| 46 |
+
ALLOW = "allow"
|
| 47 |
+
DENY = "deny"
|
| 48 |
+
REQUIRE = "require"
|
| 49 |
+
AUDIT = "audit"
|
| 50 |
+
UNSPECIFIED = "unspecified"
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _text(value: Any, name: str, *, allow_empty: bool = False) -> str:
|
| 54 |
+
if not isinstance(value, str):
|
| 55 |
+
raise SecurityIRValidationError(f"{name} must be a string")
|
| 56 |
+
if not allow_empty and not value.strip():
|
| 57 |
+
raise SecurityIRValidationError(f"{name} must be a non-empty string")
|
| 58 |
+
if value != value.strip():
|
| 59 |
+
raise SecurityIRValidationError(f"{name} must not have surrounding whitespace")
|
| 60 |
+
return value
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _identifier(value: Any, name: str) -> str:
|
| 64 |
+
normalized = _text(value, name)
|
| 65 |
+
if not _ID_RE.fullmatch(normalized):
|
| 66 |
+
raise SecurityIRValidationError(f"{name} is not a stable identifier")
|
| 67 |
+
return normalized
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _ids(values: Sequence[str] | None, name: str) -> tuple[str, ...]:
|
| 71 |
+
if values is None:
|
| 72 |
+
return ()
|
| 73 |
+
if isinstance(values, (str, bytes, bytearray)) or not isinstance(values, Sequence):
|
| 74 |
+
raise SecurityIRValidationError(f"{name} must be a sequence")
|
| 75 |
+
result = tuple(_identifier(value, name) for value in values)
|
| 76 |
+
if len(result) != len(set(result)):
|
| 77 |
+
raise SecurityIRValidationError(f"{name} values must be unique")
|
| 78 |
+
return result
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def _attributes(value: Mapping[str, Any] | None) -> Mapping[str, Any]:
|
| 82 |
+
try:
|
| 83 |
+
return freeze_json_mapping(value)
|
| 84 |
+
except ProvenanceValidationError as exc:
|
| 85 |
+
raise SecurityIRValidationError(str(exc)) from exc
|
| 86 |
+
|
| 87 |
+
|
| 88 |
+
def _payload(value: Any) -> Any:
|
| 89 |
+
try:
|
| 90 |
+
return freeze_json(value)
|
| 91 |
+
except ProvenanceValidationError as exc:
|
| 92 |
+
raise SecurityIRValidationError(str(exc)) from exc
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _as_mapping(value: Any, name: str) -> Mapping[str, Any]:
|
| 96 |
+
if not isinstance(value, Mapping):
|
| 97 |
+
raise SecurityIRValidationError(f"{name} must be a mapping")
|
| 98 |
+
return value
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
def _known_fields(value: Mapping[str, Any], allowed: frozenset[str], name: str) -> None:
|
| 102 |
+
unknown = sorted(set(value) - allowed)
|
| 103 |
+
if unknown:
|
| 104 |
+
raise SecurityIRValidationError(f"unknown {name} field(s): {', '.join(unknown)}")
|
| 105 |
+
|
| 106 |
+
|
| 107 |
+
@dataclass(frozen=True, slots=True)
|
| 108 |
+
class SecuritySource:
|
| 109 |
+
"""A typed reference to source/evidence bytes outside the declaration."""
|
| 110 |
+
|
| 111 |
+
source_id: str
|
| 112 |
+
uri: str
|
| 113 |
+
revision: str = ""
|
| 114 |
+
content_sha256: str = ""
|
| 115 |
+
review_status: str = "unreviewed"
|
| 116 |
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
| 117 |
+
|
| 118 |
+
def __post_init__(self) -> None:
|
| 119 |
+
object.__setattr__(self, "source_id", _identifier(self.source_id, "source_id"))
|
| 120 |
+
object.__setattr__(self, "uri", _text(self.uri, "uri"))
|
| 121 |
+
object.__setattr__(self, "revision", _text(self.revision, "revision", allow_empty=True))
|
| 122 |
+
if self.content_sha256 and not _SHA256_RE.fullmatch(self.content_sha256):
|
| 123 |
+
raise SecurityIRValidationError("content_sha256 must be a lowercase SHA-256 hex digest")
|
| 124 |
+
object.__setattr__(self, "review_status", _text(self.review_status, "review_status"))
|
| 125 |
+
object.__setattr__(self, "attributes", _attributes(self.attributes))
|
| 126 |
+
|
| 127 |
+
def to_dict(self) -> dict[str, Any]:
|
| 128 |
+
return {
|
| 129 |
+
"attributes": thaw_json(self.attributes),
|
| 130 |
+
"content_sha256": self.content_sha256,
|
| 131 |
+
"review_status": self.review_status,
|
| 132 |
+
"revision": self.revision,
|
| 133 |
+
"source_id": self.source_id,
|
| 134 |
+
"uri": self.uri,
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
@classmethod
|
| 138 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "SecuritySource":
|
| 139 |
+
value = _as_mapping(value, "source")
|
| 140 |
+
_known_fields(
|
| 141 |
+
value,
|
| 142 |
+
frozenset(
|
| 143 |
+
{
|
| 144 |
+
"source_id",
|
| 145 |
+
"uri",
|
| 146 |
+
"revision",
|
| 147 |
+
"content_sha256",
|
| 148 |
+
"review_status",
|
| 149 |
+
"attributes",
|
| 150 |
+
}
|
| 151 |
+
),
|
| 152 |
+
"source",
|
| 153 |
+
)
|
| 154 |
+
return cls(
|
| 155 |
+
source_id=value.get("source_id", ""),
|
| 156 |
+
uri=value.get("uri", ""),
|
| 157 |
+
revision=value.get("revision", ""),
|
| 158 |
+
content_sha256=value.get("content_sha256", ""),
|
| 159 |
+
review_status=value.get("review_status", "unreviewed"),
|
| 160 |
+
attributes=value.get("attributes", {}),
|
| 161 |
+
)
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
@dataclass(frozen=True, slots=True)
|
| 165 |
+
class Principal:
|
| 166 |
+
"""An actor that may hold roles or exercise authority."""
|
| 167 |
+
|
| 168 |
+
principal_id: str
|
| 169 |
+
kind: str = "unspecified"
|
| 170 |
+
role_ids: tuple[str, ...] = ()
|
| 171 |
+
trust_zone_ids: tuple[str, ...] = ()
|
| 172 |
+
source_ids: tuple[str, ...] = ()
|
| 173 |
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
| 174 |
+
|
| 175 |
+
def __post_init__(self) -> None:
|
| 176 |
+
object.__setattr__(self, "principal_id", _identifier(self.principal_id, "principal_id"))
|
| 177 |
+
object.__setattr__(self, "kind", _text(self.kind, "principal kind"))
|
| 178 |
+
for name in ("role_ids", "trust_zone_ids", "source_ids"):
|
| 179 |
+
object.__setattr__(self, name, _ids(getattr(self, name), name))
|
| 180 |
+
object.__setattr__(self, "attributes", _attributes(self.attributes))
|
| 181 |
+
|
| 182 |
+
def to_dict(self) -> dict[str, Any]:
|
| 183 |
+
return _record_dict(
|
| 184 |
+
self,
|
| 185 |
+
"principal_id",
|
| 186 |
+
"kind",
|
| 187 |
+
"role_ids",
|
| 188 |
+
"trust_zone_ids",
|
| 189 |
+
"source_ids",
|
| 190 |
+
)
|
| 191 |
+
|
| 192 |
+
@classmethod
|
| 193 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "Principal":
|
| 194 |
+
return _record_from_dict(cls, value, "principal_id")
|
| 195 |
+
|
| 196 |
+
|
| 197 |
+
@dataclass(frozen=True, slots=True)
|
| 198 |
+
class Asset:
|
| 199 |
+
"""A security-relevant unit of value or protected information."""
|
| 200 |
+
|
| 201 |
+
asset_id: str
|
| 202 |
+
kind: str = "unspecified"
|
| 203 |
+
symbol: str = ""
|
| 204 |
+
source_ids: tuple[str, ...] = ()
|
| 205 |
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
| 206 |
+
|
| 207 |
+
def __post_init__(self) -> None:
|
| 208 |
+
object.__setattr__(self, "asset_id", _identifier(self.asset_id, "asset_id"))
|
| 209 |
+
object.__setattr__(self, "kind", _text(self.kind, "asset kind"))
|
| 210 |
+
object.__setattr__(self, "symbol", _text(self.symbol, "asset symbol", allow_empty=True))
|
| 211 |
+
object.__setattr__(self, "source_ids", _ids(self.source_ids, "source_ids"))
|
| 212 |
+
object.__setattr__(self, "attributes", _attributes(self.attributes))
|
| 213 |
+
|
| 214 |
+
def to_dict(self) -> dict[str, Any]:
|
| 215 |
+
return _record_dict(self, "asset_id", "kind", "symbol", "source_ids")
|
| 216 |
+
|
| 217 |
+
@classmethod
|
| 218 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "Asset":
|
| 219 |
+
return _record_from_dict(cls, value, "asset_id")
|
| 220 |
+
|
| 221 |
+
|
| 222 |
+
@dataclass(frozen=True, slots=True)
|
| 223 |
+
class TrustZone:
|
| 224 |
+
"""A boundary inside which a declared trust posture applies."""
|
| 225 |
+
|
| 226 |
+
trust_zone_id: str
|
| 227 |
+
name: str
|
| 228 |
+
source_ids: tuple[str, ...] = ()
|
| 229 |
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
| 230 |
+
|
| 231 |
+
def __post_init__(self) -> None:
|
| 232 |
+
object.__setattr__(
|
| 233 |
+
self,
|
| 234 |
+
"trust_zone_id",
|
| 235 |
+
_identifier(self.trust_zone_id, "trust_zone_id"),
|
| 236 |
+
)
|
| 237 |
+
object.__setattr__(self, "name", _text(self.name, "trust zone name"))
|
| 238 |
+
object.__setattr__(self, "source_ids", _ids(self.source_ids, "source_ids"))
|
| 239 |
+
object.__setattr__(self, "attributes", _attributes(self.attributes))
|
| 240 |
+
|
| 241 |
+
def to_dict(self) -> dict[str, Any]:
|
| 242 |
+
return _record_dict(self, "trust_zone_id", "name", "source_ids")
|
| 243 |
+
|
| 244 |
+
@classmethod
|
| 245 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "TrustZone":
|
| 246 |
+
return _record_from_dict(cls, value, "trust_zone_id")
|
| 247 |
+
|
| 248 |
+
|
| 249 |
+
@dataclass(frozen=True, slots=True)
|
| 250 |
+
class Channel:
|
| 251 |
+
"""A declared communication or data-flow channel."""
|
| 252 |
+
|
| 253 |
+
channel_id: str
|
| 254 |
+
source_node_id: str
|
| 255 |
+
target_node_id: str
|
| 256 |
+
protocol: str = "unspecified"
|
| 257 |
+
trust_zone_ids: tuple[str, ...] = ()
|
| 258 |
+
source_ids: tuple[str, ...] = ()
|
| 259 |
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
| 260 |
+
|
| 261 |
+
def __post_init__(self) -> None:
|
| 262 |
+
for name in ("channel_id", "source_node_id", "target_node_id"):
|
| 263 |
+
object.__setattr__(self, name, _identifier(getattr(self, name), name))
|
| 264 |
+
object.__setattr__(self, "protocol", _text(self.protocol, "channel protocol"))
|
| 265 |
+
object.__setattr__(self, "trust_zone_ids", _ids(self.trust_zone_ids, "trust_zone_ids"))
|
| 266 |
+
object.__setattr__(self, "source_ids", _ids(self.source_ids, "source_ids"))
|
| 267 |
+
object.__setattr__(self, "attributes", _attributes(self.attributes))
|
| 268 |
+
|
| 269 |
+
def to_dict(self) -> dict[str, Any]:
|
| 270 |
+
return _record_dict(
|
| 271 |
+
self,
|
| 272 |
+
"channel_id",
|
| 273 |
+
"source_node_id",
|
| 274 |
+
"target_node_id",
|
| 275 |
+
"protocol",
|
| 276 |
+
"trust_zone_ids",
|
| 277 |
+
"source_ids",
|
| 278 |
+
)
|
| 279 |
+
|
| 280 |
+
@classmethod
|
| 281 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "Channel":
|
| 282 |
+
return _record_from_dict(
|
| 283 |
+
cls, value, "channel_id", required=("source_node_id", "target_node_id")
|
| 284 |
+
)
|
| 285 |
+
|
| 286 |
+
|
| 287 |
+
@dataclass(frozen=True, slots=True)
|
| 288 |
+
class Resource:
|
| 289 |
+
"""A protected system resource, account, wallet, service, or entity."""
|
| 290 |
+
|
| 291 |
+
resource_id: str
|
| 292 |
+
kind: str = "unspecified"
|
| 293 |
+
owner_principal_ids: tuple[str, ...] = ()
|
| 294 |
+
asset_ids: tuple[str, ...] = ()
|
| 295 |
+
trust_zone_ids: tuple[str, ...] = ()
|
| 296 |
+
source_ids: tuple[str, ...] = ()
|
| 297 |
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
| 298 |
+
|
| 299 |
+
def __post_init__(self) -> None:
|
| 300 |
+
object.__setattr__(self, "resource_id", _identifier(self.resource_id, "resource_id"))
|
| 301 |
+
object.__setattr__(self, "kind", _text(self.kind, "resource kind"))
|
| 302 |
+
for name in (
|
| 303 |
+
"owner_principal_ids",
|
| 304 |
+
"asset_ids",
|
| 305 |
+
"trust_zone_ids",
|
| 306 |
+
"source_ids",
|
| 307 |
+
):
|
| 308 |
+
object.__setattr__(self, name, _ids(getattr(self, name), name))
|
| 309 |
+
object.__setattr__(self, "attributes", _attributes(self.attributes))
|
| 310 |
+
|
| 311 |
+
def to_dict(self) -> dict[str, Any]:
|
| 312 |
+
return _record_dict(
|
| 313 |
+
self,
|
| 314 |
+
"resource_id",
|
| 315 |
+
"kind",
|
| 316 |
+
"owner_principal_ids",
|
| 317 |
+
"asset_ids",
|
| 318 |
+
"trust_zone_ids",
|
| 319 |
+
"source_ids",
|
| 320 |
+
)
|
| 321 |
+
|
| 322 |
+
@classmethod
|
| 323 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "Resource":
|
| 324 |
+
return _record_from_dict(cls, value, "resource_id")
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
@dataclass(frozen=True, slots=True)
|
| 328 |
+
class Policy:
|
| 329 |
+
"""A declarative security decision rule."""
|
| 330 |
+
|
| 331 |
+
policy_id: str
|
| 332 |
+
name: str
|
| 333 |
+
effect: PolicyEffect = PolicyEffect.UNSPECIFIED
|
| 334 |
+
principal_ids: tuple[str, ...] = ()
|
| 335 |
+
resource_ids: tuple[str, ...] = ()
|
| 336 |
+
channel_ids: tuple[str, ...] = ()
|
| 337 |
+
source_ids: tuple[str, ...] = ()
|
| 338 |
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
| 339 |
+
|
| 340 |
+
def __post_init__(self) -> None:
|
| 341 |
+
object.__setattr__(self, "policy_id", _identifier(self.policy_id, "policy_id"))
|
| 342 |
+
object.__setattr__(self, "name", _text(self.name, "policy name"))
|
| 343 |
+
try:
|
| 344 |
+
effect = (
|
| 345 |
+
self.effect if isinstance(self.effect, PolicyEffect) else PolicyEffect(self.effect)
|
| 346 |
+
)
|
| 347 |
+
except (TypeError, ValueError) as exc:
|
| 348 |
+
raise SecurityIRValidationError(f"unsupported policy effect: {self.effect!r}") from exc
|
| 349 |
+
object.__setattr__(self, "effect", effect)
|
| 350 |
+
for name in ("principal_ids", "resource_ids", "channel_ids", "source_ids"):
|
| 351 |
+
object.__setattr__(self, name, _ids(getattr(self, name), name))
|
| 352 |
+
object.__setattr__(self, "attributes", _attributes(self.attributes))
|
| 353 |
+
|
| 354 |
+
def to_dict(self) -> dict[str, Any]:
|
| 355 |
+
result = _record_dict(
|
| 356 |
+
self,
|
| 357 |
+
"policy_id",
|
| 358 |
+
"name",
|
| 359 |
+
"principal_ids",
|
| 360 |
+
"resource_ids",
|
| 361 |
+
"channel_ids",
|
| 362 |
+
"source_ids",
|
| 363 |
+
)
|
| 364 |
+
result["effect"] = self.effect.value
|
| 365 |
+
return result
|
| 366 |
+
|
| 367 |
+
@classmethod
|
| 368 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "Policy":
|
| 369 |
+
return _record_from_dict(cls, value, "policy_id", required=("name",))
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
@dataclass(frozen=True, slots=True)
|
| 373 |
+
class StateTransition:
|
| 374 |
+
"""One declarative transition in a state machine."""
|
| 375 |
+
|
| 376 |
+
source_state: str
|
| 377 |
+
target_state: str
|
| 378 |
+
event: str
|
| 379 |
+
guard: str = ""
|
| 380 |
+
effect: str = ""
|
| 381 |
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
| 382 |
+
|
| 383 |
+
def __post_init__(self) -> None:
|
| 384 |
+
for name in ("source_state", "target_state", "event"):
|
| 385 |
+
object.__setattr__(self, name, _text(getattr(self, name), name))
|
| 386 |
+
for name in ("guard", "effect"):
|
| 387 |
+
object.__setattr__(self, name, _text(getattr(self, name), name, allow_empty=True))
|
| 388 |
+
object.__setattr__(self, "attributes", _attributes(self.attributes))
|
| 389 |
+
|
| 390 |
+
def to_dict(self) -> dict[str, Any]:
|
| 391 |
+
return {
|
| 392 |
+
"attributes": thaw_json(self.attributes),
|
| 393 |
+
"effect": self.effect,
|
| 394 |
+
"event": self.event,
|
| 395 |
+
"guard": self.guard,
|
| 396 |
+
"source_state": self.source_state,
|
| 397 |
+
"target_state": self.target_state,
|
| 398 |
+
}
|
| 399 |
+
|
| 400 |
+
@classmethod
|
| 401 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "StateTransition":
|
| 402 |
+
value = _as_mapping(value, "state transition")
|
| 403 |
+
_known_fields(
|
| 404 |
+
value,
|
| 405 |
+
frozenset(
|
| 406 |
+
{
|
| 407 |
+
"source_state",
|
| 408 |
+
"target_state",
|
| 409 |
+
"event",
|
| 410 |
+
"guard",
|
| 411 |
+
"effect",
|
| 412 |
+
"attributes",
|
| 413 |
+
}
|
| 414 |
+
),
|
| 415 |
+
"state transition",
|
| 416 |
+
)
|
| 417 |
+
return cls(
|
| 418 |
+
source_state=value.get("source_state", ""),
|
| 419 |
+
target_state=value.get("target_state", ""),
|
| 420 |
+
event=value.get("event", ""),
|
| 421 |
+
guard=value.get("guard", ""),
|
| 422 |
+
effect=value.get("effect", ""),
|
| 423 |
+
attributes=value.get("attributes", {}),
|
| 424 |
+
)
|
| 425 |
+
|
| 426 |
+
|
| 427 |
+
@dataclass(frozen=True, slots=True)
|
| 428 |
+
class StateMachine:
|
| 429 |
+
"""A finite-state declaration; no execution history is stored here."""
|
| 430 |
+
|
| 431 |
+
state_machine_id: str
|
| 432 |
+
states: tuple[str, ...]
|
| 433 |
+
initial_state: str = ""
|
| 434 |
+
transitions: tuple[StateTransition, ...] = ()
|
| 435 |
+
source_ids: tuple[str, ...] = ()
|
| 436 |
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
| 437 |
+
|
| 438 |
+
def __post_init__(self) -> None:
|
| 439 |
+
object.__setattr__(
|
| 440 |
+
self,
|
| 441 |
+
"state_machine_id",
|
| 442 |
+
_identifier(self.state_machine_id, "state_machine_id"),
|
| 443 |
+
)
|
| 444 |
+
states = tuple(_text(value, "state") for value in self.states)
|
| 445 |
+
if not states or len(states) != len(set(states)):
|
| 446 |
+
raise SecurityIRValidationError("state machine states must be non-empty and unique")
|
| 447 |
+
object.__setattr__(self, "states", states)
|
| 448 |
+
initial = _text(self.initial_state, "initial_state", allow_empty=True)
|
| 449 |
+
if initial and initial not in states:
|
| 450 |
+
raise SecurityIRValidationError("initial_state must be one of states")
|
| 451 |
+
object.__setattr__(self, "initial_state", initial)
|
| 452 |
+
transitions = tuple(
|
| 453 |
+
item
|
| 454 |
+
if isinstance(item, StateTransition)
|
| 455 |
+
else StateTransition.from_dict(_as_mapping(item, "state transition"))
|
| 456 |
+
for item in self.transitions
|
| 457 |
+
)
|
| 458 |
+
for transition in transitions:
|
| 459 |
+
if transition.source_state not in states or transition.target_state not in states:
|
| 460 |
+
raise SecurityIRValidationError(
|
| 461 |
+
"state transition endpoints must be declared states"
|
| 462 |
+
)
|
| 463 |
+
object.__setattr__(self, "transitions", transitions)
|
| 464 |
+
object.__setattr__(self, "source_ids", _ids(self.source_ids, "source_ids"))
|
| 465 |
+
object.__setattr__(self, "attributes", _attributes(self.attributes))
|
| 466 |
+
|
| 467 |
+
def to_dict(self) -> dict[str, Any]:
|
| 468 |
+
return {
|
| 469 |
+
"attributes": thaw_json(self.attributes),
|
| 470 |
+
"initial_state": self.initial_state,
|
| 471 |
+
"source_ids": list(self.source_ids),
|
| 472 |
+
"state_machine_id": self.state_machine_id,
|
| 473 |
+
"states": list(self.states),
|
| 474 |
+
"transitions": [item.to_dict() for item in self.transitions],
|
| 475 |
+
}
|
| 476 |
+
|
| 477 |
+
@classmethod
|
| 478 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "StateMachine":
|
| 479 |
+
value = _as_mapping(value, "state machine")
|
| 480 |
+
_known_fields(
|
| 481 |
+
value,
|
| 482 |
+
frozenset(
|
| 483 |
+
{
|
| 484 |
+
"state_machine_id",
|
| 485 |
+
"states",
|
| 486 |
+
"initial_state",
|
| 487 |
+
"transitions",
|
| 488 |
+
"source_ids",
|
| 489 |
+
"attributes",
|
| 490 |
+
}
|
| 491 |
+
),
|
| 492 |
+
"state machine",
|
| 493 |
+
)
|
| 494 |
+
return cls(
|
| 495 |
+
state_machine_id=value.get("state_machine_id", ""),
|
| 496 |
+
states=tuple(value.get("states", ())),
|
| 497 |
+
initial_state=value.get("initial_state", ""),
|
| 498 |
+
transitions=tuple(
|
| 499 |
+
StateTransition.from_dict(item) for item in value.get("transitions", ())
|
| 500 |
+
),
|
| 501 |
+
source_ids=tuple(value.get("source_ids", ())),
|
| 502 |
+
attributes=value.get("attributes", {}),
|
| 503 |
+
)
|
| 504 |
+
|
| 505 |
+
|
| 506 |
+
@dataclass(frozen=True, slots=True)
|
| 507 |
+
class ThreatAssumption:
|
| 508 |
+
"""A declared premise; presence does not establish truth."""
|
| 509 |
+
|
| 510 |
+
assumption_id: str
|
| 511 |
+
statement: str
|
| 512 |
+
source_ids: tuple[str, ...] = ()
|
| 513 |
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
| 514 |
+
|
| 515 |
+
def __post_init__(self) -> None:
|
| 516 |
+
object.__setattr__(
|
| 517 |
+
self,
|
| 518 |
+
"assumption_id",
|
| 519 |
+
_identifier(self.assumption_id, "assumption_id"),
|
| 520 |
+
)
|
| 521 |
+
object.__setattr__(self, "statement", _text(self.statement, "statement"))
|
| 522 |
+
object.__setattr__(self, "source_ids", _ids(self.source_ids, "source_ids"))
|
| 523 |
+
object.__setattr__(self, "attributes", _attributes(self.attributes))
|
| 524 |
+
|
| 525 |
+
def to_dict(self) -> dict[str, Any]:
|
| 526 |
+
return _record_dict(self, "assumption_id", "statement", "source_ids")
|
| 527 |
+
|
| 528 |
+
@classmethod
|
| 529 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "ThreatAssumption":
|
| 530 |
+
return _record_from_dict(cls, value, "assumption_id", required=("statement",))
|
| 531 |
+
|
| 532 |
+
|
| 533 |
+
@dataclass(frozen=True, slots=True)
|
| 534 |
+
class SecurityClaim:
|
| 535 |
+
"""A source-grounded security property under explicit assumptions."""
|
| 536 |
+
|
| 537 |
+
claim_id: str
|
| 538 |
+
statement: str
|
| 539 |
+
domain: str
|
| 540 |
+
severity: str = "unspecified"
|
| 541 |
+
assumption_ids: tuple[str, ...] = ()
|
| 542 |
+
policy_ids: tuple[str, ...] = ()
|
| 543 |
+
source_ids: tuple[str, ...] = ()
|
| 544 |
+
attributes: Mapping[str, Any] = field(default_factory=dict)
|
| 545 |
+
|
| 546 |
+
def __post_init__(self) -> None:
|
| 547 |
+
object.__setattr__(self, "claim_id", _identifier(self.claim_id, "claim_id"))
|
| 548 |
+
object.__setattr__(self, "statement", _text(self.statement, "statement"))
|
| 549 |
+
object.__setattr__(self, "domain", _identifier(self.domain, "claim domain"))
|
| 550 |
+
object.__setattr__(self, "severity", _text(self.severity, "severity"))
|
| 551 |
+
for name in ("assumption_ids", "policy_ids", "source_ids"):
|
| 552 |
+
object.__setattr__(self, name, _ids(getattr(self, name), name))
|
| 553 |
+
object.__setattr__(self, "attributes", _attributes(self.attributes))
|
| 554 |
+
|
| 555 |
+
def to_dict(self) -> dict[str, Any]:
|
| 556 |
+
return _record_dict(
|
| 557 |
+
self,
|
| 558 |
+
"claim_id",
|
| 559 |
+
"statement",
|
| 560 |
+
"domain",
|
| 561 |
+
"severity",
|
| 562 |
+
"assumption_ids",
|
| 563 |
+
"policy_ids",
|
| 564 |
+
"source_ids",
|
| 565 |
+
)
|
| 566 |
+
|
| 567 |
+
@classmethod
|
| 568 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "SecurityClaim":
|
| 569 |
+
return _record_from_dict(cls, value, "claim_id", required=("statement", "domain"))
|
| 570 |
+
|
| 571 |
+
|
| 572 |
+
@dataclass(frozen=True, slots=True)
|
| 573 |
+
class SecurityExtension:
|
| 574 |
+
"""A namespaced, versioned declaration not owned by the shared vocabulary."""
|
| 575 |
+
|
| 576 |
+
extension_id: str
|
| 577 |
+
vocabulary: str
|
| 578 |
+
version: str
|
| 579 |
+
payload: Any
|
| 580 |
+
required: bool = False
|
| 581 |
+
source_ids: tuple[str, ...] = ()
|
| 582 |
+
|
| 583 |
+
def __post_init__(self) -> None:
|
| 584 |
+
object.__setattr__(self, "extension_id", _identifier(self.extension_id, "extension_id"))
|
| 585 |
+
object.__setattr__(self, "vocabulary", _identifier(self.vocabulary, "extension vocabulary"))
|
| 586 |
+
object.__setattr__(self, "version", _text(self.version, "extension version"))
|
| 587 |
+
if not isinstance(self.required, bool):
|
| 588 |
+
raise SecurityIRValidationError("extension required must be a boolean")
|
| 589 |
+
object.__setattr__(self, "payload", _payload(self.payload))
|
| 590 |
+
object.__setattr__(self, "source_ids", _ids(self.source_ids, "source_ids"))
|
| 591 |
+
|
| 592 |
+
def to_dict(self) -> dict[str, Any]:
|
| 593 |
+
return {
|
| 594 |
+
"extension_id": self.extension_id,
|
| 595 |
+
"payload": thaw_json(self.payload),
|
| 596 |
+
"required": self.required,
|
| 597 |
+
"source_ids": list(self.source_ids),
|
| 598 |
+
"version": self.version,
|
| 599 |
+
"vocabulary": self.vocabulary,
|
| 600 |
+
}
|
| 601 |
+
|
| 602 |
+
@classmethod
|
| 603 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "SecurityExtension":
|
| 604 |
+
value = _as_mapping(value, "extension")
|
| 605 |
+
_known_fields(
|
| 606 |
+
value,
|
| 607 |
+
frozenset(
|
| 608 |
+
{
|
| 609 |
+
"extension_id",
|
| 610 |
+
"vocabulary",
|
| 611 |
+
"version",
|
| 612 |
+
"payload",
|
| 613 |
+
"required",
|
| 614 |
+
"source_ids",
|
| 615 |
+
}
|
| 616 |
+
),
|
| 617 |
+
"extension",
|
| 618 |
+
)
|
| 619 |
+
return cls(
|
| 620 |
+
extension_id=value.get("extension_id", ""),
|
| 621 |
+
vocabulary=value.get("vocabulary", ""),
|
| 622 |
+
version=value.get("version", ""),
|
| 623 |
+
payload=value.get("payload"),
|
| 624 |
+
required=value.get("required", False),
|
| 625 |
+
source_ids=tuple(value.get("source_ids", ())),
|
| 626 |
+
)
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
_RECORD_DEFAULTS: Mapping[type[Any], Mapping[str, Any]] = MappingProxyType(
|
| 630 |
+
{
|
| 631 |
+
Principal: {
|
| 632 |
+
"kind": "unspecified",
|
| 633 |
+
"role_ids": (),
|
| 634 |
+
"trust_zone_ids": (),
|
| 635 |
+
"source_ids": (),
|
| 636 |
+
},
|
| 637 |
+
Asset: {"kind": "unspecified", "symbol": "", "source_ids": ()},
|
| 638 |
+
TrustZone: {"source_ids": ()},
|
| 639 |
+
Channel: {
|
| 640 |
+
"protocol": "unspecified",
|
| 641 |
+
"trust_zone_ids": (),
|
| 642 |
+
"source_ids": (),
|
| 643 |
+
},
|
| 644 |
+
Resource: {
|
| 645 |
+
"kind": "unspecified",
|
| 646 |
+
"owner_principal_ids": (),
|
| 647 |
+
"asset_ids": (),
|
| 648 |
+
"trust_zone_ids": (),
|
| 649 |
+
"source_ids": (),
|
| 650 |
+
},
|
| 651 |
+
Policy: {
|
| 652 |
+
"effect": PolicyEffect.UNSPECIFIED,
|
| 653 |
+
"principal_ids": (),
|
| 654 |
+
"resource_ids": (),
|
| 655 |
+
"channel_ids": (),
|
| 656 |
+
"source_ids": (),
|
| 657 |
+
},
|
| 658 |
+
ThreatAssumption: {"source_ids": ()},
|
| 659 |
+
SecurityClaim: {
|
| 660 |
+
"severity": "unspecified",
|
| 661 |
+
"assumption_ids": (),
|
| 662 |
+
"policy_ids": (),
|
| 663 |
+
"source_ids": (),
|
| 664 |
+
},
|
| 665 |
+
}
|
| 666 |
+
)
|
| 667 |
+
|
| 668 |
+
|
| 669 |
+
def _record_dict(record: Any, *field_names: str) -> dict[str, Any]:
|
| 670 |
+
result: dict[str, Any] = {"attributes": thaw_json(record.attributes)}
|
| 671 |
+
for name in field_names:
|
| 672 |
+
value = getattr(record, name)
|
| 673 |
+
result[name] = list(value) if isinstance(value, tuple) else value
|
| 674 |
+
return result
|
| 675 |
+
|
| 676 |
+
|
| 677 |
+
def _record_from_dict(
|
| 678 |
+
record_type: type[Any],
|
| 679 |
+
value: Mapping[str, Any],
|
| 680 |
+
id_field: str,
|
| 681 |
+
*,
|
| 682 |
+
required: tuple[str, ...] = (),
|
| 683 |
+
) -> Any:
|
| 684 |
+
value = _as_mapping(value, record_type.__name__)
|
| 685 |
+
defaults = dict(_RECORD_DEFAULTS[record_type])
|
| 686 |
+
allowed = frozenset({id_field, *defaults, *required, "attributes"})
|
| 687 |
+
_known_fields(value, allowed, record_type.__name__)
|
| 688 |
+
kwargs = {id_field: value.get(id_field, ""), "attributes": value.get("attributes", {})}
|
| 689 |
+
for name, default in defaults.items():
|
| 690 |
+
item = value.get(name, default)
|
| 691 |
+
kwargs[name] = tuple(item) if isinstance(default, tuple) else item
|
| 692 |
+
for name in required:
|
| 693 |
+
kwargs[name] = value.get(name, "")
|
| 694 |
+
return record_type(**kwargs)
|
| 695 |
+
|
| 696 |
+
|
| 697 |
+
SECURITY_IR_COLLECTION_SCHEMA = CollectionSchema(
|
| 698 |
+
{
|
| 699 |
+
"/sources": CollectionSemantics.SET_LIKE,
|
| 700 |
+
"/principals": CollectionSemantics.SET_LIKE,
|
| 701 |
+
"/principals/*/role_ids": CollectionSemantics.SET_LIKE,
|
| 702 |
+
"/principals/*/trust_zone_ids": CollectionSemantics.SET_LIKE,
|
| 703 |
+
"/principals/*/source_ids": CollectionSemantics.SET_LIKE,
|
| 704 |
+
"/assets": CollectionSemantics.SET_LIKE,
|
| 705 |
+
"/assets/*/source_ids": CollectionSemantics.SET_LIKE,
|
| 706 |
+
"/trust_zones": CollectionSemantics.SET_LIKE,
|
| 707 |
+
"/trust_zones/*/source_ids": CollectionSemantics.SET_LIKE,
|
| 708 |
+
"/channels": CollectionSemantics.SET_LIKE,
|
| 709 |
+
"/channels/*/trust_zone_ids": CollectionSemantics.SET_LIKE,
|
| 710 |
+
"/channels/*/source_ids": CollectionSemantics.SET_LIKE,
|
| 711 |
+
"/resources": CollectionSemantics.SET_LIKE,
|
| 712 |
+
"/resources/*/owner_principal_ids": CollectionSemantics.SET_LIKE,
|
| 713 |
+
"/resources/*/asset_ids": CollectionSemantics.SET_LIKE,
|
| 714 |
+
"/resources/*/trust_zone_ids": CollectionSemantics.SET_LIKE,
|
| 715 |
+
"/resources/*/source_ids": CollectionSemantics.SET_LIKE,
|
| 716 |
+
"/policies": CollectionSemantics.SET_LIKE,
|
| 717 |
+
"/policies/*/principal_ids": CollectionSemantics.SET_LIKE,
|
| 718 |
+
"/policies/*/resource_ids": CollectionSemantics.SET_LIKE,
|
| 719 |
+
"/policies/*/channel_ids": CollectionSemantics.SET_LIKE,
|
| 720 |
+
"/policies/*/source_ids": CollectionSemantics.SET_LIKE,
|
| 721 |
+
"/state_machines": CollectionSemantics.SET_LIKE,
|
| 722 |
+
"/state_machines/*/states": CollectionSemantics.SET_LIKE,
|
| 723 |
+
"/state_machines/*/transitions": CollectionSemantics.SET_LIKE,
|
| 724 |
+
"/state_machines/*/source_ids": CollectionSemantics.SET_LIKE,
|
| 725 |
+
"/assumptions": CollectionSemantics.SET_LIKE,
|
| 726 |
+
"/assumptions/*/source_ids": CollectionSemantics.SET_LIKE,
|
| 727 |
+
"/claims": CollectionSemantics.SET_LIKE,
|
| 728 |
+
"/claims/*/assumption_ids": CollectionSemantics.SET_LIKE,
|
| 729 |
+
"/claims/*/policy_ids": CollectionSemantics.SET_LIKE,
|
| 730 |
+
"/claims/*/source_ids": CollectionSemantics.SET_LIKE,
|
| 731 |
+
"/extensions": CollectionSemantics.SET_LIKE,
|
| 732 |
+
"/extensions/*/source_ids": CollectionSemantics.SET_LIKE,
|
| 733 |
+
}
|
| 734 |
+
)
|
| 735 |
+
|
| 736 |
+
|
| 737 |
+
@dataclass(frozen=True, slots=True)
|
| 738 |
+
class SecurityIR:
|
| 739 |
+
"""An immutable Security IR declaration with dependency-stable identity."""
|
| 740 |
+
|
| 741 |
+
declaration_id: str
|
| 742 |
+
principals: tuple[Principal, ...] = ()
|
| 743 |
+
assets: tuple[Asset, ...] = ()
|
| 744 |
+
trust_zones: tuple[TrustZone, ...] = ()
|
| 745 |
+
channels: tuple[Channel, ...] = ()
|
| 746 |
+
resources: tuple[Resource, ...] = ()
|
| 747 |
+
policies: tuple[Policy, ...] = ()
|
| 748 |
+
state_machines: tuple[StateMachine, ...] = ()
|
| 749 |
+
assumptions: tuple[ThreatAssumption, ...] = ()
|
| 750 |
+
claims: tuple[SecurityClaim, ...] = ()
|
| 751 |
+
sources: tuple[SecuritySource, ...] = ()
|
| 752 |
+
extensions: tuple[SecurityExtension, ...] = ()
|
| 753 |
+
schema_version: str = SECURITY_IR_SCHEMA_VERSION
|
| 754 |
+
|
| 755 |
+
_COLLECTION_TYPES: ClassVar[Mapping[str, type[Any]]] = MappingProxyType(
|
| 756 |
+
{
|
| 757 |
+
"principals": Principal,
|
| 758 |
+
"assets": Asset,
|
| 759 |
+
"trust_zones": TrustZone,
|
| 760 |
+
"channels": Channel,
|
| 761 |
+
"resources": Resource,
|
| 762 |
+
"policies": Policy,
|
| 763 |
+
"state_machines": StateMachine,
|
| 764 |
+
"assumptions": ThreatAssumption,
|
| 765 |
+
"claims": SecurityClaim,
|
| 766 |
+
"sources": SecuritySource,
|
| 767 |
+
"extensions": SecurityExtension,
|
| 768 |
+
}
|
| 769 |
+
)
|
| 770 |
+
|
| 771 |
+
def __post_init__(self) -> None:
|
| 772 |
+
object.__setattr__(
|
| 773 |
+
self,
|
| 774 |
+
"declaration_id",
|
| 775 |
+
_identifier(self.declaration_id, "declaration_id"),
|
| 776 |
+
)
|
| 777 |
+
if self.schema_version != SECURITY_IR_SCHEMA_VERSION:
|
| 778 |
+
raise SecurityIRValidationError(
|
| 779 |
+
f"unsupported Security IR schema version: {self.schema_version!r}"
|
| 780 |
+
)
|
| 781 |
+
for name, record_type in self._COLLECTION_TYPES.items():
|
| 782 |
+
values = getattr(self, name)
|
| 783 |
+
if isinstance(values, (str, bytes, bytearray)) or not isinstance(values, Sequence):
|
| 784 |
+
raise SecurityIRValidationError(f"{name} must be a sequence")
|
| 785 |
+
converted = tuple(
|
| 786 |
+
item
|
| 787 |
+
if isinstance(item, record_type)
|
| 788 |
+
else record_type.from_dict(_as_mapping(item, name))
|
| 789 |
+
for item in values
|
| 790 |
+
)
|
| 791 |
+
object.__setattr__(self, name, converted)
|
| 792 |
+
validate_security_ir(self)
|
| 793 |
+
|
| 794 |
+
def to_dict(self) -> dict[str, Any]:
|
| 795 |
+
"""Return a detached, JSON-ready declaration payload."""
|
| 796 |
+
|
| 797 |
+
return {
|
| 798 |
+
"assets": [item.to_dict() for item in self.assets],
|
| 799 |
+
"assumptions": [item.to_dict() for item in self.assumptions],
|
| 800 |
+
"channels": [item.to_dict() for item in self.channels],
|
| 801 |
+
"claims": [item.to_dict() for item in self.claims],
|
| 802 |
+
"declaration_id": self.declaration_id,
|
| 803 |
+
"extensions": [item.to_dict() for item in self.extensions],
|
| 804 |
+
"policies": [item.to_dict() for item in self.policies],
|
| 805 |
+
"principals": [item.to_dict() for item in self.principals],
|
| 806 |
+
"resources": [item.to_dict() for item in self.resources],
|
| 807 |
+
"schema_version": self.schema_version,
|
| 808 |
+
"sources": [item.to_dict() for item in self.sources],
|
| 809 |
+
"state_machines": [item.to_dict() for item in self.state_machines],
|
| 810 |
+
"trust_zones": [item.to_dict() for item in self.trust_zones],
|
| 811 |
+
}
|
| 812 |
+
|
| 813 |
+
def validate(self) -> None:
|
| 814 |
+
"""Validate this declaration against the complete v1 contract."""
|
| 815 |
+
|
| 816 |
+
validate_security_ir(self)
|
| 817 |
+
|
| 818 |
+
@classmethod
|
| 819 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "SecurityIR":
|
| 820 |
+
"""Decode a strict Security IR v1 declaration."""
|
| 821 |
+
|
| 822 |
+
value = _as_mapping(value, "SecurityIR")
|
| 823 |
+
allowed = frozenset({"declaration_id", "schema_version", *cls._COLLECTION_TYPES})
|
| 824 |
+
_known_fields(value, allowed, "SecurityIR")
|
| 825 |
+
kwargs: dict[str, Any] = {
|
| 826 |
+
"declaration_id": value.get("declaration_id", ""),
|
| 827 |
+
"schema_version": value.get("schema_version", SECURITY_IR_SCHEMA_VERSION),
|
| 828 |
+
}
|
| 829 |
+
for name, record_type in cls._COLLECTION_TYPES.items():
|
| 830 |
+
raw = value.get(name, ())
|
| 831 |
+
if isinstance(raw, (str, bytes, bytearray)) or not isinstance(raw, Sequence):
|
| 832 |
+
raise SecurityIRValidationError(f"{name} must be a sequence")
|
| 833 |
+
kwargs[name] = tuple(record_type.from_dict(item) for item in raw)
|
| 834 |
+
return cls(**kwargs)
|
| 835 |
+
|
| 836 |
+
def canonical_bytes(self) -> bytes:
|
| 837 |
+
"""Return canonical declaration bytes (not a verification artifact)."""
|
| 838 |
+
|
| 839 |
+
return canonical_json_bytes(self.to_dict(), collection_schema=SECURITY_IR_COLLECTION_SCHEMA)
|
| 840 |
+
|
| 841 |
+
def canonical_json(self) -> str:
|
| 842 |
+
"""Return canonical declaration JSON."""
|
| 843 |
+
|
| 844 |
+
return self.canonical_bytes().decode("utf-8")
|
| 845 |
+
|
| 846 |
+
@property
|
| 847 |
+
def identity(self) -> CanonicalIdentity:
|
| 848 |
+
"""Return the shared fixed-profile identity for this declaration."""
|
| 849 |
+
|
| 850 |
+
return canonical_identity(
|
| 851 |
+
self.to_dict(),
|
| 852 |
+
domain=SECURITY_IR_IDENTITY_DOMAIN,
|
| 853 |
+
schema_version=self.schema_version,
|
| 854 |
+
collection_schema=SECURITY_IR_COLLECTION_SCHEMA,
|
| 855 |
+
)
|
| 856 |
+
|
| 857 |
+
@property
|
| 858 |
+
def declaration_identity(self) -> CanonicalIdentity:
|
| 859 |
+
"""Explicit spelling emphasizing that result state is not addressed."""
|
| 860 |
+
|
| 861 |
+
return self.identity
|
| 862 |
+
|
| 863 |
+
@property
|
| 864 |
+
def model_id(self) -> str:
|
| 865 |
+
"""Compatibility spelling for the declaration's stable local ID."""
|
| 866 |
+
|
| 867 |
+
return self.declaration_id
|
| 868 |
+
|
| 869 |
+
@property
|
| 870 |
+
def digest(self) -> str:
|
| 871 |
+
return self.identity.digest
|
| 872 |
+
|
| 873 |
+
@property
|
| 874 |
+
def cid(self) -> str:
|
| 875 |
+
return self.identity.cid
|
| 876 |
+
|
| 877 |
+
|
| 878 |
+
def _unique(records: Sequence[Any], field_name: str, label: str) -> set[str]:
|
| 879 |
+
values = [getattr(item, field_name) for item in records]
|
| 880 |
+
if len(values) != len(set(values)):
|
| 881 |
+
raise SecurityIRValidationError(f"duplicate {label} identifier")
|
| 882 |
+
return set(values)
|
| 883 |
+
|
| 884 |
+
|
| 885 |
+
def _require_refs(values: Sequence[str], known: set[str], field_name: str) -> None:
|
| 886 |
+
missing = sorted(set(values) - known)
|
| 887 |
+
if missing:
|
| 888 |
+
raise SecurityIRValidationError(f"{field_name} contains unknown identifiers: {missing}")
|
| 889 |
+
|
| 890 |
+
|
| 891 |
+
def validate_security_ir(declaration: SecurityIR) -> SecurityIR:
|
| 892 |
+
"""Validate identifiers, types, and cross-references in a declaration."""
|
| 893 |
+
|
| 894 |
+
if not isinstance(declaration, SecurityIR):
|
| 895 |
+
raise SecurityIRValidationError("declaration must be a SecurityIR")
|
| 896 |
+
source_ids = _unique(declaration.sources, "source_id", "source")
|
| 897 |
+
principal_ids = _unique(declaration.principals, "principal_id", "principal")
|
| 898 |
+
asset_ids = _unique(declaration.assets, "asset_id", "asset")
|
| 899 |
+
zone_ids = _unique(declaration.trust_zones, "trust_zone_id", "trust zone")
|
| 900 |
+
channel_ids = _unique(declaration.channels, "channel_id", "channel")
|
| 901 |
+
resource_ids = _unique(declaration.resources, "resource_id", "resource")
|
| 902 |
+
policy_ids = _unique(declaration.policies, "policy_id", "policy")
|
| 903 |
+
_unique(declaration.state_machines, "state_machine_id", "state machine")
|
| 904 |
+
assumption_ids = _unique(declaration.assumptions, "assumption_id", "assumption")
|
| 905 |
+
_unique(declaration.claims, "claim_id", "claim")
|
| 906 |
+
_unique(declaration.extensions, "extension_id", "extension")
|
| 907 |
+
|
| 908 |
+
for record in (
|
| 909 |
+
*declaration.principals,
|
| 910 |
+
*declaration.assets,
|
| 911 |
+
*declaration.trust_zones,
|
| 912 |
+
*declaration.channels,
|
| 913 |
+
*declaration.resources,
|
| 914 |
+
*declaration.policies,
|
| 915 |
+
*declaration.state_machines,
|
| 916 |
+
*declaration.assumptions,
|
| 917 |
+
*declaration.claims,
|
| 918 |
+
*declaration.extensions,
|
| 919 |
+
):
|
| 920 |
+
_require_refs(record.source_ids, source_ids, f"{type(record).__name__}.source_ids")
|
| 921 |
+
for item in declaration.principals:
|
| 922 |
+
_require_refs(
|
| 923 |
+
item.trust_zone_ids, zone_ids, f"Principal {item.principal_id}.trust_zone_ids"
|
| 924 |
+
)
|
| 925 |
+
for item in declaration.channels:
|
| 926 |
+
known_nodes = principal_ids | resource_ids | asset_ids | zone_ids
|
| 927 |
+
_require_refs(
|
| 928 |
+
(item.source_node_id, item.target_node_id),
|
| 929 |
+
known_nodes,
|
| 930 |
+
f"Channel {item.channel_id} endpoints",
|
| 931 |
+
)
|
| 932 |
+
_require_refs(item.trust_zone_ids, zone_ids, f"Channel {item.channel_id}.trust_zone_ids")
|
| 933 |
+
for item in declaration.resources:
|
| 934 |
+
_require_refs(
|
| 935 |
+
item.owner_principal_ids,
|
| 936 |
+
principal_ids,
|
| 937 |
+
f"Resource {item.resource_id}.owner_principal_ids",
|
| 938 |
+
)
|
| 939 |
+
_require_refs(item.asset_ids, asset_ids, f"Resource {item.resource_id}.asset_ids")
|
| 940 |
+
_require_refs(
|
| 941 |
+
item.trust_zone_ids,
|
| 942 |
+
zone_ids,
|
| 943 |
+
f"Resource {item.resource_id}.trust_zone_ids",
|
| 944 |
+
)
|
| 945 |
+
for item in declaration.policies:
|
| 946 |
+
_require_refs(
|
| 947 |
+
item.principal_ids,
|
| 948 |
+
principal_ids,
|
| 949 |
+
f"Policy {item.policy_id}.principal_ids",
|
| 950 |
+
)
|
| 951 |
+
_require_refs(
|
| 952 |
+
item.resource_ids,
|
| 953 |
+
resource_ids,
|
| 954 |
+
f"Policy {item.policy_id}.resource_ids",
|
| 955 |
+
)
|
| 956 |
+
_require_refs(item.channel_ids, channel_ids, f"Policy {item.policy_id}.channel_ids")
|
| 957 |
+
for item in declaration.claims:
|
| 958 |
+
_require_refs(
|
| 959 |
+
item.assumption_ids,
|
| 960 |
+
assumption_ids,
|
| 961 |
+
f"SecurityClaim {item.claim_id}.assumption_ids",
|
| 962 |
+
)
|
| 963 |
+
_require_refs(item.policy_ids, policy_ids, f"SecurityClaim {item.claim_id}.policy_ids")
|
| 964 |
+
return declaration
|
| 965 |
+
|
| 966 |
+
|
| 967 |
+
# Descriptive aliases for callers using the plan's plural vocabulary.
|
| 968 |
+
Assumption = ThreatAssumption
|
| 969 |
+
Claim = SecurityClaim
|
| 970 |
+
Source = SecuritySource
|
| 971 |
+
Extension = SecurityExtension
|
| 972 |
+
SecurityAsset = Asset
|
| 973 |
+
SecurityAssumption = ThreatAssumption
|
| 974 |
+
SecurityChannel = Channel
|
| 975 |
+
SecurityPolicy = Policy
|
| 976 |
+
SecurityPrincipal = Principal
|
| 977 |
+
SecurityResource = Resource
|
| 978 |
+
SecurityStateMachine = StateMachine
|
| 979 |
+
SecurityTrustZone = TrustZone
|
| 980 |
+
SecurityIRV1 = SecurityIR
|
| 981 |
+
|
| 982 |
+
|
| 983 |
+
__all__ = [
|
| 984 |
+
"Asset",
|
| 985 |
+
"Assumption",
|
| 986 |
+
"Channel",
|
| 987 |
+
"Claim",
|
| 988 |
+
"Extension",
|
| 989 |
+
"Policy",
|
| 990 |
+
"PolicyEffect",
|
| 991 |
+
"Principal",
|
| 992 |
+
"Resource",
|
| 993 |
+
"SECURITY_IR_COLLECTION_SCHEMA",
|
| 994 |
+
"SECURITY_IR_IDENTITY_DOMAIN",
|
| 995 |
+
"SECURITY_IR_SCHEMA_VERSION",
|
| 996 |
+
"SECURITY_IR_V1_SCHEMA_VERSION",
|
| 997 |
+
"SecurityAsset",
|
| 998 |
+
"SecurityAssumption",
|
| 999 |
+
"SecurityChannel",
|
| 1000 |
+
"SecurityClaim",
|
| 1001 |
+
"SecurityExtension",
|
| 1002 |
+
"SecurityIR",
|
| 1003 |
+
"SecurityIRV1",
|
| 1004 |
+
"SecurityIRValidationError",
|
| 1005 |
+
"SecurityPolicy",
|
| 1006 |
+
"SecurityPrincipal",
|
| 1007 |
+
"SecurityResource",
|
| 1008 |
+
"SecuritySource",
|
| 1009 |
+
"SecurityStateMachine",
|
| 1010 |
+
"SecurityTrustZone",
|
| 1011 |
+
"Source",
|
| 1012 |
+
"StateMachine",
|
| 1013 |
+
"StateTransition",
|
| 1014 |
+
"ThreatAssumption",
|
| 1015 |
+
"TrustZone",
|
| 1016 |
+
"validate_security_ir",
|
| 1017 |
+
]
|
releases/20261004-retained-checkpoints-v1/source/d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
releases/20261004-retained-checkpoints-v1/source/d7be6bff3a1f1464d4783567b90942258ef718bc1c2b7e02938698ed4e619e57/ipfs_datasets_py/logic/ui_ux_ir/decoder.py
ADDED
|
@@ -0,0 +1,207 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Exact-version decoding for UI/UX IR wire documents (UIR-011)."""
|
| 2 |
+
|
| 3 |
+
from __future__ import annotations
|
| 4 |
+
|
| 5 |
+
import json
|
| 6 |
+
from typing import Any, Mapping
|
| 7 |
+
|
| 8 |
+
from .schema import (
|
| 9 |
+
LEGACY_UI_UX_IR_SCHEMA_VERSION,
|
| 10 |
+
ReviewStatus,
|
| 11 |
+
SourceSpan,
|
| 12 |
+
TerminalOutcomeKind,
|
| 13 |
+
UIComponent,
|
| 14 |
+
UILocaleDefaults,
|
| 15 |
+
UIIRDocument,
|
| 16 |
+
UIIRValidationError,
|
| 17 |
+
UISourceRef,
|
| 18 |
+
UITerminalOutcome,
|
| 19 |
+
UI_UX_IR_SCHEMA_VERSION,
|
| 20 |
+
reject_unknown_document_fields,
|
| 21 |
+
validate_ui_ir,
|
| 22 |
+
)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class UIIRDecodeError(UIIRValidationError):
|
| 26 |
+
"""Raised when an untrusted payload cannot be decoded exactly."""
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def _require_mapping(value: Any, label: str) -> Mapping[str, Any]:
|
| 30 |
+
if not isinstance(value, Mapping):
|
| 31 |
+
raise UIIRDecodeError(f"{label} must be an object")
|
| 32 |
+
return value
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
def _tuple_str(value: Any, label: str) -> tuple[str, ...]:
|
| 36 |
+
if value is None:
|
| 37 |
+
return ()
|
| 38 |
+
if not isinstance(value, (list, tuple)):
|
| 39 |
+
raise UIIRDecodeError(f"{label} must be an array")
|
| 40 |
+
out: list[str] = []
|
| 41 |
+
for item in value:
|
| 42 |
+
if not isinstance(item, str) or not item.strip():
|
| 43 |
+
raise UIIRDecodeError(f"{label} members must be non-empty strings")
|
| 44 |
+
out.append(item)
|
| 45 |
+
return tuple(out)
|
| 46 |
+
|
| 47 |
+
|
| 48 |
+
def _decode_source(payload: Mapping[str, Any]) -> UISourceRef:
|
| 49 |
+
span_raw = payload.get("span")
|
| 50 |
+
span = None
|
| 51 |
+
if span_raw is not None:
|
| 52 |
+
span_map = _require_mapping(span_raw, "UISourceRef.span")
|
| 53 |
+
span = SourceSpan(
|
| 54 |
+
start_char=int(span_map.get("start_char", 0)),
|
| 55 |
+
end_char=int(span_map.get("end_char", 0)),
|
| 56 |
+
)
|
| 57 |
+
review = payload.get("review_status", ReviewStatus.UNREVIEWED)
|
| 58 |
+
if isinstance(review, str):
|
| 59 |
+
review = ReviewStatus(review)
|
| 60 |
+
return UISourceRef(
|
| 61 |
+
ref_id=str(payload.get("ref_id") or ""),
|
| 62 |
+
source_uri=str(payload.get("source_uri") or ""),
|
| 63 |
+
source_id=str(payload.get("source_id") or ""),
|
| 64 |
+
source_revision=str(payload.get("source_revision") or ""),
|
| 65 |
+
content_sha256=str(payload.get("content_sha256") or ""),
|
| 66 |
+
container_uri=str(payload.get("container_uri") or ""),
|
| 67 |
+
container_sha256=str(payload.get("container_sha256") or ""),
|
| 68 |
+
content_cid=str(payload.get("content_cid") or ""),
|
| 69 |
+
license_expression=str(payload.get("license_expression") or ""),
|
| 70 |
+
review_status=review,
|
| 71 |
+
span=span,
|
| 72 |
+
)
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def _decode_component(payload: Mapping[str, Any]) -> UIComponent:
|
| 76 |
+
return UIComponent(
|
| 77 |
+
component_id=str(payload.get("component_id") or ""),
|
| 78 |
+
role=str(payload.get("role") or ""),
|
| 79 |
+
purpose=str(payload.get("purpose") or ""),
|
| 80 |
+
accessible_name_ref=str(payload.get("accessible_name_ref") or ""),
|
| 81 |
+
accessible_description_ref=str(payload.get("accessible_description_ref") or ""),
|
| 82 |
+
parent_id=str(payload.get("parent_id") or ""),
|
| 83 |
+
child_ids=_tuple_str(payload.get("child_ids"), "UIComponent.child_ids"),
|
| 84 |
+
modality_binding_ids=_tuple_str(
|
| 85 |
+
payload.get("modality_binding_ids"), "UIComponent.modality_binding_ids"
|
| 86 |
+
),
|
| 87 |
+
data_binding_ids=_tuple_str(
|
| 88 |
+
payload.get("data_binding_ids"), "UIComponent.data_binding_ids"
|
| 89 |
+
),
|
| 90 |
+
program_binding_ids=_tuple_str(
|
| 91 |
+
payload.get("program_binding_ids"), "UIComponent.program_binding_ids"
|
| 92 |
+
),
|
| 93 |
+
feedback_ids=_tuple_str(payload.get("feedback_ids"), "UIComponent.feedback_ids"),
|
| 94 |
+
privacy_sensitivity=str(payload.get("privacy_sensitivity") or "none"),
|
| 95 |
+
presentation_classification=str(
|
| 96 |
+
payload.get("presentation_classification") or "interactive"
|
| 97 |
+
),
|
| 98 |
+
source_ref_ids=_tuple_str(
|
| 99 |
+
payload.get("source_ref_ids"), "UIComponent.source_ref_ids"
|
| 100 |
+
),
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
|
| 104 |
+
def _decode_terminal(payload: Mapping[str, Any]) -> UITerminalOutcome:
|
| 105 |
+
kind = payload.get("kind", TerminalOutcomeKind.SUCCESS)
|
| 106 |
+
if isinstance(kind, str):
|
| 107 |
+
kind = TerminalOutcomeKind(kind)
|
| 108 |
+
return UITerminalOutcome(
|
| 109 |
+
outcome_id=str(payload.get("outcome_id") or ""),
|
| 110 |
+
kind=kind,
|
| 111 |
+
description=str(payload.get("description") or ""),
|
| 112 |
+
source_ref_ids=_tuple_str(
|
| 113 |
+
payload.get("source_ref_ids"), "UITerminalOutcome.source_ref_ids"
|
| 114 |
+
),
|
| 115 |
+
)
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _decode_locale(payload: Mapping[str, Any] | None) -> UILocaleDefaults:
|
| 119 |
+
if not payload:
|
| 120 |
+
return UILocaleDefaults()
|
| 121 |
+
data = _require_mapping(payload, "locale_defaults")
|
| 122 |
+
return UILocaleDefaults(
|
| 123 |
+
default_locale=str(data.get("default_locale") or "en"),
|
| 124 |
+
fallback_locales=_tuple_str(
|
| 125 |
+
data.get("fallback_locales"), "locale_defaults.fallback_locales"
|
| 126 |
+
),
|
| 127 |
+
text_direction=str(data.get("text_direction") or "ltr"),
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def decode_ui_ir(payload: Mapping[str, Any] | str | bytes) -> UIIRDocument:
|
| 132 |
+
"""Decode a wire payload into a validated ``UIIRDocument``.
|
| 133 |
+
|
| 134 |
+
Unknown versions and unknown top-level fields fail closed. Legacy versions
|
| 135 |
+
must be migrated explicitly via :mod:`migrations` before decode.
|
| 136 |
+
"""
|
| 137 |
+
|
| 138 |
+
if isinstance(payload, (bytes, bytearray)):
|
| 139 |
+
try:
|
| 140 |
+
payload = json.loads(bytes(payload).decode("utf-8"))
|
| 141 |
+
except (UnicodeDecodeError, json.JSONDecodeError) as exc:
|
| 142 |
+
raise UIIRDecodeError(f"UI/UX IR payload is not valid UTF-8 JSON: {exc}") from exc
|
| 143 |
+
elif isinstance(payload, str):
|
| 144 |
+
try:
|
| 145 |
+
payload = json.loads(payload)
|
| 146 |
+
except json.JSONDecodeError as exc:
|
| 147 |
+
raise UIIRDecodeError(f"UI/UX IR payload is not valid JSON: {exc}") from exc
|
| 148 |
+
if not isinstance(payload, Mapping):
|
| 149 |
+
raise UIIRDecodeError("UI/UX IR payload must decode to an object")
|
| 150 |
+
|
| 151 |
+
version = str(payload.get("schema_version") or "")
|
| 152 |
+
if not version:
|
| 153 |
+
raise UIIRDecodeError("UI/UX IR payload missing schema_version")
|
| 154 |
+
if version == LEGACY_UI_UX_IR_SCHEMA_VERSION:
|
| 155 |
+
raise UIIRDecodeError(
|
| 156 |
+
f"Legacy schema_version {version!r} requires explicit migration before decode"
|
| 157 |
+
)
|
| 158 |
+
if version != UI_UX_IR_SCHEMA_VERSION:
|
| 159 |
+
raise UIIRDecodeError(
|
| 160 |
+
f"Unsupported schema_version {version!r}; expected {UI_UX_IR_SCHEMA_VERSION!r}"
|
| 161 |
+
)
|
| 162 |
+
try:
|
| 163 |
+
reject_unknown_document_fields(payload)
|
| 164 |
+
except UIIRValidationError as exc:
|
| 165 |
+
raise UIIRDecodeError(str(exc)) from exc
|
| 166 |
+
|
| 167 |
+
sources_raw = payload.get("sources") or ()
|
| 168 |
+
components_raw = payload.get("components") or ()
|
| 169 |
+
terminals_raw = payload.get("terminal_outcomes") or ()
|
| 170 |
+
if not isinstance(sources_raw, (list, tuple)):
|
| 171 |
+
raise UIIRDecodeError("sources must be an array")
|
| 172 |
+
if not isinstance(components_raw, (list, tuple)):
|
| 173 |
+
raise UIIRDecodeError("components must be an array")
|
| 174 |
+
if not isinstance(terminals_raw, (list, tuple)):
|
| 175 |
+
raise UIIRDecodeError("terminal_outcomes must be an array")
|
| 176 |
+
|
| 177 |
+
try:
|
| 178 |
+
document = UIIRDocument(
|
| 179 |
+
document_id=str(payload.get("document_id") or ""),
|
| 180 |
+
title=str(payload.get("title") or ""),
|
| 181 |
+
schema_version=version,
|
| 182 |
+
sources=tuple(
|
| 183 |
+
_decode_source(_require_mapping(item, "sources[]")) for item in sources_raw
|
| 184 |
+
),
|
| 185 |
+
components=tuple(
|
| 186 |
+
_decode_component(_require_mapping(item, "components[]"))
|
| 187 |
+
for item in components_raw
|
| 188 |
+
),
|
| 189 |
+
entry_components=_tuple_str(
|
| 190 |
+
payload.get("entry_components"), "entry_components"
|
| 191 |
+
),
|
| 192 |
+
terminal_outcomes=tuple(
|
| 193 |
+
_decode_terminal(_require_mapping(item, "terminal_outcomes[]"))
|
| 194 |
+
for item in terminals_raw
|
| 195 |
+
),
|
| 196 |
+
locale_defaults=_decode_locale(payload.get("locale_defaults")),
|
| 197 |
+
tags=_tuple_str(payload.get("tags"), "tags"),
|
| 198 |
+
)
|
| 199 |
+
except UIIRValidationError as exc:
|
| 200 |
+
raise UIIRDecodeError(str(exc)) from exc
|
| 201 |
+
except (TypeError, ValueError, KeyError) as exc:
|
| 202 |
+
raise UIIRDecodeError(f"Failed to decode UI/UX IR document: {exc}") from exc
|
| 203 |
+
|
| 204 |
+
return validate_ui_ir(document)
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
__all__ = ["UIIRDecodeError", "decode_ui_ir"]
|
releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py
ADDED
|
@@ -0,0 +1,611 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lineage-bound joint residual projection and latent-conditioned formula decoder.
|
| 2 |
+
|
| 3 |
+
The frozen 8D or current 384D numerical core supplies a raw representation.
|
| 4 |
+
This module trains a new residual projection and token decoder together using
|
| 5 |
+
embedding reconstruction and formula token losses. Formula gradients reach the
|
| 6 |
+
new projection; they do not differentiate the historical sparse core. Source
|
| 7 |
+
strings bind observations only and never enter the decoder. The first head
|
| 8 |
+
supports one exact canonical deontic rule; other logic projections abstain.
|
| 9 |
+
No checkpoint, metric or syntax check grants semantic or Lake admission.
|
| 10 |
+
"""
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import copy
|
| 14 |
+
import hashlib
|
| 15 |
+
import json
|
| 16 |
+
import math
|
| 17 |
+
from pathlib import Path
|
| 18 |
+
import random
|
| 19 |
+
import re
|
| 20 |
+
import stat
|
| 21 |
+
import time
|
| 22 |
+
|
| 23 |
+
from . import legal_formula_codec as codec_module
|
| 24 |
+
|
| 25 |
+
SCHEMA = "modal-latent-formula-checkpoint/v1"
|
| 26 |
+
ARCHITECTURE = "residual-projection-latent-formula-gru/v1"
|
| 27 |
+
PROJECTION_ID = "typed_deontic_rule_v1"
|
| 28 |
+
MAX_BYTES = 48 * 1024 * 1024
|
| 29 |
+
MAX_ROWS = 4096
|
| 30 |
+
FALSE = {"qualified": False, "admitted": False, "formalized": False,
|
| 31 |
+
"roundtrip_ok": False, "proof_authority": False,
|
| 32 |
+
"semantic_correctness_verified": False, "promotion_performed": False,
|
| 33 |
+
"publication_performed": False, "lake_executed": False}
|
| 34 |
+
_SHA = re.compile(r"[0-9a-f]{64}\Z")
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def _require(condition, message):
|
| 38 |
+
if not condition:
|
| 39 |
+
raise ValueError(message)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
def _raw(value):
|
| 43 |
+
return json.dumps(value, sort_keys=True, separators=(",", ":"),
|
| 44 |
+
ensure_ascii=True, allow_nan=False).encode()
|
| 45 |
+
|
| 46 |
+
|
| 47 |
+
def checkpoint_digest(value):
|
| 48 |
+
return hashlib.sha256(_raw(value)).hexdigest()
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _pins():
|
| 52 |
+
from ...logic.autoformal import tree_pin
|
| 53 |
+
from ...logic.legal_ir import canonical_contracts
|
| 54 |
+
from . import legal_ir_grammar_decoder
|
| 55 |
+
expected = next((parent / "ipfs_datasets_py" for parent in Path(__file__).resolve().parents
|
| 56 |
+
if (parent / "ipfs_datasets_py/logic/autoformal/tree_pin.py").is_file()), None)
|
| 57 |
+
_require(expected is not None, "canonical package root is missing")
|
| 58 |
+
modules = (codec_module, tree_pin, canonical_contracts, legal_ir_grammar_decoder)
|
| 59 |
+
for module in modules:
|
| 60 |
+
_require(expected.resolve() in Path(module.__file__).resolve().parents,
|
| 61 |
+
"latent formula dependency loaded outside pinned package tree")
|
| 62 |
+
tree_pin.require_workspace_logic_tree()
|
| 63 |
+
files = {Path(module.__file__).name: hashlib.sha256(Path(module.__file__).read_bytes()).hexdigest()
|
| 64 |
+
for module in modules}
|
| 65 |
+
files[Path(__file__).name] = hashlib.sha256(Path(__file__).read_bytes()).hexdigest()
|
| 66 |
+
return {"scope": "listed_latent_decoder_and_grammar_sources_only", "files": files}
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
_IMPLEMENTATION_AT_IMPORT = _pins()
|
| 70 |
+
|
| 71 |
+
|
| 72 |
+
def _implementation():
|
| 73 |
+
current = _pins()
|
| 74 |
+
_require(current == _IMPLEMENTATION_AT_IMPORT, "latent formula implementation changed since import")
|
| 75 |
+
return current
|
| 76 |
+
|
| 77 |
+
|
| 78 |
+
def _torch():
|
| 79 |
+
import torch
|
| 80 |
+
_require(torch.get_num_threads() == 1, "caller must reserve CPU and set torch.set_num_threads(1)")
|
| 81 |
+
return torch
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _binding(value):
|
| 85 |
+
fields = {"domain", "lineage_id", "dimension", "runtime_profile", "core_sha256"}
|
| 86 |
+
_require(type(value) is dict and set(value) == fields, "closed latent binding required")
|
| 87 |
+
_require(value["domain"] == "legal_ir", "legal latent decoder requires legal_ir domain")
|
| 88 |
+
dimension = {"legacy_hub_v1": 8, "current_legal_v2": 384}.get(value["lineage_id"])
|
| 89 |
+
_require(type(value["dimension"]) is int and dimension == value["dimension"],
|
| 90 |
+
"lineage and latent dimension differ")
|
| 91 |
+
_require(type(value["runtime_profile"]) is str and 0 < len(value["runtime_profile"]) <= 256,
|
| 92 |
+
"bounded runtime profile required")
|
| 93 |
+
_require(type(value["core_sha256"]) is str and _SHA.fullmatch(value["core_sha256"]),
|
| 94 |
+
"exact core state SHA256 required")
|
| 95 |
+
return copy.deepcopy(value)
|
| 96 |
+
|
| 97 |
+
|
| 98 |
+
def _config(*, learning_rate=.01, batch_size=8, seed=1729, hidden_size=32,
|
| 99 |
+
token_embedding_dim=16, projection_width=16, formula_weight=1., reconstruction_weight=1.):
|
| 100 |
+
for name, value, low, high in (("batch_size", batch_size, 1, 16), ("seed", seed, 0, 2**31 - 1),
|
| 101 |
+
("hidden_size", hidden_size, 8, 128), ("token_embedding_dim", token_embedding_dim, 8, 64),
|
| 102 |
+
("projection_width", projection_width, 1, 64)):
|
| 103 |
+
_require(type(value) is int and low <= value <= high, name + " is outside bounded integer range")
|
| 104 |
+
for name, value, high in (("learning_rate", learning_rate, .1), ("formula_weight", formula_weight, 100.),
|
| 105 |
+
("reconstruction_weight", reconstruction_weight, 100.)):
|
| 106 |
+
_require(type(value) in (int, float) and math.isfinite(value) and 0 < value <= high,
|
| 107 |
+
name + " must be finite and positive within its bound")
|
| 108 |
+
return {"architecture": ARCHITECTURE, "device": "cpu", "dtype": "float32", "temperature": 0,
|
| 109 |
+
"max_target_tokens": 64, "source_input": "provenance_only_not_neural_input",
|
| 110 |
+
"torch_version": str(_torch().__version__), "learning_rate": float(learning_rate),
|
| 111 |
+
"batch_size": batch_size, "seed": seed, "hidden_size": hidden_size,
|
| 112 |
+
"token_embedding_dim": token_embedding_dim, "projection_width": projection_width,
|
| 113 |
+
"formula_weight": float(formula_weight), "reconstruction_weight": float(reconstruction_weight)}
|
| 114 |
+
|
| 115 |
+
|
| 116 |
+
def _vector(value, dimension, label):
|
| 117 |
+
_require(type(value) is list and len(value) == dimension and all(
|
| 118 |
+
type(number) in (int, float) and math.isfinite(number) and abs(number) <= 1e8 for number in value),
|
| 119 |
+
label + " requires bounded finite values with exact lineage width")
|
| 120 |
+
|
| 121 |
+
|
| 122 |
+
def _rows(rows, dimension, *, training, allow_empty=False):
|
| 123 |
+
_require(type(rows) in (list, tuple) and (0 if allow_empty else 1) <= len(rows) <= MAX_ROWS,
|
| 124 |
+
"bounded rows required")
|
| 125 |
+
fields = {"id", "source_text", "latent"} | ({"embedding", "canonical_ir"} if training else set())
|
| 126 |
+
ids, sources = set(), set()
|
| 127 |
+
for row in rows:
|
| 128 |
+
_require(type(row) is dict and set(row) == fields, "closed latent row schema required")
|
| 129 |
+
_require(type(row["id"]) is str and 0 < len(row["id"]) <= 512 and row["id"] not in ids,
|
| 130 |
+
"unique bounded row id required")
|
| 131 |
+
_require(type(row["source_text"]) is str and 0 < len(row["source_text"]) <= 16384
|
| 132 |
+
and row["source_text"].strip(), "bounded nonempty source provenance required")
|
| 133 |
+
source = " ".join(row["source_text"].casefold().split())
|
| 134 |
+
_require(not training or source not in sources, "duplicate normalized training source")
|
| 135 |
+
ids.add(row["id"])
|
| 136 |
+
sources.add(source)
|
| 137 |
+
_vector(row["latent"], dimension, "latent")
|
| 138 |
+
if training:
|
| 139 |
+
_vector(row["embedding"], dimension, "embedding")
|
| 140 |
+
return list(rows)
|
| 141 |
+
|
| 142 |
+
|
| 143 |
+
def _splits(training, tuning, dimension):
|
| 144 |
+
train = _rows(training, dimension, training=True)
|
| 145 |
+
tune = _rows(tuning, dimension, training=True, allow_empty=True)
|
| 146 |
+
_require(not {row["id"] for row in train} & {row["id"] for row in tune}, "training/tuning IDs overlap")
|
| 147 |
+
key = lambda row: " ".join(row["source_text"].casefold().split())
|
| 148 |
+
_require(not {key(row) for row in train} & {key(row) for row in tune}, "training/tuning sources overlap")
|
| 149 |
+
return train, tune
|
| 150 |
+
|
| 151 |
+
|
| 152 |
+
def _model(binding, codec, config):
|
| 153 |
+
torch = _torch()
|
| 154 |
+
class JointDecoder(torch.nn.Module):
|
| 155 |
+
def __init__(self):
|
| 156 |
+
super().__init__()
|
| 157 |
+
dimension, width, hidden = binding["dimension"], config["projection_width"], config["hidden_size"]
|
| 158 |
+
self.projection_down = torch.nn.Linear(dimension, width)
|
| 159 |
+
self.projection_up = torch.nn.Linear(width, dimension)
|
| 160 |
+
self.condition = torch.nn.Linear(dimension, hidden)
|
| 161 |
+
self.target_embedding = torch.nn.Embedding(len(codec["target_vocabulary"]),
|
| 162 |
+
config["token_embedding_dim"], padding_idx=0)
|
| 163 |
+
self.decoder = torch.nn.GRU(config["token_embedding_dim"], hidden, batch_first=True)
|
| 164 |
+
self.output = torch.nn.Linear(hidden, len(codec["target_vocabulary"]))
|
| 165 |
+
|
| 166 |
+
def project(self, latent):
|
| 167 |
+
return latent + self.projection_up(torch.tanh(self.projection_down(latent)))
|
| 168 |
+
|
| 169 |
+
def start(self, projected):
|
| 170 |
+
return torch.tanh(self.condition(projected)).unsqueeze(0)
|
| 171 |
+
|
| 172 |
+
def next_logits(self, tokens, hidden):
|
| 173 |
+
outputs, hidden = self.decoder(self.target_embedding(tokens), hidden)
|
| 174 |
+
return self.output(outputs), hidden
|
| 175 |
+
|
| 176 |
+
def forward(self, latent, target):
|
| 177 |
+
projected = self.project(latent)
|
| 178 |
+
return projected, self.next_logits(target, self.start(projected))[0]
|
| 179 |
+
with torch.random.fork_rng(devices=[]):
|
| 180 |
+
torch.manual_seed(config["seed"])
|
| 181 |
+
model = JointDecoder()
|
| 182 |
+
return model
|
| 183 |
+
|
| 184 |
+
|
| 185 |
+
def _optimizer(model, config):
|
| 186 |
+
return _torch().optim.Adam(model.parameters(), lr=config["learning_rate"], foreach=False)
|
| 187 |
+
|
| 188 |
+
|
| 189 |
+
def _pack(model, optimizer):
|
| 190 |
+
states = {}
|
| 191 |
+
for name, parameter in model.named_parameters():
|
| 192 |
+
state = optimizer.state.get(parameter)
|
| 193 |
+
if state:
|
| 194 |
+
states[name] = {"step": int(state["step"].item()), "exp_avg": state["exp_avg"].detach().tolist(),
|
| 195 |
+
"exp_avg_sq": state["exp_avg_sq"].detach().tolist()}
|
| 196 |
+
return ({name: value.detach().tolist() for name, value in model.state_dict().items()},
|
| 197 |
+
{"schema": "adam-default-betas-eps/v1", "parameters": states})
|
| 198 |
+
|
| 199 |
+
|
| 200 |
+
def _tensor(value, template, label, *, nonnegative=False):
|
| 201 |
+
def check(part, shape):
|
| 202 |
+
if shape:
|
| 203 |
+
_require(type(part) is list and len(part) == shape[0], label + " tensor shape differs")
|
| 204 |
+
for item in part:
|
| 205 |
+
check(item, shape[1:])
|
| 206 |
+
else:
|
| 207 |
+
_require(type(part) in (int, float) and math.isfinite(part) and (not nonnegative or part >= 0),
|
| 208 |
+
label + " tensor values must be finite and valid")
|
| 209 |
+
check(value, tuple(template.shape))
|
| 210 |
+
tensor = _torch().tensor(value, dtype=_torch().float32)
|
| 211 |
+
_require(bool(_torch().isfinite(tensor).all()), label + " overflows float32")
|
| 212 |
+
return tensor
|
| 213 |
+
|
| 214 |
+
|
| 215 |
+
def build_checkpoint(binding, train_rows, tune_rows, **options):
|
| 216 |
+
"""Initialize a separate head; no existing weights are converted or updated."""
|
| 217 |
+
binding, config, implementation = _binding(binding), _config(**options), _implementation()
|
| 218 |
+
train, tune = _splits(train_rows, tune_rows, binding["dimension"])
|
| 219 |
+
# Reuse only the exact target grammar. The sentinel creates no textual model
|
| 220 |
+
# vocabulary, and actual source strings never condition generation.
|
| 221 |
+
codec = codec_module.fit_codec([{"id": row["id"], "source_text": "latent", "canonical_ir": row["canonical_ir"]}
|
| 222 |
+
for row in train])
|
| 223 |
+
for row in tune:
|
| 224 |
+
codec_module.encode_target(codec, row["canonical_ir"])
|
| 225 |
+
model = _model(binding, codec, config)
|
| 226 |
+
weights, optimizer = _pack(model, _optimizer(model, config))
|
| 227 |
+
checkpoint = {"schema": SCHEMA, "binding": binding, "projection_id": PROJECTION_ID, "config": config,
|
| 228 |
+
"codec": codec, "implementation": implementation, "training_manifest_sha256": checkpoint_digest(train),
|
| 229 |
+
"tuning_manifest_sha256": checkpoint_digest(tune), "training_count": len(train), "tuning_count": len(tune),
|
| 230 |
+
"model_state": weights, "optimizer_state": optimizer,
|
| 231 |
+
"progress": {"epochs_completed": 0, "row_cursor": 0, "optimizer_steps": 0},
|
| 232 |
+
"parent_checkpoint_sha256": None, **FALSE}
|
| 233 |
+
validate_checkpoint(checkpoint)
|
| 234 |
+
return checkpoint
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _restore(checkpoint, expected_binding=None):
|
| 238 |
+
torch = _torch()
|
| 239 |
+
fields = {"schema", "binding", "projection_id", "config", "codec", "implementation",
|
| 240 |
+
"training_manifest_sha256", "tuning_manifest_sha256", "training_count", "tuning_count",
|
| 241 |
+
"model_state", "optimizer_state", "progress", "parent_checkpoint_sha256", *FALSE}
|
| 242 |
+
_require(type(checkpoint) is dict and set(checkpoint) == fields and checkpoint["schema"] == SCHEMA,
|
| 243 |
+
"closed latent checkpoint schema required")
|
| 244 |
+
_require(len(_raw(checkpoint)) <= MAX_BYTES, "latent checkpoint exceeds byte bound")
|
| 245 |
+
_require(all(checkpoint[key] is False for key in FALSE), "latent checkpoint cannot grant authority")
|
| 246 |
+
binding = _binding(checkpoint["binding"])
|
| 247 |
+
if expected_binding is not None:
|
| 248 |
+
_require(binding == _binding(expected_binding), "latent checkpoint binding differs")
|
| 249 |
+
_require(checkpoint["projection_id"] == PROJECTION_ID, "unsupported formula projection")
|
| 250 |
+
_require(checkpoint["implementation"] == _implementation(), "latent formula source provenance differs")
|
| 251 |
+
config = checkpoint["config"]
|
| 252 |
+
keys = ("learning_rate", "batch_size", "seed", "hidden_size", "token_embedding_dim", "projection_width",
|
| 253 |
+
"formula_weight", "reconstruction_weight")
|
| 254 |
+
_require(type(config) is dict and all(name in config for name in keys), "closed model config required")
|
| 255 |
+
_require(_raw(config) == _raw(_config(**{name: config[name] for name in keys})), "model config differs")
|
| 256 |
+
codec_module.validate_codec(checkpoint["codec"])
|
| 257 |
+
_require(checkpoint["codec"]["source_vocabulary"] == ["<pad>", "<unk>", "latent"],
|
| 258 |
+
"latent model must not contain source vocabulary")
|
| 259 |
+
for name in ("training_manifest_sha256", "tuning_manifest_sha256"):
|
| 260 |
+
_require(type(checkpoint[name]) is str and _SHA.fullmatch(checkpoint[name]), "invalid manifest hash")
|
| 261 |
+
parent = checkpoint["parent_checkpoint_sha256"]
|
| 262 |
+
_require(parent is None or type(parent) is str and _SHA.fullmatch(parent), "invalid parent checkpoint hash")
|
| 263 |
+
count, tune_count = checkpoint["training_count"], checkpoint["tuning_count"]
|
| 264 |
+
_require(type(count) is int and 1 <= count <= MAX_ROWS and type(tune_count) is int and 0 <= tune_count <= MAX_ROWS,
|
| 265 |
+
"invalid split counts")
|
| 266 |
+
progress = checkpoint["progress"]
|
| 267 |
+
_require(type(progress) is dict and set(progress) == {"epochs_completed", "row_cursor", "optimizer_steps"}
|
| 268 |
+
and all(type(number) is int and 0 <= number <= 10**9 for number in progress.values()),
|
| 269 |
+
"closed bounded integer training progress required")
|
| 270 |
+
batch, cursor = config["batch_size"], progress["row_cursor"]
|
| 271 |
+
_require(cursor < count and cursor % batch == 0 and progress["optimizer_steps"] ==
|
| 272 |
+
progress["epochs_completed"] * math.ceil(count / batch) + cursor // batch,
|
| 273 |
+
"optimizer step and row cursor differ")
|
| 274 |
+
model = _model(binding, checkpoint["codec"], config)
|
| 275 |
+
templates = model.state_dict()
|
| 276 |
+
weights = checkpoint["model_state"]
|
| 277 |
+
_require(type(weights) is dict and set(weights) == set(templates), "model state keys differ")
|
| 278 |
+
model.load_state_dict({name: _tensor(weights[name], template, name) for name, template in templates.items()})
|
| 279 |
+
optimizer = _optimizer(model, config)
|
| 280 |
+
moments = checkpoint["optimizer_state"]
|
| 281 |
+
_require(type(moments) is dict and set(moments) == {"schema", "parameters"}
|
| 282 |
+
and moments["schema"] == "adam-default-betas-eps/v1" and type(moments["parameters"]) is dict,
|
| 283 |
+
"closed Adam moments required")
|
| 284 |
+
parameters = dict(model.named_parameters())
|
| 285 |
+
_require(set(moments["parameters"]) == (set(parameters) if progress["optimizer_steps"] else set()),
|
| 286 |
+
"Adam parameter set differs")
|
| 287 |
+
for name, item in moments["parameters"].items():
|
| 288 |
+
_require(type(item) is dict and set(item) == {"step", "exp_avg", "exp_avg_sq"}
|
| 289 |
+
and type(item["step"]) is int and item["step"] == progress["optimizer_steps"],
|
| 290 |
+
"Adam parameter step differs")
|
| 291 |
+
parameter = parameters[name]
|
| 292 |
+
optimizer.state[parameter] = {"step": torch.tensor(float(item["step"])),
|
| 293 |
+
"exp_avg": _tensor(item["exp_avg"], parameter, name + ".exp_avg"),
|
| 294 |
+
"exp_avg_sq": _tensor(item["exp_avg_sq"], parameter, name + ".exp_avg_sq", nonnegative=True)}
|
| 295 |
+
model.eval()
|
| 296 |
+
return torch, model, optimizer
|
| 297 |
+
|
| 298 |
+
|
| 299 |
+
def validate_checkpoint(checkpoint, *, expected_binding=None):
|
| 300 |
+
_restore(checkpoint, expected_binding)
|
| 301 |
+
|
| 302 |
+
|
| 303 |
+
def _batch(rows, codec):
|
| 304 |
+
torch = _torch()
|
| 305 |
+
targets = [codec_module.encode_target(codec, row["canonical_ir"]) for row in rows]
|
| 306 |
+
width = max(map(len, targets))
|
| 307 |
+
return (torch.tensor([row["latent"] for row in rows], dtype=torch.float32),
|
| 308 |
+
torch.tensor([row["embedding"] for row in rows], dtype=torch.float32),
|
| 309 |
+
torch.tensor([target + [0] * (width - len(target)) for target in targets], dtype=torch.long))
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
def _loss(model, rows, codec, config):
|
| 313 |
+
torch = _torch()
|
| 314 |
+
latent, expected_embedding, target = _batch(rows, codec)
|
| 315 |
+
projected, logits = model(latent, target[:, :-1])
|
| 316 |
+
expected = target[:, 1:]
|
| 317 |
+
formula = torch.nn.functional.cross_entropy(logits.reshape(-1, logits.shape[-1]), expected.reshape(-1), ignore_index=0)
|
| 318 |
+
reconstruction = torch.nn.functional.mse_loss(projected, expected_embedding)
|
| 319 |
+
total = config["formula_weight"] * formula + config["reconstruction_weight"] * reconstruction
|
| 320 |
+
return total, formula, reconstruction, int((expected != 0).sum())
|
| 321 |
+
|
| 322 |
+
|
| 323 |
+
def _norm(values):
|
| 324 |
+
return math.sqrt(sum(float(value.detach().double().square().sum()) for value in values if value is not None))
|
| 325 |
+
|
| 326 |
+
|
| 327 |
+
def _metrics(model, rows, codec, config, deadline):
|
| 328 |
+
torch = _torch()
|
| 329 |
+
evaluated, tokens, ce, reconstruction = 0, 0, 0., 0.
|
| 330 |
+
model.eval()
|
| 331 |
+
with torch.no_grad():
|
| 332 |
+
for start in range(0, len(rows), config["batch_size"]):
|
| 333 |
+
if time.monotonic() >= deadline:
|
| 334 |
+
break
|
| 335 |
+
batch = rows[start:start + config["batch_size"]]
|
| 336 |
+
loss, formula, mse, count = _loss(model, batch, codec, config)
|
| 337 |
+
_require(bool(torch.isfinite(loss)), "nonfinite evaluation loss")
|
| 338 |
+
ce += float(formula) * count
|
| 339 |
+
reconstruction += float(mse) * len(batch)
|
| 340 |
+
tokens += count
|
| 341 |
+
evaluated += len(batch)
|
| 342 |
+
return {"token_cross_entropy": ce / tokens if tokens else None,
|
| 343 |
+
"reconstruction_mse": reconstruction / evaluated if evaluated else None,
|
| 344 |
+
"rows_evaluated": evaluated, "token_count": tokens, "complete": evaluated == len(rows),
|
| 345 |
+
"teacher_forcing": True, "used_for_fit_or_selection": False}
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
def train(checkpoint, train_rows, tune_rows, *, epochs=20, max_seconds=60, max_optimizer_steps=None):
|
| 349 |
+
"""Continue complete batches, retaining exact Adam and partial-epoch cursor.
|
| 350 |
+
|
| 351 |
+
Formula and reconstruction losses jointly update the residual projection.
|
| 352 |
+
Tuning metrics are observational; this API does not select or promote a
|
| 353 |
+
candidate. The deadline is soft at numeric-batch and evaluation boundaries.
|
| 354 |
+
"""
|
| 355 |
+
started = time.monotonic()
|
| 356 |
+
_require(type(epochs) is int and 1 <= epochs <= 1000, "epochs must be in 1..1000")
|
| 357 |
+
_require(type(max_seconds) in (int, float) and math.isfinite(max_seconds) and 0 <= max_seconds <= 3600,
|
| 358 |
+
"bounded nonnegative deadline required")
|
| 359 |
+
_require(max_optimizer_steps is None or type(max_optimizer_steps) is int and 0 <= max_optimizer_steps <= 100000,
|
| 360 |
+
"bounded optimizer step budget required")
|
| 361 |
+
deadline = started + max_seconds
|
| 362 |
+
torch, model, optimizer = _restore(checkpoint)
|
| 363 |
+
training, tuning = _splits(train_rows, tune_rows, checkpoint["binding"]["dimension"])
|
| 364 |
+
_require(checkpoint_digest(training) == checkpoint["training_manifest_sha256"]
|
| 365 |
+
and checkpoint_digest(tuning) == checkpoint["tuning_manifest_sha256"], "resume manifests differ")
|
| 366 |
+
config, codec = checkpoint["config"], checkpoint["codec"]
|
| 367 |
+
progress = dict(checkpoint["progress"])
|
| 368 |
+
start_step, start_epoch = progress["optimizer_steps"], progress["epochs_completed"]
|
| 369 |
+
goal = start_epoch + epochs
|
| 370 |
+
before = _metrics(model, training, codec, config, deadline)
|
| 371 |
+
initial, _ = _pack(model, optimizer)
|
| 372 |
+
groups = {"projection": [parameter for name, parameter in model.named_parameters() if name.startswith("projection_")],
|
| 373 |
+
"decoder": [parameter for name, parameter in model.named_parameters() if not name.startswith("projection_")]}
|
| 374 |
+
maximum = {"projection": 0., "decoder": 0., "formula_to_projection": 0.}
|
| 375 |
+
history, stopped = [], "epoch_limit"
|
| 376 |
+
while progress["epochs_completed"] < goal:
|
| 377 |
+
if time.monotonic() >= deadline:
|
| 378 |
+
stopped = "deadline_before_batch"; break
|
| 379 |
+
if max_optimizer_steps is not None and progress["optimizer_steps"] - start_step >= max_optimizer_steps:
|
| 380 |
+
stopped = "optimizer_step_budget"; break
|
| 381 |
+
order = list(range(len(training)))
|
| 382 |
+
random.Random(config["seed"] + progress["epochs_completed"]).shuffle(order)
|
| 383 |
+
indices = order[progress["row_cursor"]:progress["row_cursor"] + config["batch_size"]]
|
| 384 |
+
batch = [training[index] for index in indices]
|
| 385 |
+
model.train()
|
| 386 |
+
optimizer.zero_grad(set_to_none=True)
|
| 387 |
+
loss, formula, mse, tokens = _loss(model, batch, codec, config)
|
| 388 |
+
_require(bool(torch.isfinite(loss)), "nonfinite joint training loss")
|
| 389 |
+
formula_gradients = torch.autograd.grad(formula, groups["projection"], retain_graph=True)
|
| 390 |
+
_require(all(bool(torch.isfinite(value).all()) for value in formula_gradients), "nonfinite formula projection gradient")
|
| 391 |
+
maximum["formula_to_projection"] = max(maximum["formula_to_projection"], _norm(formula_gradients))
|
| 392 |
+
loss.backward()
|
| 393 |
+
for name, parameters in groups.items():
|
| 394 |
+
_require(all(parameter.grad is not None and bool(torch.isfinite(parameter.grad).all()) for parameter in parameters),
|
| 395 |
+
"missing or nonfinite joint gradient")
|
| 396 |
+
maximum[name] = max(maximum[name], _norm(parameter.grad for parameter in parameters))
|
| 397 |
+
torch.nn.utils.clip_grad_norm_(list(model.parameters()), 5., error_if_nonfinite=True)
|
| 398 |
+
optimizer.step()
|
| 399 |
+
_require(all(bool(torch.isfinite(parameter).all()) for parameter in model.parameters()), "nonfinite updated weights")
|
| 400 |
+
_require(all(bool(torch.isfinite(value).all()) for item in optimizer.state.values() for value in item.values()
|
| 401 |
+
if torch.is_tensor(value)), "nonfinite updated Adam moments")
|
| 402 |
+
progress["optimizer_steps"] += 1
|
| 403 |
+
progress["row_cursor"] += len(indices)
|
| 404 |
+
if progress["row_cursor"] == len(training):
|
| 405 |
+
progress["epochs_completed"] += 1
|
| 406 |
+
progress["row_cursor"] = 0
|
| 407 |
+
history.append({"step": progress["optimizer_steps"], "token_cross_entropy": float(formula.detach()),
|
| 408 |
+
"reconstruction_mse": float(mse.detach()), "joint_loss": float(loss.detach()), "token_count": tokens})
|
| 409 |
+
after = _metrics(model, training, codec, config, deadline)
|
| 410 |
+
tuning_metrics = _metrics(model, tuning, codec, config, deadline)
|
| 411 |
+
weights, moments = _pack(model, optimizer)
|
| 412 |
+
result = copy.deepcopy(checkpoint)
|
| 413 |
+
result.update(model_state=weights, optimizer_state=moments, progress=progress,
|
| 414 |
+
parent_checkpoint_sha256=checkpoint_digest(checkpoint))
|
| 415 |
+
_require(result["implementation"] == _implementation(), "latent producer changed during training")
|
| 416 |
+
_require(len(_raw(result)) <= MAX_BYTES, "latent checkpoint exceeds byte bound")
|
| 417 |
+
selected = lambda state, prefix: {name: value for name, value in state.items()
|
| 418 |
+
if name.startswith("projection_") == (prefix == "projection")}
|
| 419 |
+
evidence = {name: {"gradient_norm_max": maximum[name],
|
| 420 |
+
"initial_parameters_sha256": checkpoint_digest(selected(initial, name)),
|
| 421 |
+
"final_parameters_sha256": checkpoint_digest(selected(weights, name)),
|
| 422 |
+
"parameter_update_l2": _norm(torch.tensor(weights[key], dtype=torch.float64) - torch.tensor(initial[key], dtype=torch.float64)
|
| 423 |
+
for key in selected(weights, name))} for name in groups}
|
| 424 |
+
report = {"schema": "modal-latent-formula-training/v1", "binding": copy.deepcopy(checkpoint["binding"]),
|
| 425 |
+
"checkpoint_sha256": checkpoint_digest(result), "parent_checkpoint_sha256": checkpoint_digest(checkpoint),
|
| 426 |
+
"projection_id": PROJECTION_ID, "training_executed": progress["optimizer_steps"] > start_step,
|
| 427 |
+
"optimizer_steps": progress["optimizer_steps"] - start_step,
|
| 428 |
+
"epochs_completed": progress["epochs_completed"] - start_epoch, "progress": dict(progress),
|
| 429 |
+
"stopped_reason": stopped, "elapsed_seconds": time.monotonic() - started,
|
| 430 |
+
"deadline_scope": "soft_before_batch; preparation_serialization_and_inflight_batch_not_interruptible",
|
| 431 |
+
"training_before": before, "training_after": after, "tuning": tuning_metrics, "batch_losses": history,
|
| 432 |
+
"parameter_evidence": evidence, "formula_projection_gradient_norm_max": maximum["formula_to_projection"],
|
| 433 |
+
"objective": "formula_token_cross_entropy_plus_projected_embedding_mse",
|
| 434 |
+
"core_sparse_weights_frozen_for_formula_gradient": True, "sample_memory_used": False,
|
| 435 |
+
"source_text_is_neural_input": False, "formula_conditioning": "learned_residual_projection_of_core_representation",
|
| 436 |
+
"heldout_canary": False, "selection_performed": False, "family_backend_syntax_checked": False,
|
| 437 |
+
"unsupported_projection_policy": "explicit_abstention", "examples_persisted": False,
|
| 438 |
+
"download_calls": 0, "provider_calls": 0, **FALSE}
|
| 439 |
+
return {"checkpoint": result, "report": report}
|
| 440 |
+
|
| 441 |
+
|
| 442 |
+
def _display(canonical_ir):
|
| 443 |
+
rule = canonical_ir["rules"][0]
|
| 444 |
+
atom = lambda value: value if re.fullmatch(r"[A-Za-z_][A-Za-z_0-9]*", value) else json.dumps(value, ensure_ascii=False)
|
| 445 |
+
text = rule["modality"] + "(" + atom(rule["action"]) + "(" + atom(rule["actor"]) + ", " + atom(rule["object"]) + "))"
|
| 446 |
+
qualifiers = {field: rule[field] for field in ("conditions", "exceptions", "temporal") if rule[field]}
|
| 447 |
+
return text + (" scope=" + json.dumps(qualifiers, sort_keys=True, ensure_ascii=False) if qualifiers else "")
|
| 448 |
+
|
| 449 |
+
|
| 450 |
+
class LatentFormulaDecoder:
|
| 451 |
+
"""Worker-private cached inference; inputs never include formula targets."""
|
| 452 |
+
def __init__(self, checkpoint, *, expected_binding=None):
|
| 453 |
+
self.torch, self.model, _ = _restore(checkpoint, expected_binding)
|
| 454 |
+
self._checkpoint = copy.deepcopy(checkpoint)
|
| 455 |
+
self._checkpoint_sha256 = checkpoint_digest(checkpoint)
|
| 456 |
+
self._codec = self._checkpoint["codec"]
|
| 457 |
+
# A version-counter-only check misses writes through tensor.data. Keep
|
| 458 |
+
# one tensor-sized reference, rather than repeatedly serializing the
|
| 459 |
+
# full JSON checkpoint (which also contains Adam and provenance).
|
| 460 |
+
self._reference_weights = {name: tensor.detach().clone()
|
| 461 |
+
for name, tensor in self.model.state_dict().items()}
|
| 462 |
+
|
| 463 |
+
@property
|
| 464 |
+
def checkpoint(self):
|
| 465 |
+
"""A diagnostic snapshot; callers cannot mutate inference metadata."""
|
| 466 |
+
return copy.deepcopy(self._checkpoint)
|
| 467 |
+
|
| 468 |
+
@property
|
| 469 |
+
def codec(self):
|
| 470 |
+
return copy.deepcopy(self._codec)
|
| 471 |
+
|
| 472 |
+
@property
|
| 473 |
+
def checkpoint_sha256(self):
|
| 474 |
+
return self._checkpoint_sha256
|
| 475 |
+
|
| 476 |
+
def _check(self):
|
| 477 |
+
_torch()
|
| 478 |
+
_require(self._checkpoint["implementation"] == _implementation(), "latent source provenance differs")
|
| 479 |
+
state = self.model.state_dict()
|
| 480 |
+
_require(set(state) == set(self._reference_weights), "cached decoder weights differ from checkpoint")
|
| 481 |
+
_require(all(tensor.shape == self._reference_weights[name].shape
|
| 482 |
+
and tensor.dtype == self._reference_weights[name].dtype
|
| 483 |
+
and tensor.device == self._reference_weights[name].device
|
| 484 |
+
and self.torch.equal(tensor, self._reference_weights[name])
|
| 485 |
+
for name, tensor in state.items()), "cached decoder weights differ from checkpoint")
|
| 486 |
+
|
| 487 |
+
def project(self, latents):
|
| 488 |
+
self._check()
|
| 489 |
+
_require(type(latents) in (list, tuple) and 1 <= len(latents) <= 128, "one to 128 vectors required")
|
| 490 |
+
for latent in latents:
|
| 491 |
+
_vector(latent, self._checkpoint["binding"]["dimension"], "latent")
|
| 492 |
+
self.model.eval()
|
| 493 |
+
with self.torch.no_grad():
|
| 494 |
+
values = self.model.project(self.torch.tensor(latents, dtype=self.torch.float32))
|
| 495 |
+
_require(bool(self.torch.isfinite(values).all()), "nonfinite learned projection")
|
| 496 |
+
result = values.tolist()
|
| 497 |
+
self._check()
|
| 498 |
+
return result
|
| 499 |
+
|
| 500 |
+
def _decode(self, row, projection_id):
|
| 501 |
+
base = {"id": row["id"], "source_sha256": hashlib.sha256(row["source_text"].encode()).hexdigest(),
|
| 502 |
+
"latent_sha256": checkpoint_digest(row["latent"]), "projection_id": projection_id,
|
| 503 |
+
"status": "abstained", "reason": None, "canonical_ir": None, "formula_text": None, "formal_outputs": [],
|
| 504 |
+
"teacher_forcing": False, "target_access": False, "training_executed": False,
|
| 505 |
+
"source_text_is_neural_input": False, "latent_input_conditioned": True, "independent_text_to_logic": False,
|
| 506 |
+
"learned_formula_generation": True, "sample_memory_used": False, "family_syntax_checked": False,
|
| 507 |
+
"temperature": 0, **FALSE}
|
| 508 |
+
if projection_id != PROJECTION_ID:
|
| 509 |
+
return {**base, "reason": "unsupported_formula_projection"}
|
| 510 |
+
if not self._checkpoint["progress"]["optimizer_steps"]:
|
| 511 |
+
return {**base, "reason": "untrained_formula_head"}
|
| 512 |
+
if not bool(self.model.output.weight.detach().any()) and not bool(self.model.output.bias.detach().any()):
|
| 513 |
+
return {**base, "reason": "zero_output_head"}
|
| 514 |
+
torch = self.torch
|
| 515 |
+
prefix, minimum_margin = [codec_module.TARGET_BOS], None
|
| 516 |
+
self.model.eval()
|
| 517 |
+
with torch.no_grad():
|
| 518 |
+
projected = self.model.project(torch.tensor([row["latent"]], dtype=torch.float32))
|
| 519 |
+
if not bool(torch.isfinite(projected).all()):
|
| 520 |
+
return {**base, "reason": "nonfinite_learned_projection"}
|
| 521 |
+
hidden = self.model.start(projected)
|
| 522 |
+
if not bool(torch.isfinite(hidden).all()):
|
| 523 |
+
return {**base, "reason": "nonfinite_decoder_condition"}
|
| 524 |
+
for _ in range(63):
|
| 525 |
+
allowed = codec_module.allowed_token_ids(self._codec, prefix)
|
| 526 |
+
if not allowed:
|
| 527 |
+
return {**base, "reason": "no_allowed_grammar_token", "generated_token_ids": prefix}
|
| 528 |
+
logits, hidden = self.model.next_logits(torch.tensor([[prefix[-1]]], dtype=torch.long), hidden)
|
| 529 |
+
scores = logits[0, -1, allowed]
|
| 530 |
+
if not bool(torch.isfinite(scores).all()):
|
| 531 |
+
return {**base, "reason": "nonfinite_decoder_scores"}
|
| 532 |
+
ranking = torch.argsort(scores, descending=True, stable=True)
|
| 533 |
+
if len(allowed) > 1:
|
| 534 |
+
margin = float(scores[ranking[0]] - scores[ranking[1]])
|
| 535 |
+
minimum_margin = margin if minimum_margin is None else min(minimum_margin, margin)
|
| 536 |
+
if margin <= 1e-7:
|
| 537 |
+
return {**base, "reason": "ambiguous_decoder_scores", "generated_token_ids": prefix}
|
| 538 |
+
prefix.append(allowed[int(ranking[0])])
|
| 539 |
+
if prefix[-1] == codec_module.TARGET_EOS:
|
| 540 |
+
try:
|
| 541 |
+
canonical_ir = codec_module.decode_target(self._codec, prefix)
|
| 542 |
+
except ValueError as error:
|
| 543 |
+
return {**base, "reason": "generated_ir_rejected", "detail": str(error), "generated_token_ids": prefix}
|
| 544 |
+
display = _display(canonical_ir)
|
| 545 |
+
output = {"family": "deontic", "format": "typed-deontic-rule/v1",
|
| 546 |
+
"payload": canonical_ir["rules"][0], "formula_text": display,
|
| 547 |
+
"formula_text_role": "display_only_full_ast_is_authoritative",
|
| 548 |
+
"syntax_scope": "canonical_rule_schema_and_decoder_grammar",
|
| 549 |
+
"origin": "learned_latent_conditioned_formula_decoder", **FALSE}
|
| 550 |
+
return {**base, "status": "decoded", "canonical_ir": canonical_ir, "formula_text": display,
|
| 551 |
+
"formal_outputs": [output], "generated_token_ids": prefix,
|
| 552 |
+
"minimum_decision_logit_margin": minimum_margin,
|
| 553 |
+
"syntax_scope": "canonical_rule_schema_and_decoder_grammar"}
|
| 554 |
+
return {**base, "reason": "generation_length_limit", "generated_token_ids": prefix}
|
| 555 |
+
|
| 556 |
+
def infer(self, rows, *, projection_id=PROJECTION_ID):
|
| 557 |
+
self._check()
|
| 558 |
+
_require(type(projection_id) is str and 0 < len(projection_id) <= 256, "bounded projection id required")
|
| 559 |
+
_require(type(rows) in (list, tuple) and 1 <= len(rows) <= 128, "one to 128 inference rows required")
|
| 560 |
+
validated = _rows(rows, self._checkpoint["binding"]["dimension"], training=False)
|
| 561 |
+
results = [self._decode(row, projection_id) for row in validated]
|
| 562 |
+
self._check()
|
| 563 |
+
count = sum(row["status"] == "decoded" for row in results)
|
| 564 |
+
return {"schema": "modal-latent-formula-inference/v1", "binding": copy.deepcopy(self._checkpoint["binding"]),
|
| 565 |
+
"checkpoint_sha256": self.checkpoint_sha256, "rows": results, "decoded_count": count,
|
| 566 |
+
"status": "decoded" if count == len(rows) else "partial" if count else "abstained",
|
| 567 |
+
"decoded_formulas_generated": count > 0, "training_executed": False,
|
| 568 |
+
"source_text_is_neural_input": False, "latent_input_conditioned": True,
|
| 569 |
+
"teacher_forcing": False, "target_access": False, "learned_formula_generation": True,
|
| 570 |
+
"independent_text_to_logic": False, "sample_memory_used": False, **FALSE}
|
| 571 |
+
|
| 572 |
+
|
| 573 |
+
def infer(checkpoint, rows, *, expected_binding=None, projection_id=PROJECTION_ID):
|
| 574 |
+
return LatentFormulaDecoder(checkpoint, expected_binding=expected_binding).infer(rows, projection_id=projection_id)
|
| 575 |
+
|
| 576 |
+
|
| 577 |
+
def project(checkpoint, latents, *, expected_binding=None):
|
| 578 |
+
return LatentFormulaDecoder(checkpoint, expected_binding=expected_binding).project(latents)
|
| 579 |
+
|
| 580 |
+
|
| 581 |
+
def save_checkpoint(checkpoint, path):
|
| 582 |
+
validate_checkpoint(checkpoint)
|
| 583 |
+
data = _raw(checkpoint)
|
| 584 |
+
destination = Path(path)
|
| 585 |
+
with destination.open("xb") as handle:
|
| 586 |
+
handle.write(data)
|
| 587 |
+
return {"path": str(destination), "sha256": hashlib.sha256(data).hexdigest(), "size_bytes": len(data), **FALSE}
|
| 588 |
+
|
| 589 |
+
|
| 590 |
+
def load_checkpoint(path, *, expected_sha256, expected_binding=None):
|
| 591 |
+
_require(type(expected_sha256) is str and _SHA.fullmatch(expected_sha256), "expected checkpoint SHA256 required")
|
| 592 |
+
source = Path(path)
|
| 593 |
+
_require(not source.is_symlink(), "checkpoint symlink is forbidden")
|
| 594 |
+
metadata = source.stat()
|
| 595 |
+
_require(stat.S_ISREG(metadata.st_mode) and metadata.st_size <= MAX_BYTES, "bounded regular checkpoint file required")
|
| 596 |
+
data = source.read_bytes()
|
| 597 |
+
_require(len(data) <= MAX_BYTES and hashlib.sha256(data).hexdigest() == expected_sha256, "checkpoint hash differs")
|
| 598 |
+
def pairs(items):
|
| 599 |
+
result = {}
|
| 600 |
+
for key, value in items:
|
| 601 |
+
_require(key not in result, "duplicate JSON keys are forbidden")
|
| 602 |
+
result[key] = value
|
| 603 |
+
return result
|
| 604 |
+
result = json.loads(data, object_pairs_hook=pairs)
|
| 605 |
+
_require(_raw(result) == data, "checkpoint requires canonical finite JSON")
|
| 606 |
+
validate_checkpoint(result, expected_binding=expected_binding)
|
| 607 |
+
return result
|
| 608 |
+
|
| 609 |
+
|
| 610 |
+
__all__ = ["SCHEMA", "ARCHITECTURE", "PROJECTION_ID", "FALSE", "build_checkpoint", "train", "infer", "project",
|
| 611 |
+
"LatentFormulaDecoder", "checkpoint_digest", "validate_checkpoint", "save_checkpoint", "load_checkpoint"]
|
releases/20261004-retained-checkpoints-v1/source/f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91/ipfs_datasets_py/logic/software_verification/program.py
ADDED
|
@@ -0,0 +1,1430 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Language-neutral program and control-flow semantics.
|
| 2 |
+
|
| 3 |
+
The records in this module describe source programs; they do not execute a
|
| 4 |
+
program and they do not encode a particular solver language. ``ProgramIR``
|
| 5 |
+
performs closed-world validation of symbols, expression dependencies, command
|
| 6 |
+
evaluation order, function scopes, and control-flow graphs. Consequently a
|
| 7 |
+
frontend cannot silently leave a name unresolved or construct a partial CFG.
|
| 8 |
+
"""
|
| 9 |
+
|
| 10 |
+
from __future__ import annotations
|
| 11 |
+
|
| 12 |
+
import re
|
| 13 |
+
from collections import defaultdict, deque
|
| 14 |
+
from collections.abc import Mapping, Sequence
|
| 15 |
+
from dataclasses import dataclass, field
|
| 16 |
+
from enum import Enum
|
| 17 |
+
from typing import Any, Final
|
| 18 |
+
|
| 19 |
+
from ipfs_datasets_py.logic.ir_core.canonical import canonical_json_bytes
|
| 20 |
+
from ipfs_datasets_py.logic.ir_core.claims import FrozenMap
|
| 21 |
+
from ipfs_datasets_py.logic.ir_core.identity import CanonicalIdentity, canonical_identity
|
| 22 |
+
from ipfs_datasets_py.logic.ir_core.provenance import SourceRef, SourceSpan
|
| 23 |
+
|
| 24 |
+
PROGRAM_IR_SCHEMA_VERSION: Final = "program-ir/v1"
|
| 25 |
+
PROGRAM_IR_IDENTITY_DOMAIN: Final = "logic.software-verification.program"
|
| 26 |
+
|
| 27 |
+
_ID_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:/-]{0,255}$")
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
class ProgramValidationError(ValueError):
|
| 31 |
+
"""Raised when program semantics are incomplete or inconsistent."""
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class SymbolKind(str, Enum):
|
| 35 |
+
GLOBAL = "global"
|
| 36 |
+
PARAMETER = "parameter"
|
| 37 |
+
LOCAL = "local"
|
| 38 |
+
RESULT = "result"
|
| 39 |
+
EXCEPTION = "exception"
|
| 40 |
+
FUNCTION = "function"
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
class ExpressionKind(str, Enum):
|
| 44 |
+
LITERAL = "literal"
|
| 45 |
+
SYMBOL = "symbol"
|
| 46 |
+
UNARY = "unary"
|
| 47 |
+
BINARY = "binary"
|
| 48 |
+
CONDITIONAL = "conditional"
|
| 49 |
+
CALL = "call"
|
| 50 |
+
FIELD = "field"
|
| 51 |
+
INDEX = "index"
|
| 52 |
+
QUANTIFIED = "quantified"
|
| 53 |
+
OLD = "old"
|
| 54 |
+
RESULT = "result"
|
| 55 |
+
UNDEFINED = "undefined"
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
class CommandKind(str, Enum):
|
| 59 |
+
SKIP = "skip"
|
| 60 |
+
ASSIGN = "assign"
|
| 61 |
+
ASSUME = "assume"
|
| 62 |
+
ASSERT = "assert"
|
| 63 |
+
CALL = "call"
|
| 64 |
+
RETURN = "return"
|
| 65 |
+
THROW = "throw"
|
| 66 |
+
HAVOC = "havoc"
|
| 67 |
+
ALLOCATE = "allocate"
|
| 68 |
+
DEALLOCATE = "deallocate"
|
| 69 |
+
ATOMIC = "atomic"
|
| 70 |
+
UNDEFINED = "undefined"
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
class EdgeKind(str, Enum):
|
| 74 |
+
NORMAL = "normal"
|
| 75 |
+
TRUE = "true"
|
| 76 |
+
FALSE = "false"
|
| 77 |
+
EXCEPTION = "exception"
|
| 78 |
+
RETURN = "return"
|
| 79 |
+
BREAK = "break"
|
| 80 |
+
CONTINUE = "continue"
|
| 81 |
+
|
| 82 |
+
|
| 83 |
+
class Purity(str, Enum):
|
| 84 |
+
"""Explicit source-level purity classification.
|
| 85 |
+
|
| 86 |
+
``UNKNOWN`` is intentionally distinct from ``IMPURE``. Downstream tools
|
| 87 |
+
must not promote an unknown declaration to a pure one.
|
| 88 |
+
"""
|
| 89 |
+
|
| 90 |
+
PURE = "pure"
|
| 91 |
+
READ_ONLY = "read_only"
|
| 92 |
+
IMPURE = "impure"
|
| 93 |
+
UNKNOWN = "unknown"
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
class UndefinedBehaviorConsequence(str, Enum):
|
| 97 |
+
TRAP = "trap"
|
| 98 |
+
NONDETERMINISTIC = "nondeterministic"
|
| 99 |
+
UNCONSTRAINED = "unconstrained"
|
| 100 |
+
LANGUAGE_DEFINED = "language_defined"
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
def _text(value: object, label: str) -> str:
|
| 104 |
+
if not isinstance(value, str) or not value or value.strip() != value:
|
| 105 |
+
raise ProgramValidationError(
|
| 106 |
+
f"{label} must be a non-empty string without surrounding whitespace"
|
| 107 |
+
)
|
| 108 |
+
if "\x00" in value:
|
| 109 |
+
raise ProgramValidationError(f"{label} must not contain NUL bytes")
|
| 110 |
+
return value
|
| 111 |
+
|
| 112 |
+
|
| 113 |
+
def _optional_text(value: object, label: str) -> str:
|
| 114 |
+
if value == "":
|
| 115 |
+
return ""
|
| 116 |
+
return _text(value, label)
|
| 117 |
+
|
| 118 |
+
|
| 119 |
+
def _identifier(value: object, label: str) -> str:
|
| 120 |
+
result = _text(value, label)
|
| 121 |
+
if not _ID_RE.fullmatch(result):
|
| 122 |
+
raise ProgramValidationError(f"{label} must be a stable identifier")
|
| 123 |
+
return result
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
def _ids(
|
| 127 |
+
values: Sequence[str],
|
| 128 |
+
label: str,
|
| 129 |
+
*,
|
| 130 |
+
preserve_order: bool = False,
|
| 131 |
+
) -> tuple[str, ...]:
|
| 132 |
+
if isinstance(values, (str, bytes, bytearray)) or not isinstance(values, Sequence):
|
| 133 |
+
raise ProgramValidationError(f"{label} must be a sequence of identifiers")
|
| 134 |
+
result = tuple(_identifier(item, f"{label} item") for item in values)
|
| 135 |
+
if len(result) != len(set(result)):
|
| 136 |
+
raise ProgramValidationError(f"{label} must not contain duplicates")
|
| 137 |
+
return result if preserve_order else tuple(sorted(result))
|
| 138 |
+
|
| 139 |
+
|
| 140 |
+
def _source_map(
|
| 141 |
+
source_ref_ids: Sequence[str],
|
| 142 |
+
span_ids: Sequence[str],
|
| 143 |
+
owner: str,
|
| 144 |
+
) -> tuple[tuple[str, ...], tuple[str, ...]]:
|
| 145 |
+
sources = _ids(source_ref_ids, f"{owner}.source_ref_ids")
|
| 146 |
+
spans = _ids(span_ids, f"{owner}.span_ids")
|
| 147 |
+
if not sources and not spans:
|
| 148 |
+
raise ProgramValidationError(
|
| 149 |
+
f"{owner} must be source mapped with source_ref_ids or span_ids"
|
| 150 |
+
)
|
| 151 |
+
return sources, spans
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
def _enum(value: object, enum_type: type[Enum], label: str) -> Any:
|
| 155 |
+
try:
|
| 156 |
+
return value if isinstance(value, enum_type) else enum_type(value)
|
| 157 |
+
except (TypeError, ValueError) as error:
|
| 158 |
+
choices = ", ".join(item.value for item in enum_type)
|
| 159 |
+
raise ProgramValidationError(f"{label} must be one of {choices}") from error
|
| 160 |
+
|
| 161 |
+
|
| 162 |
+
def _mapping(value: object, label: str) -> Mapping[str, Any]:
|
| 163 |
+
if not isinstance(value, Mapping):
|
| 164 |
+
raise ProgramValidationError(f"{label} must be a mapping")
|
| 165 |
+
return value
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def _frozen(value: Mapping[str, Any] | FrozenMap, label: str) -> FrozenMap:
|
| 169 |
+
try:
|
| 170 |
+
return value if isinstance(value, FrozenMap) else FrozenMap(value)
|
| 171 |
+
except (TypeError, ValueError) as error:
|
| 172 |
+
raise ProgramValidationError(
|
| 173 |
+
f"{label} must contain JSON-compatible data: {error}"
|
| 174 |
+
) from error
|
| 175 |
+
|
| 176 |
+
|
| 177 |
+
def _known(values: Sequence[str], known: set[str], label: str) -> None:
|
| 178 |
+
missing = sorted(set(values) - known)
|
| 179 |
+
if missing:
|
| 180 |
+
raise ProgramValidationError(f"{label} references unknown ids {missing}")
|
| 181 |
+
|
| 182 |
+
|
| 183 |
+
@dataclass(frozen=True, slots=True)
|
| 184 |
+
class ProgramSymbol:
|
| 185 |
+
symbol_id: str
|
| 186 |
+
name: str
|
| 187 |
+
type_ref: str
|
| 188 |
+
kind: SymbolKind | str
|
| 189 |
+
source_ref_ids: tuple[str, ...] = ()
|
| 190 |
+
span_ids: tuple[str, ...] = ()
|
| 191 |
+
attributes: FrozenMap = field(default_factory=FrozenMap)
|
| 192 |
+
|
| 193 |
+
def __post_init__(self) -> None:
|
| 194 |
+
sources, spans = _source_map(self.source_ref_ids, self.span_ids, "ProgramSymbol")
|
| 195 |
+
object.__setattr__(self, "symbol_id", _identifier(self.symbol_id, "symbol_id"))
|
| 196 |
+
object.__setattr__(self, "name", _text(self.name, "name"))
|
| 197 |
+
object.__setattr__(self, "type_ref", _text(self.type_ref, "type_ref"))
|
| 198 |
+
object.__setattr__(self, "kind", _enum(self.kind, SymbolKind, "kind"))
|
| 199 |
+
object.__setattr__(self, "source_ref_ids", sources)
|
| 200 |
+
object.__setattr__(self, "span_ids", spans)
|
| 201 |
+
object.__setattr__(self, "attributes", _frozen(self.attributes, "attributes"))
|
| 202 |
+
|
| 203 |
+
def to_dict(self) -> dict[str, Any]:
|
| 204 |
+
return {
|
| 205 |
+
"attributes": self.attributes.to_dict(),
|
| 206 |
+
"kind": self.kind.value,
|
| 207 |
+
"name": self.name,
|
| 208 |
+
"source_ref_ids": list(self.source_ref_ids),
|
| 209 |
+
"span_ids": list(self.span_ids),
|
| 210 |
+
"symbol_id": self.symbol_id,
|
| 211 |
+
"type_ref": self.type_ref,
|
| 212 |
+
}
|
| 213 |
+
|
| 214 |
+
@classmethod
|
| 215 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "ProgramSymbol":
|
| 216 |
+
return cls(
|
| 217 |
+
symbol_id=value.get("symbol_id", ""),
|
| 218 |
+
name=value.get("name", ""),
|
| 219 |
+
type_ref=value.get("type_ref", ""),
|
| 220 |
+
kind=value.get("kind", ""),
|
| 221 |
+
source_ref_ids=tuple(value.get("source_ref_ids", ())),
|
| 222 |
+
span_ids=tuple(value.get("span_ids", ())),
|
| 223 |
+
attributes=_frozen(_mapping(value.get("attributes", {}), "attributes"), "attributes"),
|
| 224 |
+
)
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
@dataclass(frozen=True, slots=True)
|
| 228 |
+
class ProgramExpression:
|
| 229 |
+
"""One typed expression with explicit operand evaluation order."""
|
| 230 |
+
|
| 231 |
+
expression_id: str
|
| 232 |
+
kind: ExpressionKind | str
|
| 233 |
+
type_ref: str
|
| 234 |
+
operand_ids: tuple[str, ...] = ()
|
| 235 |
+
evaluation_order: tuple[str, ...] = ()
|
| 236 |
+
symbol_ids: tuple[str, ...] = ()
|
| 237 |
+
operator: str = ""
|
| 238 |
+
attributes: FrozenMap = field(default_factory=FrozenMap)
|
| 239 |
+
source_ref_ids: tuple[str, ...] = ()
|
| 240 |
+
span_ids: tuple[str, ...] = ()
|
| 241 |
+
|
| 242 |
+
def __post_init__(self) -> None:
|
| 243 |
+
sources, spans = _source_map(self.source_ref_ids, self.span_ids, "ProgramExpression")
|
| 244 |
+
operands = _ids(self.operand_ids, "operand_ids", preserve_order=True)
|
| 245 |
+
order = _ids(
|
| 246 |
+
self.evaluation_order or operands,
|
| 247 |
+
"evaluation_order",
|
| 248 |
+
preserve_order=True,
|
| 249 |
+
)
|
| 250 |
+
if len(order) != len(operands) or set(order) != set(operands):
|
| 251 |
+
raise ProgramValidationError(
|
| 252 |
+
"evaluation_order must contain every operand_id exactly once"
|
| 253 |
+
)
|
| 254 |
+
kind = _enum(self.kind, ExpressionKind, "kind")
|
| 255 |
+
symbols = _ids(self.symbol_ids, "symbol_ids")
|
| 256 |
+
if kind in {ExpressionKind.SYMBOL, ExpressionKind.RESULT} and len(symbols) != 1:
|
| 257 |
+
raise ProgramValidationError(
|
| 258 |
+
f"{kind.value} expressions must reference exactly one symbol"
|
| 259 |
+
)
|
| 260 |
+
if kind is ExpressionKind.LITERAL and (operands or symbols):
|
| 261 |
+
raise ProgramValidationError("literal expressions cannot reference operands or symbols")
|
| 262 |
+
if (
|
| 263 |
+
kind
|
| 264 |
+
in {
|
| 265 |
+
ExpressionKind.UNARY,
|
| 266 |
+
ExpressionKind.FIELD,
|
| 267 |
+
ExpressionKind.OLD,
|
| 268 |
+
}
|
| 269 |
+
and len(operands) != 1
|
| 270 |
+
):
|
| 271 |
+
raise ProgramValidationError(f"{kind.value} expressions require exactly one operand")
|
| 272 |
+
if kind is ExpressionKind.BINARY and len(operands) != 2:
|
| 273 |
+
raise ProgramValidationError("binary expressions require exactly two operands")
|
| 274 |
+
if kind is ExpressionKind.CONDITIONAL and len(operands) != 3:
|
| 275 |
+
raise ProgramValidationError(
|
| 276 |
+
"conditional expressions require condition, then, and else operands"
|
| 277 |
+
)
|
| 278 |
+
if (
|
| 279 |
+
kind
|
| 280 |
+
in {
|
| 281 |
+
ExpressionKind.UNARY,
|
| 282 |
+
ExpressionKind.BINARY,
|
| 283 |
+
ExpressionKind.FIELD,
|
| 284 |
+
ExpressionKind.INDEX,
|
| 285 |
+
ExpressionKind.QUANTIFIED,
|
| 286 |
+
}
|
| 287 |
+
and not self.operator
|
| 288 |
+
):
|
| 289 |
+
raise ProgramValidationError(f"{kind.value} expressions require operator")
|
| 290 |
+
object.__setattr__(self, "expression_id", _identifier(self.expression_id, "expression_id"))
|
| 291 |
+
object.__setattr__(self, "kind", kind)
|
| 292 |
+
object.__setattr__(self, "type_ref", _text(self.type_ref, "type_ref"))
|
| 293 |
+
object.__setattr__(self, "operand_ids", operands)
|
| 294 |
+
object.__setattr__(self, "evaluation_order", order)
|
| 295 |
+
object.__setattr__(self, "symbol_ids", symbols)
|
| 296 |
+
object.__setattr__(self, "operator", _optional_text(self.operator, "operator"))
|
| 297 |
+
object.__setattr__(self, "attributes", _frozen(self.attributes, "attributes"))
|
| 298 |
+
object.__setattr__(self, "source_ref_ids", sources)
|
| 299 |
+
object.__setattr__(self, "span_ids", spans)
|
| 300 |
+
|
| 301 |
+
def to_dict(self) -> dict[str, Any]:
|
| 302 |
+
return {
|
| 303 |
+
"attributes": self.attributes.to_dict(),
|
| 304 |
+
"evaluation_order": list(self.evaluation_order),
|
| 305 |
+
"expression_id": self.expression_id,
|
| 306 |
+
"kind": self.kind.value,
|
| 307 |
+
"operand_ids": list(self.operand_ids),
|
| 308 |
+
"operator": self.operator,
|
| 309 |
+
"source_ref_ids": list(self.source_ref_ids),
|
| 310 |
+
"span_ids": list(self.span_ids),
|
| 311 |
+
"symbol_ids": list(self.symbol_ids),
|
| 312 |
+
"type_ref": self.type_ref,
|
| 313 |
+
}
|
| 314 |
+
|
| 315 |
+
@classmethod
|
| 316 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "ProgramExpression":
|
| 317 |
+
return cls(
|
| 318 |
+
expression_id=value.get("expression_id", ""),
|
| 319 |
+
kind=value.get("kind", ""),
|
| 320 |
+
type_ref=value.get("type_ref", ""),
|
| 321 |
+
operand_ids=tuple(value.get("operand_ids", ())),
|
| 322 |
+
evaluation_order=tuple(value.get("evaluation_order", ())),
|
| 323 |
+
symbol_ids=tuple(value.get("symbol_ids", ())),
|
| 324 |
+
operator=value.get("operator", ""),
|
| 325 |
+
attributes=_frozen(_mapping(value.get("attributes", {}), "attributes"), "attributes"),
|
| 326 |
+
source_ref_ids=tuple(value.get("source_ref_ids", ())),
|
| 327 |
+
span_ids=tuple(value.get("span_ids", ())),
|
| 328 |
+
)
|
| 329 |
+
|
| 330 |
+
|
| 331 |
+
@dataclass(frozen=True, slots=True)
|
| 332 |
+
class EffectSummary:
|
| 333 |
+
"""Explicit read/write/resource and observable effects."""
|
| 334 |
+
|
| 335 |
+
reads: tuple[str, ...] = ()
|
| 336 |
+
writes: tuple[str, ...] = ()
|
| 337 |
+
allocates: tuple[str, ...] = ()
|
| 338 |
+
deallocates: tuple[str, ...] = ()
|
| 339 |
+
raises: tuple[str, ...] = ()
|
| 340 |
+
performs_io: bool = False
|
| 341 |
+
nondeterministic: bool = False
|
| 342 |
+
synchronizes: bool = False
|
| 343 |
+
|
| 344 |
+
def __post_init__(self) -> None:
|
| 345 |
+
for name in ("reads", "writes", "allocates", "deallocates"):
|
| 346 |
+
object.__setattr__(self, name, _ids(getattr(self, name), name))
|
| 347 |
+
object.__setattr__(
|
| 348 |
+
self,
|
| 349 |
+
"raises",
|
| 350 |
+
tuple(sorted(_text(item, "raises item") for item in self.raises)),
|
| 351 |
+
)
|
| 352 |
+
if len(self.raises) != len(set(self.raises)):
|
| 353 |
+
raise ProgramValidationError("raises must not contain duplicates")
|
| 354 |
+
for name in ("performs_io", "nondeterministic", "synchronizes"):
|
| 355 |
+
if not isinstance(getattr(self, name), bool):
|
| 356 |
+
raise ProgramValidationError(f"{name} must be boolean")
|
| 357 |
+
|
| 358 |
+
@property
|
| 359 |
+
def is_pure(self) -> bool:
|
| 360 |
+
return not (
|
| 361 |
+
self.writes
|
| 362 |
+
or self.allocates
|
| 363 |
+
or self.deallocates
|
| 364 |
+
or self.raises
|
| 365 |
+
or self.performs_io
|
| 366 |
+
or self.nondeterministic
|
| 367 |
+
or self.synchronizes
|
| 368 |
+
)
|
| 369 |
+
|
| 370 |
+
@property
|
| 371 |
+
def is_read_only(self) -> bool:
|
| 372 |
+
return not (
|
| 373 |
+
self.writes
|
| 374 |
+
or self.allocates
|
| 375 |
+
or self.deallocates
|
| 376 |
+
or self.performs_io
|
| 377 |
+
or self.synchronizes
|
| 378 |
+
)
|
| 379 |
+
|
| 380 |
+
def symbol_ids(self) -> tuple[str, ...]:
|
| 381 |
+
return tuple(sorted(set(self.reads + self.writes + self.allocates + self.deallocates)))
|
| 382 |
+
|
| 383 |
+
def is_subset_of(self, other: "EffectSummary") -> bool:
|
| 384 |
+
return (
|
| 385 |
+
set(self.reads) <= set(other.reads)
|
| 386 |
+
and set(self.writes) <= set(other.writes)
|
| 387 |
+
and set(self.allocates) <= set(other.allocates)
|
| 388 |
+
and set(self.deallocates) <= set(other.deallocates)
|
| 389 |
+
and set(self.raises) <= set(other.raises)
|
| 390 |
+
and (not self.performs_io or other.performs_io)
|
| 391 |
+
and (not self.nondeterministic or other.nondeterministic)
|
| 392 |
+
and (not self.synchronizes or other.synchronizes)
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
def to_dict(self) -> dict[str, Any]:
|
| 396 |
+
return {
|
| 397 |
+
"allocates": list(self.allocates),
|
| 398 |
+
"deallocates": list(self.deallocates),
|
| 399 |
+
"nondeterministic": self.nondeterministic,
|
| 400 |
+
"performs_io": self.performs_io,
|
| 401 |
+
"raises": list(self.raises),
|
| 402 |
+
"reads": list(self.reads),
|
| 403 |
+
"synchronizes": self.synchronizes,
|
| 404 |
+
"writes": list(self.writes),
|
| 405 |
+
}
|
| 406 |
+
|
| 407 |
+
@classmethod
|
| 408 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "EffectSummary":
|
| 409 |
+
return cls(
|
| 410 |
+
reads=tuple(value.get("reads", ())),
|
| 411 |
+
writes=tuple(value.get("writes", ())),
|
| 412 |
+
allocates=tuple(value.get("allocates", ())),
|
| 413 |
+
deallocates=tuple(value.get("deallocates", ())),
|
| 414 |
+
raises=tuple(value.get("raises", ())),
|
| 415 |
+
performs_io=value.get("performs_io", False),
|
| 416 |
+
nondeterministic=value.get("nondeterministic", False),
|
| 417 |
+
synchronizes=value.get("synchronizes", False),
|
| 418 |
+
)
|
| 419 |
+
|
| 420 |
+
|
| 421 |
+
@dataclass(frozen=True, slots=True)
|
| 422 |
+
class UndefinedBehaviorCondition:
|
| 423 |
+
condition_id: str
|
| 424 |
+
expression_id: str
|
| 425 |
+
description: str
|
| 426 |
+
consequence: UndefinedBehaviorConsequence | str
|
| 427 |
+
source_ref_ids: tuple[str, ...] = ()
|
| 428 |
+
span_ids: tuple[str, ...] = ()
|
| 429 |
+
|
| 430 |
+
def __post_init__(self) -> None:
|
| 431 |
+
sources, spans = _source_map(
|
| 432 |
+
self.source_ref_ids, self.span_ids, "UndefinedBehaviorCondition"
|
| 433 |
+
)
|
| 434 |
+
object.__setattr__(self, "condition_id", _identifier(self.condition_id, "condition_id"))
|
| 435 |
+
object.__setattr__(self, "expression_id", _identifier(self.expression_id, "expression_id"))
|
| 436 |
+
object.__setattr__(self, "description", _text(self.description, "description"))
|
| 437 |
+
object.__setattr__(
|
| 438 |
+
self,
|
| 439 |
+
"consequence",
|
| 440 |
+
_enum(self.consequence, UndefinedBehaviorConsequence, "consequence"),
|
| 441 |
+
)
|
| 442 |
+
object.__setattr__(self, "source_ref_ids", sources)
|
| 443 |
+
object.__setattr__(self, "span_ids", spans)
|
| 444 |
+
|
| 445 |
+
def to_dict(self) -> dict[str, Any]:
|
| 446 |
+
return {
|
| 447 |
+
"condition_id": self.condition_id,
|
| 448 |
+
"consequence": self.consequence.value,
|
| 449 |
+
"description": self.description,
|
| 450 |
+
"expression_id": self.expression_id,
|
| 451 |
+
"source_ref_ids": list(self.source_ref_ids),
|
| 452 |
+
"span_ids": list(self.span_ids),
|
| 453 |
+
}
|
| 454 |
+
|
| 455 |
+
@classmethod
|
| 456 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "UndefinedBehaviorCondition":
|
| 457 |
+
return cls(
|
| 458 |
+
condition_id=value.get("condition_id", ""),
|
| 459 |
+
expression_id=value.get("expression_id", ""),
|
| 460 |
+
description=value.get("description", ""),
|
| 461 |
+
consequence=value.get("consequence", ""),
|
| 462 |
+
source_ref_ids=tuple(value.get("source_ref_ids", ())),
|
| 463 |
+
span_ids=tuple(value.get("span_ids", ())),
|
| 464 |
+
)
|
| 465 |
+
|
| 466 |
+
|
| 467 |
+
@dataclass(frozen=True, slots=True)
|
| 468 |
+
class ProgramCommand:
|
| 469 |
+
"""One atomic command; block order supplies sequential composition."""
|
| 470 |
+
|
| 471 |
+
command_id: str
|
| 472 |
+
kind: CommandKind | str
|
| 473 |
+
expression_ids: tuple[str, ...] = ()
|
| 474 |
+
evaluation_order: tuple[str, ...] = ()
|
| 475 |
+
target_symbol_ids: tuple[str, ...] = ()
|
| 476 |
+
effects: EffectSummary = field(default_factory=EffectSummary)
|
| 477 |
+
undefined_behavior: tuple[UndefinedBehaviorCondition, ...] = ()
|
| 478 |
+
source_ref_ids: tuple[str, ...] = ()
|
| 479 |
+
span_ids: tuple[str, ...] = ()
|
| 480 |
+
attributes: FrozenMap = field(default_factory=FrozenMap)
|
| 481 |
+
|
| 482 |
+
def __post_init__(self) -> None:
|
| 483 |
+
sources, spans = _source_map(self.source_ref_ids, self.span_ids, "ProgramCommand")
|
| 484 |
+
expressions = _ids(self.expression_ids, "expression_ids", preserve_order=True)
|
| 485 |
+
order = _ids(
|
| 486 |
+
self.evaluation_order or expressions,
|
| 487 |
+
"evaluation_order",
|
| 488 |
+
preserve_order=True,
|
| 489 |
+
)
|
| 490 |
+
if len(order) != len(expressions) or set(order) != set(expressions):
|
| 491 |
+
raise ProgramValidationError(
|
| 492 |
+
"command evaluation_order must contain every expression_id exactly once"
|
| 493 |
+
)
|
| 494 |
+
kind = _enum(self.kind, CommandKind, "kind")
|
| 495 |
+
targets = _ids(self.target_symbol_ids, "target_symbol_ids")
|
| 496 |
+
effects = (
|
| 497 |
+
self.effects
|
| 498 |
+
if isinstance(self.effects, EffectSummary)
|
| 499 |
+
else EffectSummary.from_dict(_mapping(self.effects, "effects"))
|
| 500 |
+
)
|
| 501 |
+
undefined = tuple(
|
| 502 |
+
item
|
| 503 |
+
if isinstance(item, UndefinedBehaviorCondition)
|
| 504 |
+
else UndefinedBehaviorCondition.from_dict(_mapping(item, "undefined_behavior item"))
|
| 505 |
+
for item in self.undefined_behavior
|
| 506 |
+
)
|
| 507 |
+
if kind is CommandKind.ASSIGN and not targets:
|
| 508 |
+
raise ProgramValidationError("assign commands require target_symbol_ids")
|
| 509 |
+
if kind in {CommandKind.ASSUME, CommandKind.ASSERT} and len(expressions) != 1:
|
| 510 |
+
raise ProgramValidationError(f"{kind.value} commands require exactly one expression")
|
| 511 |
+
if kind is CommandKind.THROW and not effects.raises:
|
| 512 |
+
raise ProgramValidationError("throw commands require an explicit raised type")
|
| 513 |
+
if kind is CommandKind.UNDEFINED and not undefined:
|
| 514 |
+
raise ProgramValidationError(
|
| 515 |
+
"undefined commands require an explicit undefined_behavior condition"
|
| 516 |
+
)
|
| 517 |
+
ids = [item.condition_id for item in undefined]
|
| 518 |
+
if len(ids) != len(set(ids)):
|
| 519 |
+
raise ProgramValidationError("duplicate undefined behavior condition ids")
|
| 520 |
+
object.__setattr__(self, "command_id", _identifier(self.command_id, "command_id"))
|
| 521 |
+
object.__setattr__(self, "kind", kind)
|
| 522 |
+
object.__setattr__(self, "expression_ids", expressions)
|
| 523 |
+
object.__setattr__(self, "evaluation_order", order)
|
| 524 |
+
object.__setattr__(self, "target_symbol_ids", targets)
|
| 525 |
+
object.__setattr__(self, "effects", effects)
|
| 526 |
+
object.__setattr__(self, "undefined_behavior", undefined)
|
| 527 |
+
object.__setattr__(self, "source_ref_ids", sources)
|
| 528 |
+
object.__setattr__(self, "span_ids", spans)
|
| 529 |
+
object.__setattr__(self, "attributes", _frozen(self.attributes, "attributes"))
|
| 530 |
+
|
| 531 |
+
def to_dict(self) -> dict[str, Any]:
|
| 532 |
+
return {
|
| 533 |
+
"attributes": self.attributes.to_dict(),
|
| 534 |
+
"command_id": self.command_id,
|
| 535 |
+
"effects": self.effects.to_dict(),
|
| 536 |
+
"evaluation_order": list(self.evaluation_order),
|
| 537 |
+
"expression_ids": list(self.expression_ids),
|
| 538 |
+
"kind": self.kind.value,
|
| 539 |
+
"source_ref_ids": list(self.source_ref_ids),
|
| 540 |
+
"span_ids": list(self.span_ids),
|
| 541 |
+
"target_symbol_ids": list(self.target_symbol_ids),
|
| 542 |
+
"undefined_behavior": [item.to_dict() for item in self.undefined_behavior],
|
| 543 |
+
}
|
| 544 |
+
|
| 545 |
+
@classmethod
|
| 546 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "ProgramCommand":
|
| 547 |
+
return cls(
|
| 548 |
+
command_id=value.get("command_id", ""),
|
| 549 |
+
kind=value.get("kind", ""),
|
| 550 |
+
expression_ids=tuple(value.get("expression_ids", ())),
|
| 551 |
+
evaluation_order=tuple(value.get("evaluation_order", ())),
|
| 552 |
+
target_symbol_ids=tuple(value.get("target_symbol_ids", ())),
|
| 553 |
+
effects=EffectSummary.from_dict(_mapping(value.get("effects", {}), "effects")),
|
| 554 |
+
undefined_behavior=tuple(
|
| 555 |
+
UndefinedBehaviorCondition.from_dict(_mapping(item, "undefined_behavior item"))
|
| 556 |
+
for item in value.get("undefined_behavior", ())
|
| 557 |
+
),
|
| 558 |
+
source_ref_ids=tuple(value.get("source_ref_ids", ())),
|
| 559 |
+
span_ids=tuple(value.get("span_ids", ())),
|
| 560 |
+
attributes=_frozen(_mapping(value.get("attributes", {}), "attributes"), "attributes"),
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
|
| 564 |
+
@dataclass(frozen=True, slots=True)
|
| 565 |
+
class BasicBlock:
|
| 566 |
+
block_id: str
|
| 567 |
+
command_ids: tuple[str, ...] = ()
|
| 568 |
+
source_ref_ids: tuple[str, ...] = ()
|
| 569 |
+
span_ids: tuple[str, ...] = ()
|
| 570 |
+
|
| 571 |
+
def __post_init__(self) -> None:
|
| 572 |
+
sources, spans = _source_map(self.source_ref_ids, self.span_ids, "BasicBlock")
|
| 573 |
+
object.__setattr__(self, "block_id", _identifier(self.block_id, "block_id"))
|
| 574 |
+
object.__setattr__(
|
| 575 |
+
self,
|
| 576 |
+
"command_ids",
|
| 577 |
+
_ids(self.command_ids, "command_ids", preserve_order=True),
|
| 578 |
+
)
|
| 579 |
+
object.__setattr__(self, "source_ref_ids", sources)
|
| 580 |
+
object.__setattr__(self, "span_ids", spans)
|
| 581 |
+
|
| 582 |
+
def to_dict(self) -> dict[str, Any]:
|
| 583 |
+
return {
|
| 584 |
+
"block_id": self.block_id,
|
| 585 |
+
"command_ids": list(self.command_ids),
|
| 586 |
+
"source_ref_ids": list(self.source_ref_ids),
|
| 587 |
+
"span_ids": list(self.span_ids),
|
| 588 |
+
}
|
| 589 |
+
|
| 590 |
+
@classmethod
|
| 591 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "BasicBlock":
|
| 592 |
+
return cls(
|
| 593 |
+
block_id=value.get("block_id", ""),
|
| 594 |
+
command_ids=tuple(value.get("command_ids", ())),
|
| 595 |
+
source_ref_ids=tuple(value.get("source_ref_ids", ())),
|
| 596 |
+
span_ids=tuple(value.get("span_ids", ())),
|
| 597 |
+
)
|
| 598 |
+
|
| 599 |
+
|
| 600 |
+
@dataclass(frozen=True, slots=True)
|
| 601 |
+
class ControlFlowEdge:
|
| 602 |
+
edge_id: str
|
| 603 |
+
source_block_id: str
|
| 604 |
+
target_block_id: str
|
| 605 |
+
kind: EdgeKind | str = EdgeKind.NORMAL
|
| 606 |
+
order: int = 0
|
| 607 |
+
condition_expression_id: str = ""
|
| 608 |
+
exception_type: str = ""
|
| 609 |
+
|
| 610 |
+
def __post_init__(self) -> None:
|
| 611 |
+
kind = _enum(self.kind, EdgeKind, "kind")
|
| 612 |
+
if isinstance(self.order, bool) or not isinstance(self.order, int) or self.order < 0:
|
| 613 |
+
raise ProgramValidationError("edge order must be a non-negative integer")
|
| 614 |
+
condition = _optional_text(self.condition_expression_id, "condition_expression_id")
|
| 615 |
+
if condition:
|
| 616 |
+
condition = _identifier(condition, "condition_expression_id")
|
| 617 |
+
exception = _optional_text(self.exception_type, "exception_type")
|
| 618 |
+
if kind in {EdgeKind.TRUE, EdgeKind.FALSE} and not condition:
|
| 619 |
+
raise ProgramValidationError(f"{kind.value} edges require condition_expression_id")
|
| 620 |
+
if kind is EdgeKind.EXCEPTION and not exception:
|
| 621 |
+
raise ProgramValidationError("exception edges require exception_type")
|
| 622 |
+
if kind is not EdgeKind.EXCEPTION and exception:
|
| 623 |
+
raise ProgramValidationError("exception_type is only valid for exception edges")
|
| 624 |
+
object.__setattr__(self, "edge_id", _identifier(self.edge_id, "edge_id"))
|
| 625 |
+
object.__setattr__(
|
| 626 |
+
self,
|
| 627 |
+
"source_block_id",
|
| 628 |
+
_identifier(self.source_block_id, "source_block_id"),
|
| 629 |
+
)
|
| 630 |
+
object.__setattr__(
|
| 631 |
+
self,
|
| 632 |
+
"target_block_id",
|
| 633 |
+
_identifier(self.target_block_id, "target_block_id"),
|
| 634 |
+
)
|
| 635 |
+
object.__setattr__(self, "kind", kind)
|
| 636 |
+
object.__setattr__(self, "condition_expression_id", condition)
|
| 637 |
+
object.__setattr__(self, "exception_type", exception)
|
| 638 |
+
|
| 639 |
+
def to_dict(self) -> dict[str, Any]:
|
| 640 |
+
return {
|
| 641 |
+
"condition_expression_id": self.condition_expression_id,
|
| 642 |
+
"edge_id": self.edge_id,
|
| 643 |
+
"exception_type": self.exception_type,
|
| 644 |
+
"kind": self.kind.value,
|
| 645 |
+
"order": self.order,
|
| 646 |
+
"source_block_id": self.source_block_id,
|
| 647 |
+
"target_block_id": self.target_block_id,
|
| 648 |
+
}
|
| 649 |
+
|
| 650 |
+
@classmethod
|
| 651 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "ControlFlowEdge":
|
| 652 |
+
return cls(
|
| 653 |
+
edge_id=value.get("edge_id", ""),
|
| 654 |
+
source_block_id=value.get("source_block_id", ""),
|
| 655 |
+
target_block_id=value.get("target_block_id", ""),
|
| 656 |
+
kind=value.get("kind", EdgeKind.NORMAL.value),
|
| 657 |
+
order=value.get("order", 0),
|
| 658 |
+
condition_expression_id=value.get("condition_expression_id", ""),
|
| 659 |
+
exception_type=value.get("exception_type", ""),
|
| 660 |
+
)
|
| 661 |
+
|
| 662 |
+
|
| 663 |
+
@dataclass(frozen=True, slots=True)
|
| 664 |
+
class ControlFlowGraph:
|
| 665 |
+
"""A closed CFG with distinct normal and exceptional exits."""
|
| 666 |
+
|
| 667 |
+
graph_id: str
|
| 668 |
+
entry_block_id: str
|
| 669 |
+
blocks: tuple[BasicBlock, ...]
|
| 670 |
+
edges: tuple[ControlFlowEdge, ...]
|
| 671 |
+
normal_exit_block_ids: tuple[str, ...]
|
| 672 |
+
exceptional_exit_block_ids: tuple[str, ...] = ()
|
| 673 |
+
|
| 674 |
+
def __post_init__(self) -> None:
|
| 675 |
+
blocks = tuple(
|
| 676 |
+
item if isinstance(item, BasicBlock) else BasicBlock.from_dict(_mapping(item, "block"))
|
| 677 |
+
for item in self.blocks
|
| 678 |
+
)
|
| 679 |
+
edges = tuple(
|
| 680 |
+
item
|
| 681 |
+
if isinstance(item, ControlFlowEdge)
|
| 682 |
+
else ControlFlowEdge.from_dict(_mapping(item, "edge"))
|
| 683 |
+
for item in self.edges
|
| 684 |
+
)
|
| 685 |
+
object.__setattr__(self, "graph_id", _identifier(self.graph_id, "graph_id"))
|
| 686 |
+
object.__setattr__(
|
| 687 |
+
self, "entry_block_id", _identifier(self.entry_block_id, "entry_block_id")
|
| 688 |
+
)
|
| 689 |
+
object.__setattr__(self, "blocks", tuple(sorted(blocks, key=lambda item: item.block_id)))
|
| 690 |
+
object.__setattr__(self, "edges", tuple(sorted(edges, key=lambda item: item.edge_id)))
|
| 691 |
+
object.__setattr__(
|
| 692 |
+
self,
|
| 693 |
+
"normal_exit_block_ids",
|
| 694 |
+
_ids(self.normal_exit_block_ids, "normal_exit_block_ids"),
|
| 695 |
+
)
|
| 696 |
+
object.__setattr__(
|
| 697 |
+
self,
|
| 698 |
+
"exceptional_exit_block_ids",
|
| 699 |
+
_ids(self.exceptional_exit_block_ids, "exceptional_exit_block_ids"),
|
| 700 |
+
)
|
| 701 |
+
self.validate()
|
| 702 |
+
|
| 703 |
+
@property
|
| 704 |
+
def command_ids(self) -> tuple[str, ...]:
|
| 705 |
+
return tuple(command for block in self.blocks for command in block.command_ids)
|
| 706 |
+
|
| 707 |
+
def validate(
|
| 708 |
+
self,
|
| 709 |
+
*,
|
| 710 |
+
known_command_ids: set[str] | None = None,
|
| 711 |
+
known_expression_ids: set[str] | None = None,
|
| 712 |
+
) -> None:
|
| 713 |
+
block_ids = [item.block_id for item in self.blocks]
|
| 714 |
+
edge_ids = [item.edge_id for item in self.edges]
|
| 715 |
+
if not block_ids:
|
| 716 |
+
raise ProgramValidationError("a CFG requires at least one block")
|
| 717 |
+
if len(block_ids) != len(set(block_ids)):
|
| 718 |
+
raise ProgramValidationError("duplicate CFG block identifiers")
|
| 719 |
+
if len(edge_ids) != len(set(edge_ids)):
|
| 720 |
+
raise ProgramValidationError("duplicate CFG edge identifiers")
|
| 721 |
+
known_blocks = set(block_ids)
|
| 722 |
+
_known((self.entry_block_id,), known_blocks, f"CFG {self.graph_id}.entry")
|
| 723 |
+
if not self.normal_exit_block_ids:
|
| 724 |
+
raise ProgramValidationError("a CFG requires at least one normal exit")
|
| 725 |
+
_known(
|
| 726 |
+
self.normal_exit_block_ids,
|
| 727 |
+
known_blocks,
|
| 728 |
+
f"CFG {self.graph_id}.normal exits",
|
| 729 |
+
)
|
| 730 |
+
_known(
|
| 731 |
+
self.exceptional_exit_block_ids,
|
| 732 |
+
known_blocks,
|
| 733 |
+
f"CFG {self.graph_id}.exceptional exits",
|
| 734 |
+
)
|
| 735 |
+
overlap = set(self.normal_exit_block_ids) & set(self.exceptional_exit_block_ids)
|
| 736 |
+
if overlap:
|
| 737 |
+
raise ProgramValidationError(
|
| 738 |
+
f"normal and exceptional CFG exits must be separate: {sorted(overlap)}"
|
| 739 |
+
)
|
| 740 |
+
all_commands = list(self.command_ids)
|
| 741 |
+
if len(all_commands) != len(set(all_commands)):
|
| 742 |
+
raise ProgramValidationError("a command may occur in only one CFG block")
|
| 743 |
+
if known_command_ids is not None:
|
| 744 |
+
_known(all_commands, known_command_ids, f"CFG {self.graph_id}.commands")
|
| 745 |
+
|
| 746 |
+
outgoing: dict[str, list[ControlFlowEdge]] = defaultdict(list)
|
| 747 |
+
adjacency: dict[str, set[str]] = defaultdict(set)
|
| 748 |
+
for edge in self.edges:
|
| 749 |
+
_known(
|
| 750 |
+
(edge.source_block_id, edge.target_block_id),
|
| 751 |
+
known_blocks,
|
| 752 |
+
f"edge {edge.edge_id}",
|
| 753 |
+
)
|
| 754 |
+
if known_expression_ids is not None and edge.condition_expression_id:
|
| 755 |
+
_known(
|
| 756 |
+
(edge.condition_expression_id,),
|
| 757 |
+
known_expression_ids,
|
| 758 |
+
f"edge {edge.edge_id}.condition",
|
| 759 |
+
)
|
| 760 |
+
outgoing[edge.source_block_id].append(edge)
|
| 761 |
+
adjacency[edge.source_block_id].add(edge.target_block_id)
|
| 762 |
+
for block_id, block_edges in outgoing.items():
|
| 763 |
+
orders = [edge.order for edge in block_edges]
|
| 764 |
+
if len(orders) != len(set(orders)):
|
| 765 |
+
raise ProgramValidationError(
|
| 766 |
+
f"outgoing edge order is ambiguous at block {block_id}"
|
| 767 |
+
)
|
| 768 |
+
if sorted(orders) != list(range(len(orders))):
|
| 769 |
+
raise ProgramValidationError(
|
| 770 |
+
f"outgoing edge order at block {block_id} must be contiguous from zero"
|
| 771 |
+
)
|
| 772 |
+
kinds = {edge.kind for edge in block_edges}
|
| 773 |
+
if (EdgeKind.TRUE in kinds) != (EdgeKind.FALSE in kinds):
|
| 774 |
+
raise ProgramValidationError(
|
| 775 |
+
f"block {block_id} must have both true and false edges"
|
| 776 |
+
)
|
| 777 |
+
if EdgeKind.TRUE in kinds:
|
| 778 |
+
true_edges = [edge for edge in block_edges if edge.kind is EdgeKind.TRUE]
|
| 779 |
+
false_edges = [edge for edge in block_edges if edge.kind is EdgeKind.FALSE]
|
| 780 |
+
if len(true_edges) != 1 or len(false_edges) != 1:
|
| 781 |
+
raise ProgramValidationError(
|
| 782 |
+
f"block {block_id} must have exactly one true and one false edge"
|
| 783 |
+
)
|
| 784 |
+
if true_edges[0].condition_expression_id != false_edges[0].condition_expression_id:
|
| 785 |
+
raise ProgramValidationError(
|
| 786 |
+
f"true and false edges at block {block_id} must share one condition"
|
| 787 |
+
)
|
| 788 |
+
|
| 789 |
+
exits = set(self.normal_exit_block_ids) | set(self.exceptional_exit_block_ids)
|
| 790 |
+
terminal_with_edges = sorted(exits & set(outgoing))
|
| 791 |
+
if terminal_with_edges:
|
| 792 |
+
raise ProgramValidationError(f"CFG exit blocks must be terminal: {terminal_with_edges}")
|
| 793 |
+
dead_ends = sorted(known_blocks - exits - set(outgoing))
|
| 794 |
+
if dead_ends:
|
| 795 |
+
raise ProgramValidationError(f"non-exit CFG blocks have no outgoing edge: {dead_ends}")
|
| 796 |
+
reachable = {self.entry_block_id}
|
| 797 |
+
queue = deque((self.entry_block_id,))
|
| 798 |
+
while queue:
|
| 799 |
+
current = queue.popleft()
|
| 800 |
+
for target in adjacency[current]:
|
| 801 |
+
if target not in reachable:
|
| 802 |
+
reachable.add(target)
|
| 803 |
+
queue.append(target)
|
| 804 |
+
unreachable = sorted(known_blocks - reachable)
|
| 805 |
+
if unreachable:
|
| 806 |
+
raise ProgramValidationError(f"unreachable CFG blocks: {unreachable}")
|
| 807 |
+
if not (reachable & set(self.normal_exit_block_ids)):
|
| 808 |
+
raise ProgramValidationError("no normal exit is reachable from CFG entry")
|
| 809 |
+
|
| 810 |
+
def to_dict(self) -> dict[str, Any]:
|
| 811 |
+
return {
|
| 812 |
+
"blocks": [
|
| 813 |
+
item.to_dict() for item in sorted(self.blocks, key=lambda item: item.block_id)
|
| 814 |
+
],
|
| 815 |
+
"edges": [item.to_dict() for item in sorted(self.edges, key=lambda item: item.edge_id)],
|
| 816 |
+
"entry_block_id": self.entry_block_id,
|
| 817 |
+
"exceptional_exit_block_ids": list(self.exceptional_exit_block_ids),
|
| 818 |
+
"graph_id": self.graph_id,
|
| 819 |
+
"normal_exit_block_ids": list(self.normal_exit_block_ids),
|
| 820 |
+
}
|
| 821 |
+
|
| 822 |
+
@classmethod
|
| 823 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "ControlFlowGraph":
|
| 824 |
+
return cls(
|
| 825 |
+
graph_id=value.get("graph_id", ""),
|
| 826 |
+
entry_block_id=value.get("entry_block_id", ""),
|
| 827 |
+
blocks=tuple(
|
| 828 |
+
BasicBlock.from_dict(_mapping(item, "block")) for item in value.get("blocks", ())
|
| 829 |
+
),
|
| 830 |
+
edges=tuple(
|
| 831 |
+
ControlFlowEdge.from_dict(_mapping(item, "edge")) for item in value.get("edges", ())
|
| 832 |
+
),
|
| 833 |
+
normal_exit_block_ids=tuple(value.get("normal_exit_block_ids", ())),
|
| 834 |
+
exceptional_exit_block_ids=tuple(value.get("exceptional_exit_block_ids", ())),
|
| 835 |
+
)
|
| 836 |
+
|
| 837 |
+
|
| 838 |
+
@dataclass(frozen=True, slots=True)
|
| 839 |
+
class ProgramFunction:
|
| 840 |
+
function_id: str
|
| 841 |
+
name: str
|
| 842 |
+
cfg: ControlFlowGraph
|
| 843 |
+
parameter_symbol_ids: tuple[str, ...] = ()
|
| 844 |
+
local_symbol_ids: tuple[str, ...] = ()
|
| 845 |
+
exception_symbol_ids: tuple[str, ...] = ()
|
| 846 |
+
result_symbol_id: str = ""
|
| 847 |
+
return_type: str = "void"
|
| 848 |
+
purity: Purity | str = Purity.UNKNOWN
|
| 849 |
+
effects: EffectSummary = field(default_factory=EffectSummary)
|
| 850 |
+
declared_exceptions: tuple[str, ...] = ()
|
| 851 |
+
source_ref_ids: tuple[str, ...] = ()
|
| 852 |
+
span_ids: tuple[str, ...] = ()
|
| 853 |
+
|
| 854 |
+
def __post_init__(self) -> None:
|
| 855 |
+
sources, spans = _source_map(self.source_ref_ids, self.span_ids, "ProgramFunction")
|
| 856 |
+
cfg = (
|
| 857 |
+
self.cfg
|
| 858 |
+
if isinstance(self.cfg, ControlFlowGraph)
|
| 859 |
+
else ControlFlowGraph.from_dict(_mapping(self.cfg, "cfg"))
|
| 860 |
+
)
|
| 861 |
+
result = _optional_text(self.result_symbol_id, "result_symbol_id")
|
| 862 |
+
if result:
|
| 863 |
+
result = _identifier(result, "result_symbol_id")
|
| 864 |
+
effects = (
|
| 865 |
+
self.effects
|
| 866 |
+
if isinstance(self.effects, EffectSummary)
|
| 867 |
+
else EffectSummary.from_dict(_mapping(self.effects, "effects"))
|
| 868 |
+
)
|
| 869 |
+
exceptions = tuple(
|
| 870 |
+
sorted(_text(item, "declared_exceptions item") for item in self.declared_exceptions)
|
| 871 |
+
)
|
| 872 |
+
if len(exceptions) != len(set(exceptions)):
|
| 873 |
+
raise ProgramValidationError("declared_exceptions must not contain duplicates")
|
| 874 |
+
purity = _enum(self.purity, Purity, "purity")
|
| 875 |
+
if purity is Purity.PURE and not effects.is_pure:
|
| 876 |
+
raise ProgramValidationError("pure functions cannot declare impure effects")
|
| 877 |
+
if purity is Purity.READ_ONLY and not effects.is_read_only:
|
| 878 |
+
raise ProgramValidationError("read-only functions cannot declare write effects")
|
| 879 |
+
if set(effects.raises) - set(exceptions):
|
| 880 |
+
raise ProgramValidationError("function effects raise undeclared exception types")
|
| 881 |
+
object.__setattr__(self, "function_id", _identifier(self.function_id, "function_id"))
|
| 882 |
+
object.__setattr__(self, "name", _text(self.name, "name"))
|
| 883 |
+
object.__setattr__(self, "cfg", cfg)
|
| 884 |
+
object.__setattr__(
|
| 885 |
+
self,
|
| 886 |
+
"parameter_symbol_ids",
|
| 887 |
+
_ids(
|
| 888 |
+
self.parameter_symbol_ids,
|
| 889 |
+
"parameter_symbol_ids",
|
| 890 |
+
preserve_order=True,
|
| 891 |
+
),
|
| 892 |
+
)
|
| 893 |
+
object.__setattr__(
|
| 894 |
+
self, "local_symbol_ids", _ids(self.local_symbol_ids, "local_symbol_ids")
|
| 895 |
+
)
|
| 896 |
+
object.__setattr__(
|
| 897 |
+
self,
|
| 898 |
+
"exception_symbol_ids",
|
| 899 |
+
_ids(self.exception_symbol_ids, "exception_symbol_ids"),
|
| 900 |
+
)
|
| 901 |
+
scoped_groups = (
|
| 902 |
+
set(self.parameter_symbol_ids),
|
| 903 |
+
set(self.local_symbol_ids),
|
| 904 |
+
set(self.exception_symbol_ids),
|
| 905 |
+
{result} if result else set(),
|
| 906 |
+
)
|
| 907 |
+
seen: set[str] = set()
|
| 908 |
+
for group in scoped_groups:
|
| 909 |
+
if seen & group:
|
| 910 |
+
raise ProgramValidationError("function symbol scopes overlap")
|
| 911 |
+
seen.update(group)
|
| 912 |
+
object.__setattr__(self, "result_symbol_id", result)
|
| 913 |
+
object.__setattr__(self, "return_type", _text(self.return_type, "return_type"))
|
| 914 |
+
object.__setattr__(self, "purity", purity)
|
| 915 |
+
object.__setattr__(self, "effects", effects)
|
| 916 |
+
object.__setattr__(self, "declared_exceptions", exceptions)
|
| 917 |
+
object.__setattr__(self, "source_ref_ids", sources)
|
| 918 |
+
object.__setattr__(self, "span_ids", spans)
|
| 919 |
+
|
| 920 |
+
@property
|
| 921 |
+
def scoped_symbol_ids(self) -> tuple[str, ...]:
|
| 922 |
+
values = self.parameter_symbol_ids + self.local_symbol_ids + self.exception_symbol_ids
|
| 923 |
+
if self.result_symbol_id:
|
| 924 |
+
values += (self.result_symbol_id,)
|
| 925 |
+
return values
|
| 926 |
+
|
| 927 |
+
def to_dict(self) -> dict[str, Any]:
|
| 928 |
+
return {
|
| 929 |
+
"cfg": self.cfg.to_dict(),
|
| 930 |
+
"declared_exceptions": list(self.declared_exceptions),
|
| 931 |
+
"effects": self.effects.to_dict(),
|
| 932 |
+
"exception_symbol_ids": list(self.exception_symbol_ids),
|
| 933 |
+
"function_id": self.function_id,
|
| 934 |
+
"local_symbol_ids": list(self.local_symbol_ids),
|
| 935 |
+
"name": self.name,
|
| 936 |
+
"parameter_symbol_ids": list(self.parameter_symbol_ids),
|
| 937 |
+
"purity": self.purity.value,
|
| 938 |
+
"result_symbol_id": self.result_symbol_id,
|
| 939 |
+
"return_type": self.return_type,
|
| 940 |
+
"source_ref_ids": list(self.source_ref_ids),
|
| 941 |
+
"span_ids": list(self.span_ids),
|
| 942 |
+
}
|
| 943 |
+
|
| 944 |
+
@classmethod
|
| 945 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "ProgramFunction":
|
| 946 |
+
return cls(
|
| 947 |
+
function_id=value.get("function_id", ""),
|
| 948 |
+
name=value.get("name", ""),
|
| 949 |
+
cfg=ControlFlowGraph.from_dict(_mapping(value.get("cfg", {}), "cfg")),
|
| 950 |
+
parameter_symbol_ids=tuple(value.get("parameter_symbol_ids", ())),
|
| 951 |
+
local_symbol_ids=tuple(value.get("local_symbol_ids", ())),
|
| 952 |
+
result_symbol_id=value.get("result_symbol_id", ""),
|
| 953 |
+
return_type=value.get("return_type", "void"),
|
| 954 |
+
purity=value.get("purity", Purity.UNKNOWN.value),
|
| 955 |
+
effects=EffectSummary.from_dict(_mapping(value.get("effects", {}), "effects")),
|
| 956 |
+
exception_symbol_ids=tuple(value.get("exception_symbol_ids", ())),
|
| 957 |
+
declared_exceptions=tuple(value.get("declared_exceptions", ())),
|
| 958 |
+
source_ref_ids=tuple(value.get("source_ref_ids", ())),
|
| 959 |
+
span_ids=tuple(value.get("span_ids", ())),
|
| 960 |
+
)
|
| 961 |
+
|
| 962 |
+
|
| 963 |
+
@dataclass(frozen=True, slots=True)
|
| 964 |
+
class ProgramIR:
|
| 965 |
+
"""Canonical closed-world program document (``ProgramIR@1``)."""
|
| 966 |
+
|
| 967 |
+
sources: tuple[SourceRef, ...]
|
| 968 |
+
spans: tuple[SourceSpan, ...]
|
| 969 |
+
symbols: tuple[ProgramSymbol, ...]
|
| 970 |
+
expressions: tuple[ProgramExpression, ...]
|
| 971 |
+
commands: tuple[ProgramCommand, ...]
|
| 972 |
+
functions: tuple[ProgramFunction, ...]
|
| 973 |
+
global_symbol_ids: tuple[str, ...] = ()
|
| 974 |
+
metadata: FrozenMap = field(default_factory=FrozenMap)
|
| 975 |
+
program_id: str = ""
|
| 976 |
+
schema_version: str = PROGRAM_IR_SCHEMA_VERSION
|
| 977 |
+
|
| 978 |
+
def __post_init__(self) -> None:
|
| 979 |
+
object.__setattr__(
|
| 980 |
+
self,
|
| 981 |
+
"sources",
|
| 982 |
+
tuple(
|
| 983 |
+
item
|
| 984 |
+
if isinstance(item, SourceRef)
|
| 985 |
+
else SourceRef.from_dict(_mapping(item, "source"))
|
| 986 |
+
for item in self.sources
|
| 987 |
+
),
|
| 988 |
+
)
|
| 989 |
+
object.__setattr__(
|
| 990 |
+
self,
|
| 991 |
+
"spans",
|
| 992 |
+
tuple(
|
| 993 |
+
item
|
| 994 |
+
if isinstance(item, SourceSpan)
|
| 995 |
+
else SourceSpan.from_dict(_mapping(item, "span"))
|
| 996 |
+
for item in self.spans
|
| 997 |
+
),
|
| 998 |
+
)
|
| 999 |
+
for name, cls in (
|
| 1000 |
+
("symbols", ProgramSymbol),
|
| 1001 |
+
("expressions", ProgramExpression),
|
| 1002 |
+
("commands", ProgramCommand),
|
| 1003 |
+
("functions", ProgramFunction),
|
| 1004 |
+
):
|
| 1005 |
+
singular = name[:-1] if name != "classes" else "class"
|
| 1006 |
+
values = tuple(
|
| 1007 |
+
item if isinstance(item, cls) else cls.from_dict(_mapping(item, singular))
|
| 1008 |
+
for item in getattr(self, name)
|
| 1009 |
+
)
|
| 1010 |
+
identity_field = {
|
| 1011 |
+
"symbols": "symbol_id",
|
| 1012 |
+
"expressions": "expression_id",
|
| 1013 |
+
"commands": "command_id",
|
| 1014 |
+
"functions": "function_id",
|
| 1015 |
+
}[name]
|
| 1016 |
+
object.__setattr__(
|
| 1017 |
+
self,
|
| 1018 |
+
name,
|
| 1019 |
+
tuple(sorted(values, key=lambda item: getattr(item, identity_field))),
|
| 1020 |
+
)
|
| 1021 |
+
object.__setattr__(
|
| 1022 |
+
self, "sources", tuple(sorted(self.sources, key=lambda item: item.ref_id))
|
| 1023 |
+
)
|
| 1024 |
+
object.__setattr__(self, "spans", tuple(sorted(self.spans, key=lambda item: item.span_id)))
|
| 1025 |
+
object.__setattr__(
|
| 1026 |
+
self,
|
| 1027 |
+
"global_symbol_ids",
|
| 1028 |
+
_ids(self.global_symbol_ids, "global_symbol_ids"),
|
| 1029 |
+
)
|
| 1030 |
+
object.__setattr__(self, "metadata", _frozen(self.metadata, "metadata"))
|
| 1031 |
+
self.validate()
|
| 1032 |
+
identity = self._compute_identity()
|
| 1033 |
+
if self.program_id and self.program_id != identity.cid:
|
| 1034 |
+
raise ProgramValidationError("program_id does not match canonical program semantics")
|
| 1035 |
+
object.__setattr__(self, "program_id", identity.cid)
|
| 1036 |
+
|
| 1037 |
+
@property
|
| 1038 |
+
def identity(self) -> CanonicalIdentity:
|
| 1039 |
+
return self._compute_identity()
|
| 1040 |
+
|
| 1041 |
+
@property
|
| 1042 |
+
def canonical_id(self) -> str:
|
| 1043 |
+
return self.program_id
|
| 1044 |
+
|
| 1045 |
+
def _compute_identity(self) -> CanonicalIdentity:
|
| 1046 |
+
return canonical_identity(
|
| 1047 |
+
self.semantic_dict(),
|
| 1048 |
+
domain=PROGRAM_IR_IDENTITY_DOMAIN,
|
| 1049 |
+
schema_version=PROGRAM_IR_SCHEMA_VERSION,
|
| 1050 |
+
)
|
| 1051 |
+
|
| 1052 |
+
def semantic_dict(self) -> dict[str, Any]:
|
| 1053 |
+
return {
|
| 1054 |
+
"commands": [
|
| 1055 |
+
item.to_dict() for item in sorted(self.commands, key=lambda item: item.command_id)
|
| 1056 |
+
],
|
| 1057 |
+
"expressions": [
|
| 1058 |
+
item.to_dict()
|
| 1059 |
+
for item in sorted(self.expressions, key=lambda item: item.expression_id)
|
| 1060 |
+
],
|
| 1061 |
+
"functions": [
|
| 1062 |
+
item.to_dict() for item in sorted(self.functions, key=lambda item: item.function_id)
|
| 1063 |
+
],
|
| 1064 |
+
"global_symbol_ids": list(self.global_symbol_ids),
|
| 1065 |
+
"metadata": self.metadata.to_dict(),
|
| 1066 |
+
"schema_version": self.schema_version,
|
| 1067 |
+
"sources": [
|
| 1068 |
+
item.to_dict() for item in sorted(self.sources, key=lambda item: item.ref_id)
|
| 1069 |
+
],
|
| 1070 |
+
"spans": [item.to_dict() for item in sorted(self.spans, key=lambda item: item.span_id)],
|
| 1071 |
+
"symbols": [
|
| 1072 |
+
item.to_dict() for item in sorted(self.symbols, key=lambda item: item.symbol_id)
|
| 1073 |
+
],
|
| 1074 |
+
}
|
| 1075 |
+
|
| 1076 |
+
deterministic_dict = semantic_dict
|
| 1077 |
+
|
| 1078 |
+
def to_dict(self) -> dict[str, Any]:
|
| 1079 |
+
value = self.semantic_dict()
|
| 1080 |
+
value["program_id"] = self.program_id
|
| 1081 |
+
return value
|
| 1082 |
+
|
| 1083 |
+
def canonical_bytes(self) -> bytes:
|
| 1084 |
+
return canonical_json_bytes(self.to_dict())
|
| 1085 |
+
|
| 1086 |
+
def semantic_bytes(self) -> bytes:
|
| 1087 |
+
return self.identity.canonical_bytes
|
| 1088 |
+
|
| 1089 |
+
def to_json(self) -> str:
|
| 1090 |
+
return self.canonical_bytes().decode("utf-8")
|
| 1091 |
+
|
| 1092 |
+
def validate(self) -> None:
|
| 1093 |
+
if self.schema_version != PROGRAM_IR_SCHEMA_VERSION:
|
| 1094 |
+
raise ProgramValidationError(f"unsupported schema_version {self.schema_version!r}")
|
| 1095 |
+
if not self.sources:
|
| 1096 |
+
raise ProgramValidationError("a source-grounded ProgramIR requires sources")
|
| 1097 |
+
if not self.functions:
|
| 1098 |
+
raise ProgramValidationError("ProgramIR requires at least one function")
|
| 1099 |
+
|
| 1100 |
+
def unique(values: Sequence[object], attr: str, label: str) -> set[str]:
|
| 1101 |
+
ids = [getattr(item, attr) for item in values]
|
| 1102 |
+
if len(ids) != len(set(ids)):
|
| 1103 |
+
raise ProgramValidationError(f"duplicate {label} identifiers")
|
| 1104 |
+
return set(ids)
|
| 1105 |
+
|
| 1106 |
+
source_ids = unique(self.sources, "ref_id", "source")
|
| 1107 |
+
unique(self.spans, "span_id", "span")
|
| 1108 |
+
symbol_ids = unique(self.symbols, "symbol_id", "symbol")
|
| 1109 |
+
expression_ids = unique(self.expressions, "expression_id", "expression")
|
| 1110 |
+
command_ids = unique(self.commands, "command_id", "command")
|
| 1111 |
+
unique(self.functions, "function_id", "function")
|
| 1112 |
+
graph_ids = [item.cfg.graph_id for item in self.functions]
|
| 1113 |
+
if len(graph_ids) != len(set(graph_ids)):
|
| 1114 |
+
raise ProgramValidationError("duplicate CFG identifiers")
|
| 1115 |
+
|
| 1116 |
+
for source in self.sources:
|
| 1117 |
+
source.validate()
|
| 1118 |
+
spans_by_id = {item.span_id: item for item in self.spans}
|
| 1119 |
+
for span in self.spans:
|
| 1120 |
+
span.validate()
|
| 1121 |
+
_known((span.source_ref_id,), source_ids, f"span {span.span_id}")
|
| 1122 |
+
for item in (
|
| 1123 |
+
*self.symbols,
|
| 1124 |
+
*self.expressions,
|
| 1125 |
+
*self.commands,
|
| 1126 |
+
*self.functions,
|
| 1127 |
+
*(block for function in self.functions for block in function.cfg.blocks),
|
| 1128 |
+
*(condition for command in self.commands for condition in command.undefined_behavior),
|
| 1129 |
+
):
|
| 1130 |
+
self._validate_source_map(item, source_ids, spans_by_id)
|
| 1131 |
+
|
| 1132 |
+
_known(self.global_symbol_ids, symbol_ids, "global_symbol_ids")
|
| 1133 |
+
symbols_by_id = {item.symbol_id: item for item in self.symbols}
|
| 1134 |
+
for symbol_id in self.global_symbol_ids:
|
| 1135 |
+
if symbols_by_id[symbol_id].kind not in {
|
| 1136 |
+
SymbolKind.GLOBAL,
|
| 1137 |
+
SymbolKind.FUNCTION,
|
| 1138 |
+
}:
|
| 1139 |
+
raise ProgramValidationError(f"global scope contains non-global symbol {symbol_id}")
|
| 1140 |
+
expressions_by_id = {item.expression_id: item for item in self.expressions}
|
| 1141 |
+
for expression in self.expressions:
|
| 1142 |
+
_known(
|
| 1143 |
+
expression.operand_ids,
|
| 1144 |
+
expression_ids,
|
| 1145 |
+
f"expression {expression.expression_id}.operands",
|
| 1146 |
+
)
|
| 1147 |
+
_known(
|
| 1148 |
+
expression.symbol_ids,
|
| 1149 |
+
symbol_ids,
|
| 1150 |
+
f"expression {expression.expression_id}.symbols",
|
| 1151 |
+
)
|
| 1152 |
+
if expression.expression_id in expression.operand_ids:
|
| 1153 |
+
raise ProgramValidationError(
|
| 1154 |
+
f"expression {expression.expression_id} references itself"
|
| 1155 |
+
)
|
| 1156 |
+
self._reject_expression_cycles(expressions_by_id)
|
| 1157 |
+
|
| 1158 |
+
commands_by_id = {item.command_id: item for item in self.commands}
|
| 1159 |
+
for command in self.commands:
|
| 1160 |
+
_known(
|
| 1161 |
+
command.expression_ids,
|
| 1162 |
+
expression_ids,
|
| 1163 |
+
f"command {command.command_id}.expressions",
|
| 1164 |
+
)
|
| 1165 |
+
_known(
|
| 1166 |
+
command.target_symbol_ids,
|
| 1167 |
+
symbol_ids,
|
| 1168 |
+
f"command {command.command_id}.targets",
|
| 1169 |
+
)
|
| 1170 |
+
_known(
|
| 1171 |
+
command.effects.symbol_ids(),
|
| 1172 |
+
symbol_ids,
|
| 1173 |
+
f"command {command.command_id}.effects",
|
| 1174 |
+
)
|
| 1175 |
+
for condition in command.undefined_behavior:
|
| 1176 |
+
_known(
|
| 1177 |
+
(condition.expression_id,),
|
| 1178 |
+
expression_ids,
|
| 1179 |
+
f"undefined behavior {condition.condition_id}",
|
| 1180 |
+
)
|
| 1181 |
+
|
| 1182 |
+
owned_commands: dict[str, str] = {}
|
| 1183 |
+
used_scoped_symbols: set[str] = set()
|
| 1184 |
+
for function in self.functions:
|
| 1185 |
+
function.cfg.validate(
|
| 1186 |
+
known_command_ids=command_ids,
|
| 1187 |
+
known_expression_ids=expression_ids,
|
| 1188 |
+
)
|
| 1189 |
+
_known(function.scoped_symbol_ids, symbol_ids, f"function {function.function_id}")
|
| 1190 |
+
visible = set(self.global_symbol_ids) | set(function.scoped_symbol_ids)
|
| 1191 |
+
for symbol_id in function.parameter_symbol_ids:
|
| 1192 |
+
if symbols_by_id[symbol_id].kind is not SymbolKind.PARAMETER:
|
| 1193 |
+
raise ProgramValidationError(
|
| 1194 |
+
f"function parameter {symbol_id} is not a parameter symbol"
|
| 1195 |
+
)
|
| 1196 |
+
for symbol_id in function.local_symbol_ids:
|
| 1197 |
+
if symbols_by_id[symbol_id].kind is not SymbolKind.LOCAL:
|
| 1198 |
+
raise ProgramValidationError(
|
| 1199 |
+
f"function local {symbol_id} is not a local symbol"
|
| 1200 |
+
)
|
| 1201 |
+
for symbol_id in function.exception_symbol_ids:
|
| 1202 |
+
if symbols_by_id[symbol_id].kind is not SymbolKind.EXCEPTION:
|
| 1203 |
+
raise ProgramValidationError(
|
| 1204 |
+
f"function exception {symbol_id} is not an exception symbol"
|
| 1205 |
+
)
|
| 1206 |
+
if function.result_symbol_id and (
|
| 1207 |
+
symbols_by_id[function.result_symbol_id].kind is not SymbolKind.RESULT
|
| 1208 |
+
):
|
| 1209 |
+
raise ProgramValidationError(
|
| 1210 |
+
f"function result {function.result_symbol_id} is not a result symbol"
|
| 1211 |
+
)
|
| 1212 |
+
overlap = used_scoped_symbols & set(function.scoped_symbol_ids)
|
| 1213 |
+
if overlap:
|
| 1214 |
+
raise ProgramValidationError(
|
| 1215 |
+
f"function-local symbols have multiple owners: {sorted(overlap)}"
|
| 1216 |
+
)
|
| 1217 |
+
used_scoped_symbols.update(function.scoped_symbol_ids)
|
| 1218 |
+
_known(
|
| 1219 |
+
function.effects.symbol_ids(),
|
| 1220 |
+
visible,
|
| 1221 |
+
f"function {function.function_id}.effects",
|
| 1222 |
+
)
|
| 1223 |
+
edge_exceptions = {
|
| 1224 |
+
edge.exception_type
|
| 1225 |
+
for edge in function.cfg.edges
|
| 1226 |
+
if edge.kind is EdgeKind.EXCEPTION
|
| 1227 |
+
}
|
| 1228 |
+
undeclared_edge_exceptions = sorted(edge_exceptions - set(function.declared_exceptions))
|
| 1229 |
+
if undeclared_edge_exceptions:
|
| 1230 |
+
raise ProgramValidationError(
|
| 1231 |
+
f"CFG {function.cfg.graph_id} raises undeclared exceptions "
|
| 1232 |
+
f"{undeclared_edge_exceptions}"
|
| 1233 |
+
)
|
| 1234 |
+
for edge in function.cfg.edges:
|
| 1235 |
+
if edge.condition_expression_id:
|
| 1236 |
+
referenced = self._expression_symbols(
|
| 1237 |
+
(edge.condition_expression_id,), expressions_by_id
|
| 1238 |
+
)
|
| 1239 |
+
_known(
|
| 1240 |
+
tuple(referenced),
|
| 1241 |
+
visible,
|
| 1242 |
+
f"edge {edge.edge_id} condition in function {function.function_id}",
|
| 1243 |
+
)
|
| 1244 |
+
for command_id in function.cfg.command_ids:
|
| 1245 |
+
if command_id in owned_commands:
|
| 1246 |
+
raise ProgramValidationError(
|
| 1247 |
+
f"command {command_id} belongs to multiple functions"
|
| 1248 |
+
)
|
| 1249 |
+
owned_commands[command_id] = function.function_id
|
| 1250 |
+
command = commands_by_id[command_id]
|
| 1251 |
+
_known(
|
| 1252 |
+
command.target_symbol_ids,
|
| 1253 |
+
visible,
|
| 1254 |
+
f"command {command_id}.targets in function {function.function_id}",
|
| 1255 |
+
)
|
| 1256 |
+
_known(
|
| 1257 |
+
command.effects.symbol_ids(),
|
| 1258 |
+
visible,
|
| 1259 |
+
f"command {command_id}.effects in function {function.function_id}",
|
| 1260 |
+
)
|
| 1261 |
+
if not command.effects.is_subset_of(function.effects):
|
| 1262 |
+
raise ProgramValidationError(
|
| 1263 |
+
f"command {command_id} effects exceed function "
|
| 1264 |
+
f"{function.function_id} effects"
|
| 1265 |
+
)
|
| 1266 |
+
roots = list(command.expression_ids)
|
| 1267 |
+
roots.extend(item.expression_id for item in command.undefined_behavior)
|
| 1268 |
+
for edge in function.cfg.edges:
|
| 1269 |
+
if (
|
| 1270 |
+
edge.source_block_id
|
| 1271 |
+
in {
|
| 1272 |
+
block.block_id
|
| 1273 |
+
for block in function.cfg.blocks
|
| 1274 |
+
if command_id in block.command_ids
|
| 1275 |
+
}
|
| 1276 |
+
and edge.condition_expression_id
|
| 1277 |
+
):
|
| 1278 |
+
roots.append(edge.condition_expression_id)
|
| 1279 |
+
referenced = self._expression_symbols(roots, expressions_by_id)
|
| 1280 |
+
_known(
|
| 1281 |
+
tuple(referenced),
|
| 1282 |
+
visible,
|
| 1283 |
+
f"command {command_id} expressions in function {function.function_id}",
|
| 1284 |
+
)
|
| 1285 |
+
unowned = sorted(command_ids - set(owned_commands))
|
| 1286 |
+
if unowned:
|
| 1287 |
+
raise ProgramValidationError(f"commands are not owned by a function: {unowned}")
|
| 1288 |
+
scoped_declared = {
|
| 1289 |
+
item.symbol_id
|
| 1290 |
+
for item in self.symbols
|
| 1291 |
+
if item.kind
|
| 1292 |
+
in {
|
| 1293 |
+
SymbolKind.PARAMETER,
|
| 1294 |
+
SymbolKind.LOCAL,
|
| 1295 |
+
SymbolKind.RESULT,
|
| 1296 |
+
SymbolKind.EXCEPTION,
|
| 1297 |
+
}
|
| 1298 |
+
}
|
| 1299 |
+
unowned_symbols = sorted(scoped_declared - used_scoped_symbols)
|
| 1300 |
+
if unowned_symbols:
|
| 1301 |
+
raise ProgramValidationError(
|
| 1302 |
+
f"scoped symbols are not bound to a function: {unowned_symbols}"
|
| 1303 |
+
)
|
| 1304 |
+
|
| 1305 |
+
@staticmethod
|
| 1306 |
+
def _validate_source_map(
|
| 1307 |
+
item: object,
|
| 1308 |
+
source_ids: set[str],
|
| 1309 |
+
spans: Mapping[str, SourceSpan],
|
| 1310 |
+
) -> None:
|
| 1311 |
+
sources = getattr(item, "source_ref_ids")
|
| 1312 |
+
span_ids = getattr(item, "span_ids")
|
| 1313 |
+
_known(sources, source_ids, f"{type(item).__name__}.source_ref_ids")
|
| 1314 |
+
_known(span_ids, set(spans), f"{type(item).__name__}.span_ids")
|
| 1315 |
+
if sources:
|
| 1316 |
+
unlisted = sorted(
|
| 1317 |
+
{
|
| 1318 |
+
spans[span_id].source_ref_id
|
| 1319 |
+
for span_id in span_ids
|
| 1320 |
+
if spans[span_id].source_ref_id not in sources
|
| 1321 |
+
}
|
| 1322 |
+
)
|
| 1323 |
+
if unlisted:
|
| 1324 |
+
raise ProgramValidationError(
|
| 1325 |
+
f"{type(item).__name__} spans belong to unlisted sources {unlisted}"
|
| 1326 |
+
)
|
| 1327 |
+
|
| 1328 |
+
@staticmethod
|
| 1329 |
+
def _reject_expression_cycles(
|
| 1330 |
+
expressions: Mapping[str, ProgramExpression],
|
| 1331 |
+
) -> None:
|
| 1332 |
+
visiting: set[str] = set()
|
| 1333 |
+
visited: set[str] = set()
|
| 1334 |
+
|
| 1335 |
+
def visit(expression_id: str) -> None:
|
| 1336 |
+
if expression_id in visiting:
|
| 1337 |
+
raise ProgramValidationError(f"cyclic expression dependency at {expression_id}")
|
| 1338 |
+
if expression_id in visited:
|
| 1339 |
+
return
|
| 1340 |
+
visiting.add(expression_id)
|
| 1341 |
+
for child in expressions[expression_id].operand_ids:
|
| 1342 |
+
visit(child)
|
| 1343 |
+
visiting.remove(expression_id)
|
| 1344 |
+
visited.add(expression_id)
|
| 1345 |
+
|
| 1346 |
+
for expression_id in expressions:
|
| 1347 |
+
visit(expression_id)
|
| 1348 |
+
|
| 1349 |
+
@staticmethod
|
| 1350 |
+
def _expression_symbols(
|
| 1351 |
+
roots: Sequence[str],
|
| 1352 |
+
expressions: Mapping[str, ProgramExpression],
|
| 1353 |
+
) -> set[str]:
|
| 1354 |
+
symbols: set[str] = set()
|
| 1355 |
+
pending = list(roots)
|
| 1356 |
+
seen: set[str] = set()
|
| 1357 |
+
while pending:
|
| 1358 |
+
current = pending.pop()
|
| 1359 |
+
if current in seen:
|
| 1360 |
+
continue
|
| 1361 |
+
seen.add(current)
|
| 1362 |
+
expression = expressions[current]
|
| 1363 |
+
symbols.update(expression.symbol_ids)
|
| 1364 |
+
pending.extend(expression.operand_ids)
|
| 1365 |
+
return symbols
|
| 1366 |
+
|
| 1367 |
+
@classmethod
|
| 1368 |
+
def from_dict(cls, value: Mapping[str, Any]) -> "ProgramIR":
|
| 1369 |
+
value = _mapping(value, "program")
|
| 1370 |
+
return cls(
|
| 1371 |
+
sources=tuple(
|
| 1372 |
+
SourceRef.from_dict(_mapping(item, "source")) for item in value.get("sources", ())
|
| 1373 |
+
),
|
| 1374 |
+
spans=tuple(
|
| 1375 |
+
SourceSpan.from_dict(_mapping(item, "span")) for item in value.get("spans", ())
|
| 1376 |
+
),
|
| 1377 |
+
symbols=tuple(
|
| 1378 |
+
ProgramSymbol.from_dict(_mapping(item, "symbol"))
|
| 1379 |
+
for item in value.get("symbols", ())
|
| 1380 |
+
),
|
| 1381 |
+
expressions=tuple(
|
| 1382 |
+
ProgramExpression.from_dict(_mapping(item, "expression"))
|
| 1383 |
+
for item in value.get("expressions", ())
|
| 1384 |
+
),
|
| 1385 |
+
commands=tuple(
|
| 1386 |
+
ProgramCommand.from_dict(_mapping(item, "command"))
|
| 1387 |
+
for item in value.get("commands", ())
|
| 1388 |
+
),
|
| 1389 |
+
functions=tuple(
|
| 1390 |
+
ProgramFunction.from_dict(_mapping(item, "function"))
|
| 1391 |
+
for item in value.get("functions", ())
|
| 1392 |
+
),
|
| 1393 |
+
global_symbol_ids=tuple(value.get("global_symbol_ids", ())),
|
| 1394 |
+
metadata=_frozen(_mapping(value.get("metadata", {}), "metadata"), "metadata"),
|
| 1395 |
+
program_id=value.get("program_id", ""),
|
| 1396 |
+
schema_version=value.get("schema_version", PROGRAM_IR_SCHEMA_VERSION),
|
| 1397 |
+
)
|
| 1398 |
+
|
| 1399 |
+
|
| 1400 |
+
# Concise compatibility spellings for consumers that already qualify the module.
|
| 1401 |
+
Expression = ProgramExpression
|
| 1402 |
+
Command = ProgramCommand
|
| 1403 |
+
Function = ProgramFunction
|
| 1404 |
+
CFG = ControlFlowGraph
|
| 1405 |
+
|
| 1406 |
+
|
| 1407 |
+
__all__ = [
|
| 1408 |
+
"PROGRAM_IR_SCHEMA_VERSION",
|
| 1409 |
+
"BasicBlock",
|
| 1410 |
+
"CFG",
|
| 1411 |
+
"Command",
|
| 1412 |
+
"CommandKind",
|
| 1413 |
+
"ControlFlowEdge",
|
| 1414 |
+
"ControlFlowGraph",
|
| 1415 |
+
"EdgeKind",
|
| 1416 |
+
"EffectSummary",
|
| 1417 |
+
"Expression",
|
| 1418 |
+
"ExpressionKind",
|
| 1419 |
+
"Function",
|
| 1420 |
+
"ProgramCommand",
|
| 1421 |
+
"ProgramExpression",
|
| 1422 |
+
"ProgramFunction",
|
| 1423 |
+
"ProgramIR",
|
| 1424 |
+
"ProgramSymbol",
|
| 1425 |
+
"ProgramValidationError",
|
| 1426 |
+
"Purity",
|
| 1427 |
+
"SymbolKind",
|
| 1428 |
+
"UndefinedBehaviorCondition",
|
| 1429 |
+
"UndefinedBehaviorConsequence",
|
| 1430 |
+
]
|
releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py
ADDED
|
@@ -0,0 +1,313 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""Lossless, bounded token grammar for one canonical deontic rule.
|
| 2 |
+
|
| 3 |
+
This is a new codec, not the historical PGIR identifier-bucket tokenizer.
|
| 4 |
+
Source tokens and exact typed target atoms are fitted on training examples
|
| 5 |
+
only. Unknown values and overlong sequences raise; nothing is truncated,
|
| 6 |
+
hashed into identifier buckets, copied from a target, or inferred by a parser.
|
| 7 |
+
Syntax validation grants no semantic qualification or Lake admission.
|
| 8 |
+
"""
|
| 9 |
+
from __future__ import annotations
|
| 10 |
+
|
| 11 |
+
from functools import lru_cache
|
| 12 |
+
import json
|
| 13 |
+
import re
|
| 14 |
+
|
| 15 |
+
from ...logic.legal_ir.canonical_contracts import CanonicalRoundTripIR, CanonicalContractError
|
| 16 |
+
from .legal_ir_grammar_decoder import LegalIRGrammarDecoder
|
| 17 |
+
|
| 18 |
+
SCHEMA = "legal-source-formula-codec/v1"
|
| 19 |
+
MAX_SOURCE_TOKENS = 64
|
| 20 |
+
MAX_TARGET_TOKENS = 64
|
| 21 |
+
MAX_VOCABULARY = 4096
|
| 22 |
+
MAX_EXAMPLES = 4096
|
| 23 |
+
MAX_QUALIFIERS = 4
|
| 24 |
+
SOURCE_PAD = 0
|
| 25 |
+
SOURCE_UNK = 1
|
| 26 |
+
TARGET_PAD = 0
|
| 27 |
+
TARGET_BOS = 1
|
| 28 |
+
TARGET_EOS = 2
|
| 29 |
+
FIELDS = ("modality", "actor", "action", "object", "conditions", "exceptions", "temporal")
|
| 30 |
+
SCALARS = FIELDS[:4]
|
| 31 |
+
QUALIFIERS = FIELDS[4:]
|
| 32 |
+
_SOURCE_RE = re.compile(r"\w+|[^\w\s]", re.UNICODE)
|
| 33 |
+
_MODALITIES = {"O": "obligation", "P": "permission", "F": "prohibition"}
|
| 34 |
+
_POLICY = {
|
| 35 |
+
"source_tokenization": "unicode_casefold_word_or_punctuation/v1",
|
| 36 |
+
"source_unknown": "reject", "target_unknown": "reject",
|
| 37 |
+
"vocabulary_origin": "training_examples_only", "identifier_hashing": False,
|
| 38 |
+
"target_schema": "CanonicalRoundTripIR@1", "rule_count": 1,
|
| 39 |
+
"field_order": list(FIELDS), "qualifiers": "sorted_unique_input_required",
|
| 40 |
+
"max_qualifiers_per_facet": MAX_QUALIFIERS,
|
| 41 |
+
"max_source_tokens": MAX_SOURCE_TOKENS, "max_target_tokens": MAX_TARGET_TOKENS,
|
| 42 |
+
"max_vocabulary": MAX_VOCABULARY,
|
| 43 |
+
"source_pad_id": SOURCE_PAD, "source_unk_id": SOURCE_UNK,
|
| 44 |
+
"target_pad_id": TARGET_PAD, "target_bos_id": TARGET_BOS, "target_eos_id": TARGET_EOS,
|
| 45 |
+
"truncation": "reject", "generation_fallback": "none",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
class CodecError(ValueError):
|
| 50 |
+
"""Unrepresentable, malformed, unknown, or oversized codec input."""
|
| 51 |
+
|
| 52 |
+
|
| 53 |
+
def _json(value):
|
| 54 |
+
return json.dumps(value, ensure_ascii=False, sort_keys=True, separators=(",", ":"), allow_nan=False)
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
def _tag(field):
|
| 58 |
+
return _json(["field", field])
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
def _end(field):
|
| 62 |
+
return _json(["end", field])
|
| 63 |
+
|
| 64 |
+
|
| 65 |
+
def _atom(field, value):
|
| 66 |
+
return _json(["atom", field, value])
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
_STRUCTURAL = ("<pad>", "<bos>", "<eos>") + tuple(
|
| 70 |
+
item for field in FIELDS for item in ((_tag(field), _end(field)) if field in QUALIFIERS else (_tag(field),)))
|
| 71 |
+
|
| 72 |
+
|
| 73 |
+
def _source_tokens(text):
|
| 74 |
+
if type(text) is not str or not text.strip() or len(text) > 16384:
|
| 75 |
+
raise CodecError("source_text must be nonempty text of at most 16384 characters")
|
| 76 |
+
tokens = _SOURCE_RE.findall(text.casefold())
|
| 77 |
+
if not tokens or len(tokens) > MAX_SOURCE_TOKENS:
|
| 78 |
+
raise CodecError("source exceeds 64 tokens; truncation is forbidden")
|
| 79 |
+
if any(len(token) > 512 for token in tokens):
|
| 80 |
+
raise CodecError("source lexeme exceeds 512 characters")
|
| 81 |
+
return tokens
|
| 82 |
+
|
| 83 |
+
|
| 84 |
+
def _rule(canonical_ir):
|
| 85 |
+
if type(canonical_ir) is not dict or set(canonical_ir) != {"rules"}:
|
| 86 |
+
raise CodecError("canonical_ir must contain exactly rules")
|
| 87 |
+
rules = canonical_ir["rules"]
|
| 88 |
+
if type(rules) is not list or len(rules) != 1 or type(rules[0]) is not dict:
|
| 89 |
+
raise CodecError("v1 requires exactly one rule in a rules list")
|
| 90 |
+
rule = rules[0]
|
| 91 |
+
if set(rule) != set(FIELDS):
|
| 92 |
+
raise CodecError("rule must contain exactly the seven canonical facets")
|
| 93 |
+
if any(type(rule[field]) is not str for field in SCALARS):
|
| 94 |
+
raise CodecError("scalar facets require exact strings")
|
| 95 |
+
for field in QUALIFIERS:
|
| 96 |
+
values = rule[field]
|
| 97 |
+
if type(values) is not list or len(values) > MAX_QUALIFIERS or any(type(v) is not str for v in values):
|
| 98 |
+
raise CodecError("qualifier facets require at most four exact string atoms")
|
| 99 |
+
if values != sorted(set(values)):
|
| 100 |
+
raise CodecError("qualifier atoms must already be sorted and unique; normalization is forbidden")
|
| 101 |
+
try:
|
| 102 |
+
validated = CanonicalRoundTripIR.from_dict(canonical_ir).to_dict()
|
| 103 |
+
except (CanonicalContractError, TypeError, ValueError) as error:
|
| 104 |
+
raise CodecError("canonical rule validation failed: " + str(error)) from error
|
| 105 |
+
if validated != canonical_ir:
|
| 106 |
+
raise CodecError("canonical validation would change the supplied IR")
|
| 107 |
+
# PGIR's rule schema uses spelled-out modality and subject. This explicit
|
| 108 |
+
# validation projection is never emitted in place of the canonical payload.
|
| 109 |
+
projected = {"rules": [{**rule, "modality": _MODALITIES[rule["modality"]], "subject": rule["actor"]}]}
|
| 110 |
+
result = LegalIRGrammarDecoder().validate(projected, family="deontic")
|
| 111 |
+
if not result.accepted:
|
| 112 |
+
reasons = ",".join(reason.reason for reason in result.rejection_reasons)
|
| 113 |
+
raise CodecError("deontic grammar rejected rule: " + reasons)
|
| 114 |
+
return rule
|
| 115 |
+
|
| 116 |
+
|
| 117 |
+
@lru_cache(maxsize=16)
|
| 118 |
+
def _vocabularies(source, target):
|
| 119 |
+
"""Compile immutable vocabulary tuples; repeated generation stays cheap."""
|
| 120 |
+
if source[:2] != ("<pad>", "<unk>") or len(source) < 3:
|
| 121 |
+
raise CodecError("source vocabulary must start with PAD0 and UNK1 and contain training tokens")
|
| 122 |
+
if source[2:] != tuple(sorted(set(source[2:]))):
|
| 123 |
+
raise CodecError("source vocabulary must have deterministic unique token order")
|
| 124 |
+
if len(set(source)) != len(source) or len(set(target)) != len(target):
|
| 125 |
+
raise CodecError("vocabulary entries must be unique")
|
| 126 |
+
for token in source[2:]:
|
| 127 |
+
if _source_tokens(token) != [token]:
|
| 128 |
+
raise CodecError("source vocabulary entry is not one casefolded token")
|
| 129 |
+
if target[:len(_STRUCTURAL)] != _STRUCTURAL:
|
| 130 |
+
raise CodecError("target special IDs or structural grammar tags differ")
|
| 131 |
+
atoms = target[len(_STRUCTURAL):]
|
| 132 |
+
if atoms != tuple(sorted(set(atoms))):
|
| 133 |
+
raise CodecError("target atom vocabulary must have deterministic unique token order")
|
| 134 |
+
by_field = {field: [] for field in FIELDS}
|
| 135 |
+
decoded = {}
|
| 136 |
+
for token_id, token in enumerate(target[len(_STRUCTURAL):], len(_STRUCTURAL)):
|
| 137 |
+
try:
|
| 138 |
+
row = json.loads(token)
|
| 139 |
+
except (ValueError, TypeError) as error:
|
| 140 |
+
raise CodecError("target atom must be canonical JSON") from error
|
| 141 |
+
if (type(row) is not list or len(row) != 3 or row[0] != "atom"
|
| 142 |
+
or row[1] not in FIELDS or type(row[2]) is not str or _json(row) != token):
|
| 143 |
+
raise CodecError("target atom must be an exact typed field/string tuple")
|
| 144 |
+
field, value = row[1:]
|
| 145 |
+
trial = {"modality": "O", "actor": "agent", "action": "act", "object": "",
|
| 146 |
+
"conditions": [], "exceptions": [], "temporal": []}
|
| 147 |
+
trial[field] = [value] if field in QUALIFIERS else value
|
| 148 |
+
_rule({"rules": [trial]})
|
| 149 |
+
by_field[field].append((token_id, value))
|
| 150 |
+
decoded[token_id] = (field, value)
|
| 151 |
+
if any(not by_field[field] for field in SCALARS):
|
| 152 |
+
raise CodecError("each scalar field requires at least one training atom")
|
| 153 |
+
return ({token: index for index, token in enumerate(source)},
|
| 154 |
+
{token: index for index, token in enumerate(target)}, by_field, decoded)
|
| 155 |
+
|
| 156 |
+
|
| 157 |
+
def _validated(codec):
|
| 158 |
+
if type(codec) is not dict or set(codec) != {"schema", "source_vocabulary", "target_vocabulary", "policy"}:
|
| 159 |
+
raise CodecError("codec schema fields differ")
|
| 160 |
+
if codec["schema"] != SCHEMA or type(codec["policy"]) is not dict or codec["policy"] != _POLICY:
|
| 161 |
+
raise CodecError("codec version or declared policy differs")
|
| 162 |
+
try:
|
| 163 |
+
if _json(codec["policy"]) != _json(_POLICY):
|
| 164 |
+
raise CodecError("codec policy numeric types differ")
|
| 165 |
+
except (ValueError, TypeError) as error:
|
| 166 |
+
raise CodecError("codec policy must be exact finite JSON") from error
|
| 167 |
+
for name in ("source_vocabulary", "target_vocabulary"):
|
| 168 |
+
values = codec[name]
|
| 169 |
+
if type(values) is not list or not 1 <= len(values) <= MAX_VOCABULARY:
|
| 170 |
+
raise CodecError("each vocabulary must be a list of at most 4096 tokens")
|
| 171 |
+
if any(type(value) is not str or len(value) > 4096 for value in values):
|
| 172 |
+
raise CodecError("vocabulary entries must be bounded strings")
|
| 173 |
+
return _vocabularies(tuple(codec["source_vocabulary"]), tuple(codec["target_vocabulary"]))
|
| 174 |
+
|
| 175 |
+
|
| 176 |
+
def validate_codec(codec):
|
| 177 |
+
"""Validate the exact stored vocabulary, token IDs, limits and policy."""
|
| 178 |
+
_validated(codec)
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def fit_codec(examples):
|
| 182 |
+
"""Freeze vocabularies from explicitly supplied training examples only."""
|
| 183 |
+
if type(examples) is not list or not 1 <= len(examples) <= MAX_EXAMPLES:
|
| 184 |
+
raise CodecError("fit requires between one and 4096 training examples")
|
| 185 |
+
source, target, seen = set(), set(), set()
|
| 186 |
+
for example in examples:
|
| 187 |
+
if type(example) is not dict or set(example) != {"id", "source_text", "canonical_ir"}:
|
| 188 |
+
raise CodecError("training example requires exactly id, source_text and canonical_ir")
|
| 189 |
+
identifier = example["id"]
|
| 190 |
+
if type(identifier) is not str or not identifier.strip() or identifier in seen:
|
| 191 |
+
raise CodecError("training example ids must be unique nonempty strings")
|
| 192 |
+
seen.add(identifier)
|
| 193 |
+
source.update(_source_tokens(example["source_text"]))
|
| 194 |
+
rule = _rule(example["canonical_ir"])
|
| 195 |
+
for field in FIELDS:
|
| 196 |
+
for value in rule[field] if field in QUALIFIERS else [rule[field]]:
|
| 197 |
+
target.add(_atom(field, value))
|
| 198 |
+
if len(source) + 2 > MAX_VOCABULARY or len(target) + len(_STRUCTURAL) > MAX_VOCABULARY:
|
| 199 |
+
raise CodecError("training vocabulary exceeds 4096 tokens")
|
| 200 |
+
codec = {"schema": SCHEMA, "source_vocabulary": ["<pad>", "<unk>", *sorted(source)],
|
| 201 |
+
"target_vocabulary": [*_STRUCTURAL, *sorted(target)], "policy": json.loads(_json(_POLICY))}
|
| 202 |
+
validate_codec(codec)
|
| 203 |
+
for example in examples:
|
| 204 |
+
encode_source(codec, example["source_text"])
|
| 205 |
+
encode_target(codec, example["canonical_ir"])
|
| 206 |
+
return codec
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
def encode_source(codec, text):
|
| 210 |
+
"""Tokenize raw text without a compiler, target, IR or unknown fallback."""
|
| 211 |
+
source_ids = _validated(codec)[0]
|
| 212 |
+
tokens = _source_tokens(text)
|
| 213 |
+
missing = sorted(set(tokens) - source_ids.keys())
|
| 214 |
+
if missing:
|
| 215 |
+
raise CodecError("source contains out-of-vocabulary tokens: " + ", ".join(repr(x) for x in missing[:8]))
|
| 216 |
+
return [source_ids[token] for token in tokens]
|
| 217 |
+
|
| 218 |
+
|
| 219 |
+
def encode_target(codec, canonical_ir):
|
| 220 |
+
target_ids = _validated(codec)[1]
|
| 221 |
+
rule = _rule(canonical_ir)
|
| 222 |
+
pieces = ["<bos>"]
|
| 223 |
+
for field in FIELDS:
|
| 224 |
+
pieces.append(_tag(field))
|
| 225 |
+
pieces.extend(_atom(field, value) for value in (rule[field] if field in QUALIFIERS else [rule[field]]))
|
| 226 |
+
if field in QUALIFIERS:
|
| 227 |
+
pieces.append(_end(field))
|
| 228 |
+
pieces.append("<eos>")
|
| 229 |
+
if len(pieces) > MAX_TARGET_TOKENS:
|
| 230 |
+
raise CodecError("target exceeds 64 tokens; truncation is forbidden")
|
| 231 |
+
missing = [piece for piece in pieces if piece not in target_ids]
|
| 232 |
+
if missing:
|
| 233 |
+
raise CodecError("target contains out-of-vocabulary typed atoms")
|
| 234 |
+
return [target_ids[piece] for piece in pieces]
|
| 235 |
+
|
| 236 |
+
|
| 237 |
+
def _prefix(codec, token_ids):
|
| 238 |
+
_, target_ids, by_field, decoded = _validated(codec)
|
| 239 |
+
if type(token_ids) not in (list, tuple) or len(token_ids) > MAX_TARGET_TOKENS:
|
| 240 |
+
raise CodecError("target prefix must be at most 64 token IDs")
|
| 241 |
+
if any(type(token) is not int or not 0 <= token < len(codec["target_vocabulary"]) for token in token_ids):
|
| 242 |
+
raise CodecError("target token IDs must be exact integers in the vocabulary")
|
| 243 |
+
position, mode, values, rule = 0, "bos", [], {}
|
| 244 |
+
for token_id in token_ids:
|
| 245 |
+
if mode == "bos":
|
| 246 |
+
if token_id != TARGET_BOS:
|
| 247 |
+
raise CodecError("target must begin with BOS")
|
| 248 |
+
mode = "field"
|
| 249 |
+
elif mode == "field":
|
| 250 |
+
field = FIELDS[position]
|
| 251 |
+
if token_id != target_ids[_tag(field)]:
|
| 252 |
+
raise CodecError("target field order or marker differs")
|
| 253 |
+
mode, values = "values", []
|
| 254 |
+
elif mode == "values":
|
| 255 |
+
field = FIELDS[position]
|
| 256 |
+
if field in QUALIFIERS and token_id == target_ids[_end(field)]:
|
| 257 |
+
rule[field] = list(values)
|
| 258 |
+
position += 1
|
| 259 |
+
mode = "eos" if position == len(FIELDS) else "field"
|
| 260 |
+
else:
|
| 261 |
+
atom = decoded.get(token_id)
|
| 262 |
+
if atom is None or atom[0] != field:
|
| 263 |
+
raise CodecError("target atom belongs to another field or is structural")
|
| 264 |
+
value = atom[1]
|
| 265 |
+
if field in QUALIFIERS:
|
| 266 |
+
if len(values) >= MAX_QUALIFIERS or (values and value <= values[-1]):
|
| 267 |
+
raise CodecError("qualifier tokens must be sorted unique and at most four")
|
| 268 |
+
values.append(value)
|
| 269 |
+
else:
|
| 270 |
+
rule[field] = value
|
| 271 |
+
position += 1
|
| 272 |
+
mode = "field"
|
| 273 |
+
elif mode == "eos":
|
| 274 |
+
if token_id != TARGET_EOS:
|
| 275 |
+
raise CodecError("complete target requires EOS")
|
| 276 |
+
mode = "done"
|
| 277 |
+
else:
|
| 278 |
+
raise CodecError("tokens after EOS are forbidden")
|
| 279 |
+
if mode == "bos":
|
| 280 |
+
allowed = [TARGET_BOS]
|
| 281 |
+
elif mode == "field":
|
| 282 |
+
allowed = [target_ids[_tag(FIELDS[position])]]
|
| 283 |
+
elif mode == "values":
|
| 284 |
+
field = FIELDS[position]
|
| 285 |
+
allowed = [token_id for token_id, value in by_field[field]
|
| 286 |
+
if field in SCALARS or (len(values) < MAX_QUALIFIERS and (not values or value > values[-1]))]
|
| 287 |
+
if field in QUALIFIERS:
|
| 288 |
+
allowed.append(target_ids[_end(field)])
|
| 289 |
+
elif mode == "eos":
|
| 290 |
+
allowed = [TARGET_EOS]
|
| 291 |
+
else:
|
| 292 |
+
allowed = []
|
| 293 |
+
return sorted(allowed), rule, mode
|
| 294 |
+
|
| 295 |
+
|
| 296 |
+
def allowed_token_ids(codec, prefix_ids):
|
| 297 |
+
"""Exact next-token grammar; an EOS-only or incomplete rule never passes."""
|
| 298 |
+
return _prefix(codec, prefix_ids)[0]
|
| 299 |
+
|
| 300 |
+
|
| 301 |
+
def decode_target(codec, token_ids):
|
| 302 |
+
"""Parse a complete prediction into exact validated IR, without fallback."""
|
| 303 |
+
_, rule, mode = _prefix(codec, token_ids)
|
| 304 |
+
if mode != "done":
|
| 305 |
+
raise CodecError("target is incomplete; all facets and EOS are required")
|
| 306 |
+
result = {"rules": [rule]}
|
| 307 |
+
_rule(result)
|
| 308 |
+
return result
|
| 309 |
+
|
| 310 |
+
|
| 311 |
+
__all__ = ["SCHEMA", "CodecError", "fit_codec", "validate_codec", "encode_source", "encode_target",
|
| 312 |
+
"decode_target", "allowed_token_ids", "MAX_SOURCE_TOKENS", "MAX_TARGET_TOKENS", "MAX_VOCABULARY",
|
| 313 |
+
"SOURCE_PAD", "SOURCE_UNK", "TARGET_PAD", "TARGET_BOS", "TARGET_EOS"]
|
releases/retained-checkpoints/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930/asset-manifest.json
ADDED
|
@@ -0,0 +1,308 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"checkpoint": {
|
| 3 |
+
"bytes": 304490,
|
| 4 |
+
"path_in_repo": "releases/retained-checkpoints/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930/checkpoint.json",
|
| 5 |
+
"sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
|
| 6 |
+
},
|
| 7 |
+
"codec": null,
|
| 8 |
+
"companion_assets": [],
|
| 9 |
+
"config": {
|
| 10 |
+
"embedding_provenance": {
|
| 11 |
+
"assets": [
|
| 12 |
+
{
|
| 13 |
+
"bytes": 190,
|
| 14 |
+
"name": "1_Pooling/config.json",
|
| 15 |
+
"sha256": "4be450dde3b0273bb9787637cfbd28fe04a7ba6ab9d36ac48e92b11e350ffc23"
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"bytes": 583,
|
| 19 |
+
"name": "config.json",
|
| 20 |
+
"sha256": "00273cdfb3e05c7304d180270bdef8adae45023e7bdfc396338bdd815943dc59"
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"bytes": 66746168,
|
| 24 |
+
"name": "model.safetensors",
|
| 25 |
+
"sha256": "9a1eb90bbac323ea08aa5629b624fe6ae75db121b904799c2266a1e2c2de22d2"
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"bytes": 385,
|
| 29 |
+
"name": "modules.json",
|
| 30 |
+
"sha256": "73348a3d8f8ae4cc5f851dc6b98be3ea819390b814e83656d5eebbadf75fe43e"
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"bytes": 57,
|
| 34 |
+
"name": "sentence_bert_config.json",
|
| 35 |
+
"sha256": "948201d8329907aae938fa62f9ceeed53f5694dacc2b87b9f3b78b37ee986529"
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"bytes": 125,
|
| 39 |
+
"name": "special_tokens_map.json",
|
| 40 |
+
"sha256": "b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3"
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"bytes": 711661,
|
| 44 |
+
"name": "tokenizer.json",
|
| 45 |
+
"sha256": "da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0"
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"bytes": 394,
|
| 49 |
+
"name": "tokenizer_config.json",
|
| 50 |
+
"sha256": "e1790949631401af1bfb6c9c7aeec7fcf612e274d73579d99f704faea40c8ba7"
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"bytes": 231508,
|
| 54 |
+
"name": "vocab.txt",
|
| 55 |
+
"sha256": "07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3"
|
| 56 |
+
}
|
| 57 |
+
],
|
| 58 |
+
"batch_size": 32,
|
| 59 |
+
"device": "cuda",
|
| 60 |
+
"dimension": 384,
|
| 61 |
+
"dtype": "float32",
|
| 62 |
+
"encode_rows_per_second": 2155.864994796075,
|
| 63 |
+
"encode_seconds": 0.890593800926581,
|
| 64 |
+
"load_seconds": 0.6136547059286386,
|
| 65 |
+
"max_tokens_observed": 34,
|
| 66 |
+
"model_id": "thenlper/gte-small",
|
| 67 |
+
"normalized": true,
|
| 68 |
+
"revision": "17e1f347d17fe144873b1201da91788898c639cd",
|
| 69 |
+
"rows": 1920,
|
| 70 |
+
"truncated": false
|
| 71 |
+
},
|
| 72 |
+
"ridges": [
|
| 73 |
+
0.0001,
|
| 74 |
+
0.001,
|
| 75 |
+
0.01,
|
| 76 |
+
0.1
|
| 77 |
+
]
|
| 78 |
+
},
|
| 79 |
+
"contract": null,
|
| 80 |
+
"declaration": {
|
| 81 |
+
"decoder_budget_unit": "fixed schema/scalar slots",
|
| 82 |
+
"development_child_exact": "0/9",
|
| 83 |
+
"development_parent_exact": "9/9",
|
| 84 |
+
"dimension_role": "input_embedding",
|
| 85 |
+
"input_width": 384,
|
| 86 |
+
"parent_pretraining_independence": "unknown",
|
| 87 |
+
"payload_ir_family": "security_ir",
|
| 88 |
+
"promoted": false,
|
| 89 |
+
"receipt": {
|
| 90 |
+
"bytes": 304490,
|
| 91 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/06/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930",
|
| 92 |
+
"sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
|
| 93 |
+
},
|
| 94 |
+
"role": "unpromoted repository child envelope"
|
| 95 |
+
},
|
| 96 |
+
"full_runtime_closure_verified": false,
|
| 97 |
+
"identity": {
|
| 98 |
+
"checkpoint_schema": "codebase-source-384-generation@1",
|
| 99 |
+
"dimension": 384,
|
| 100 |
+
"dimension_role": "input_embedding",
|
| 101 |
+
"donor": null,
|
| 102 |
+
"donor_pins": null,
|
| 103 |
+
"embedded_decoder_schema": "structured-source-384-autoencoder/v1",
|
| 104 |
+
"format_id": null,
|
| 105 |
+
"initialization_only": false,
|
| 106 |
+
"ir_family_id": "codebase_ir",
|
| 107 |
+
"legacy_profile": "codebase_ir/source_conditioned_384_v1",
|
| 108 |
+
"native_codebase_decoder_complete": false,
|
| 109 |
+
"original_checkpoint_pin": {
|
| 110 |
+
"bytes": 304490,
|
| 111 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/06/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930",
|
| 112 |
+
"sha256": "069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930"
|
| 113 |
+
},
|
| 114 |
+
"payload_ir_family": "security_ir",
|
| 115 |
+
"profile_id": null,
|
| 116 |
+
"proof_authority": false,
|
| 117 |
+
"record_id": "ir-model-asset-binding/v1:327b68fdd5889632e5752370a9c168a80ada5597436264fb1d6fb5fc483e778f",
|
| 118 |
+
"retained_status": "borrowed_security_payload_unpromoted",
|
| 119 |
+
"role": "unpromoted repository child envelope",
|
| 120 |
+
"runtime_ready": false,
|
| 121 |
+
"schema_version": null,
|
| 122 |
+
"source_profile_id": null,
|
| 123 |
+
"task_id": null,
|
| 124 |
+
"teacher_qualified": false,
|
| 125 |
+
"trained": null
|
| 126 |
+
},
|
| 127 |
+
"license_scope": {
|
| 128 |
+
"repository_source": "AGPL-3.0, see SOURCE-LICENSE",
|
| 129 |
+
"weights_and_companions": "Original provenance retained; this release supplies no new blanket license grant."
|
| 130 |
+
},
|
| 131 |
+
"numerical_execution_performed": false,
|
| 132 |
+
"original_package": null,
|
| 133 |
+
"schema": "retained-ir-checkpoint-release/v1",
|
| 134 |
+
"source_binding_scope": "listed checkpoint implementation hashes only, not full import/native closure",
|
| 135 |
+
"source_map": [
|
| 136 |
+
{
|
| 137 |
+
"declaration_pointer": "/runtime_sha256",
|
| 138 |
+
"expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
|
| 139 |
+
"original_pin": {
|
| 140 |
+
"bytes": 27328,
|
| 141 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
|
| 142 |
+
"sha256": "3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7"
|
| 143 |
+
},
|
| 144 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py"
|
| 145 |
+
},
|
| 146 |
+
{
|
| 147 |
+
"declaration_pointer": "/shared_runtime/legal_codec_sha256",
|
| 148 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 149 |
+
"original_pin": {
|
| 150 |
+
"bytes": 14622,
|
| 151 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 152 |
+
"sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
|
| 153 |
+
},
|
| 154 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
|
| 155 |
+
},
|
| 156 |
+
{
|
| 157 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.decoder",
|
| 158 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/decoder.py",
|
| 159 |
+
"original_pin": {
|
| 160 |
+
"bytes": 24220,
|
| 161 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/decoder.py",
|
| 162 |
+
"sha256": "7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257"
|
| 163 |
+
},
|
| 164 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257/ipfs_datasets_py/logic/intent_ir/decoder.py"
|
| 165 |
+
},
|
| 166 |
+
{
|
| 167 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.formalize.rich_grammar",
|
| 168 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
|
| 169 |
+
"original_pin": {
|
| 170 |
+
"bytes": 11527,
|
| 171 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
|
| 172 |
+
"sha256": "6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b"
|
| 173 |
+
},
|
| 174 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py"
|
| 175 |
+
},
|
| 176 |
+
{
|
| 177 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.schema",
|
| 178 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/schema.py",
|
| 179 |
+
"original_pin": {
|
| 180 |
+
"bytes": 27163,
|
| 181 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/schema.py",
|
| 182 |
+
"sha256": "93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56"
|
| 183 |
+
},
|
| 184 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56/ipfs_datasets_py/logic/intent_ir/schema.py"
|
| 185 |
+
},
|
| 186 |
+
{
|
| 187 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.security_ir.model",
|
| 188 |
+
"expected_relative_path": "ipfs_datasets_py/logic/security_ir/model.py",
|
| 189 |
+
"original_pin": {
|
| 190 |
+
"bytes": 37220,
|
| 191 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/security_ir/model.py",
|
| 192 |
+
"sha256": "abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39"
|
| 193 |
+
},
|
| 194 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39/ipfs_datasets_py/logic/security_ir/model.py"
|
| 195 |
+
},
|
| 196 |
+
{
|
| 197 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.software_verification.program",
|
| 198 |
+
"expected_relative_path": "ipfs_datasets_py/logic/software_verification/program.py",
|
| 199 |
+
"original_pin": {
|
| 200 |
+
"bytes": 58065,
|
| 201 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/software_verification/program.py",
|
| 202 |
+
"sha256": "f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91"
|
| 203 |
+
},
|
| 204 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91/ipfs_datasets_py/logic/software_verification/program.py"
|
| 205 |
+
},
|
| 206 |
+
{
|
| 207 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.decoder",
|
| 208 |
+
"expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
|
| 209 |
+
"original_pin": {
|
| 210 |
+
"bytes": 7300,
|
| 211 |
+
"path": "/home/barberb/lift_coding/artifacts/ir-original-corpus-replay-20261003/inputs/legal-original/ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
|
| 212 |
+
"sha256": "21e8315b0054f7755512212d610d4e3f5f4ac86387f3b27edb9632fa8ca68bc3"
|
| 213 |
+
},
|
| 214 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/21e8315b0054f7755512212d610d4e3f5f4ac86387f3b27edb9632fa8ca68bc3/ipfs_datasets_py/logic/ui_ux_ir/decoder.py"
|
| 215 |
+
},
|
| 216 |
+
{
|
| 217 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.schema",
|
| 218 |
+
"expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/schema.py",
|
| 219 |
+
"original_pin": {
|
| 220 |
+
"bytes": 120714,
|
| 221 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/ui_ux_ir/schema.py",
|
| 222 |
+
"sha256": "8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855"
|
| 223 |
+
},
|
| 224 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855/ipfs_datasets_py/logic/ui_ux_ir/schema.py"
|
| 225 |
+
},
|
| 226 |
+
{
|
| 227 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.optimizers.logic_theorem_optimizer.modal_latent_formula",
|
| 228 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 229 |
+
"original_pin": {
|
| 230 |
+
"bytes": 35427,
|
| 231 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 232 |
+
"sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
|
| 233 |
+
},
|
| 234 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
|
| 235 |
+
},
|
| 236 |
+
{
|
| 237 |
+
"declaration_pointer": "/shared_runtime/native/runtime",
|
| 238 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
|
| 239 |
+
"original_pin": {
|
| 240 |
+
"bytes": 34679,
|
| 241 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
|
| 242 |
+
"sha256": "66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6"
|
| 243 |
+
},
|
| 244 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py"
|
| 245 |
+
},
|
| 246 |
+
{
|
| 247 |
+
"declaration_pointer": "/shared_runtime/numerical/files/canonical_contracts.py",
|
| 248 |
+
"expected_relative_path": "ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
|
| 249 |
+
"original_pin": {
|
| 250 |
+
"bytes": 109257,
|
| 251 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
|
| 252 |
+
"sha256": "d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b"
|
| 253 |
+
},
|
| 254 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py"
|
| 255 |
+
},
|
| 256 |
+
{
|
| 257 |
+
"declaration_pointer": "/shared_runtime/numerical/files/legal_formula_codec.py",
|
| 258 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 259 |
+
"original_pin": {
|
| 260 |
+
"bytes": 14622,
|
| 261 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 262 |
+
"sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
|
| 263 |
+
},
|
| 264 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
|
| 265 |
+
},
|
| 266 |
+
{
|
| 267 |
+
"declaration_pointer": "/shared_runtime/numerical/files/legal_ir_grammar_decoder.py",
|
| 268 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
|
| 269 |
+
"original_pin": {
|
| 270 |
+
"bytes": 146870,
|
| 271 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
|
| 272 |
+
"sha256": "0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd"
|
| 273 |
+
},
|
| 274 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py"
|
| 275 |
+
},
|
| 276 |
+
{
|
| 277 |
+
"declaration_pointer": "/shared_runtime/numerical/files/modal_latent_formula.py",
|
| 278 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 279 |
+
"original_pin": {
|
| 280 |
+
"bytes": 35427,
|
| 281 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 282 |
+
"sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
|
| 283 |
+
},
|
| 284 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
|
| 285 |
+
},
|
| 286 |
+
{
|
| 287 |
+
"declaration_pointer": "/shared_runtime/numerical/files/tree_pin.py",
|
| 288 |
+
"expected_relative_path": "ipfs_datasets_py/logic/autoformal/tree_pin.py",
|
| 289 |
+
"original_pin": {
|
| 290 |
+
"bytes": 1948,
|
| 291 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/autoformal/tree_pin.py",
|
| 292 |
+
"sha256": "587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d"
|
| 293 |
+
},
|
| 294 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d/ipfs_datasets_py/logic/autoformal/tree_pin.py"
|
| 295 |
+
},
|
| 296 |
+
{
|
| 297 |
+
"declaration_pointer": "/shared_runtime/runtime_sha256",
|
| 298 |
+
"expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
|
| 299 |
+
"original_pin": {
|
| 300 |
+
"bytes": 31851,
|
| 301 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
|
| 302 |
+
"sha256": "8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4"
|
| 303 |
+
},
|
| 304 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py"
|
| 305 |
+
}
|
| 306 |
+
],
|
| 307 |
+
"unknown_schema_task_profile_policy": "Unknown fields remain null; no family-only alias or default serving route."
|
| 308 |
+
}
|
releases/retained-checkpoints/069458d8266e0ffce07415e49b8b2ae87dcca4374e5a9aec43844b6c69e85930/checkpoint.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|
releases/retained-checkpoints/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f/asset-manifest.json
ADDED
|
@@ -0,0 +1,306 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"checkpoint": {
|
| 3 |
+
"bytes": 1009515,
|
| 4 |
+
"path_in_repo": "releases/retained-checkpoints/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f/checkpoint.json",
|
| 5 |
+
"sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
|
| 6 |
+
},
|
| 7 |
+
"codec": null,
|
| 8 |
+
"companion_assets": [],
|
| 9 |
+
"config": {
|
| 10 |
+
"embedding_provenance": {
|
| 11 |
+
"assets": [
|
| 12 |
+
{
|
| 13 |
+
"bytes": 190,
|
| 14 |
+
"name": "1_Pooling/config.json",
|
| 15 |
+
"sha256": "4be450dde3b0273bb9787637cfbd28fe04a7ba6ab9d36ac48e92b11e350ffc23"
|
| 16 |
+
},
|
| 17 |
+
{
|
| 18 |
+
"bytes": 583,
|
| 19 |
+
"name": "config.json",
|
| 20 |
+
"sha256": "00273cdfb3e05c7304d180270bdef8adae45023e7bdfc396338bdd815943dc59"
|
| 21 |
+
},
|
| 22 |
+
{
|
| 23 |
+
"bytes": 66746168,
|
| 24 |
+
"name": "model.safetensors",
|
| 25 |
+
"sha256": "9a1eb90bbac323ea08aa5629b624fe6ae75db121b904799c2266a1e2c2de22d2"
|
| 26 |
+
},
|
| 27 |
+
{
|
| 28 |
+
"bytes": 385,
|
| 29 |
+
"name": "modules.json",
|
| 30 |
+
"sha256": "73348a3d8f8ae4cc5f851dc6b98be3ea819390b814e83656d5eebbadf75fe43e"
|
| 31 |
+
},
|
| 32 |
+
{
|
| 33 |
+
"bytes": 57,
|
| 34 |
+
"name": "sentence_bert_config.json",
|
| 35 |
+
"sha256": "948201d8329907aae938fa62f9ceeed53f5694dacc2b87b9f3b78b37ee986529"
|
| 36 |
+
},
|
| 37 |
+
{
|
| 38 |
+
"bytes": 125,
|
| 39 |
+
"name": "special_tokens_map.json",
|
| 40 |
+
"sha256": "b6d346be366a7d1d48332dbc9fdf3bf8960b5d879522b7799ddba59e76237ee3"
|
| 41 |
+
},
|
| 42 |
+
{
|
| 43 |
+
"bytes": 711661,
|
| 44 |
+
"name": "tokenizer.json",
|
| 45 |
+
"sha256": "da0e79933b9ed51798a3ae27893d3c5fa4a201126cef75586296df9b4d2c62a0"
|
| 46 |
+
},
|
| 47 |
+
{
|
| 48 |
+
"bytes": 394,
|
| 49 |
+
"name": "tokenizer_config.json",
|
| 50 |
+
"sha256": "e1790949631401af1bfb6c9c7aeec7fcf612e274d73579d99f704faea40c8ba7"
|
| 51 |
+
},
|
| 52 |
+
{
|
| 53 |
+
"bytes": 231508,
|
| 54 |
+
"name": "vocab.txt",
|
| 55 |
+
"sha256": "07eced375cec144d27c900241f3e339478dec958f92fddbc551f295c992038a3"
|
| 56 |
+
}
|
| 57 |
+
],
|
| 58 |
+
"batch_size": 32,
|
| 59 |
+
"device": "cuda",
|
| 60 |
+
"dimension": 384,
|
| 61 |
+
"dtype": "float32",
|
| 62 |
+
"encode_rows_per_second": 2155.864994796075,
|
| 63 |
+
"encode_seconds": 0.890593800926581,
|
| 64 |
+
"load_seconds": 0.6136547059286386,
|
| 65 |
+
"max_tokens_observed": 34,
|
| 66 |
+
"model_id": "thenlper/gte-small",
|
| 67 |
+
"normalized": true,
|
| 68 |
+
"revision": "17e1f347d17fe144873b1201da91788898c639cd",
|
| 69 |
+
"rows": 1920,
|
| 70 |
+
"truncated": false
|
| 71 |
+
},
|
| 72 |
+
"ridges": [
|
| 73 |
+
0.0001,
|
| 74 |
+
0.001,
|
| 75 |
+
0.01,
|
| 76 |
+
0.1
|
| 77 |
+
]
|
| 78 |
+
},
|
| 79 |
+
"contract": null,
|
| 80 |
+
"declaration": {
|
| 81 |
+
"decoder_kind": "frozen projection and fixed-tree ridge readout",
|
| 82 |
+
"dimension_role": "input_embedding",
|
| 83 |
+
"input_width": 384,
|
| 84 |
+
"native_codebase_decoder_complete": false,
|
| 85 |
+
"owning_ir_family": "codebase_ir",
|
| 86 |
+
"payload_ir_family": "security_ir",
|
| 87 |
+
"receipt": {
|
| 88 |
+
"bytes": 1009515,
|
| 89 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/cc/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f",
|
| 90 |
+
"sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
|
| 91 |
+
},
|
| 92 |
+
"role": "registered shared parent envelope"
|
| 93 |
+
},
|
| 94 |
+
"full_runtime_closure_verified": false,
|
| 95 |
+
"identity": {
|
| 96 |
+
"checkpoint_schema": "codebase-source-384-generation@1",
|
| 97 |
+
"dimension": 384,
|
| 98 |
+
"dimension_role": "input_embedding",
|
| 99 |
+
"donor": null,
|
| 100 |
+
"donor_pins": null,
|
| 101 |
+
"embedded_decoder_schema": "structured-source-384-autoencoder/v1",
|
| 102 |
+
"format_id": null,
|
| 103 |
+
"initialization_only": false,
|
| 104 |
+
"ir_family_id": "codebase_ir",
|
| 105 |
+
"legacy_profile": "codebase_ir/source_conditioned_384_v1",
|
| 106 |
+
"native_codebase_decoder_complete": false,
|
| 107 |
+
"original_checkpoint_pin": {
|
| 108 |
+
"bytes": 1009515,
|
| 109 |
+
"path": "/home/barberb/lift_coding/artifacts/codebase-source384-20261002/qualified-02/test_real_fit_registry_replay_current/models/cc/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f",
|
| 110 |
+
"sha256": "cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f"
|
| 111 |
+
},
|
| 112 |
+
"payload_ir_family": "security_ir",
|
| 113 |
+
"profile_id": null,
|
| 114 |
+
"proof_authority": false,
|
| 115 |
+
"record_id": "ir-model-asset-binding/v1:40237a9b6a4dd5723f36fcd80a37ba4d4cadb59067bc2de399c72ea9f96a99d2",
|
| 116 |
+
"retained_status": "borrowed_security_payload_unpromoted",
|
| 117 |
+
"role": "registered shared parent envelope",
|
| 118 |
+
"runtime_ready": false,
|
| 119 |
+
"schema_version": null,
|
| 120 |
+
"source_profile_id": null,
|
| 121 |
+
"task_id": null,
|
| 122 |
+
"teacher_qualified": false,
|
| 123 |
+
"trained": null
|
| 124 |
+
},
|
| 125 |
+
"license_scope": {
|
| 126 |
+
"repository_source": "AGPL-3.0, see SOURCE-LICENSE",
|
| 127 |
+
"weights_and_companions": "Original provenance retained; this release supplies no new blanket license grant."
|
| 128 |
+
},
|
| 129 |
+
"numerical_execution_performed": false,
|
| 130 |
+
"original_package": null,
|
| 131 |
+
"schema": "retained-ir-checkpoint-release/v1",
|
| 132 |
+
"source_binding_scope": "listed checkpoint implementation hashes only, not full import/native closure",
|
| 133 |
+
"source_map": [
|
| 134 |
+
{
|
| 135 |
+
"declaration_pointer": "/runtime_sha256",
|
| 136 |
+
"expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
|
| 137 |
+
"original_pin": {
|
| 138 |
+
"bytes": 27328,
|
| 139 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py",
|
| 140 |
+
"sha256": "3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7"
|
| 141 |
+
},
|
| 142 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/3f9ca9ce7b4cf2a2d10d6aeb1fae78543c468133d2fa0df9fcb32f63f89e90f7/ipfs_datasets_py/logic/formalization/autoencoder/structured_source_384.py"
|
| 143 |
+
},
|
| 144 |
+
{
|
| 145 |
+
"declaration_pointer": "/shared_runtime/legal_codec_sha256",
|
| 146 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 147 |
+
"original_pin": {
|
| 148 |
+
"bytes": 14622,
|
| 149 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 150 |
+
"sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
|
| 151 |
+
},
|
| 152 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
|
| 153 |
+
},
|
| 154 |
+
{
|
| 155 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.decoder",
|
| 156 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/decoder.py",
|
| 157 |
+
"original_pin": {
|
| 158 |
+
"bytes": 24220,
|
| 159 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/decoder.py",
|
| 160 |
+
"sha256": "7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257"
|
| 161 |
+
},
|
| 162 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/7bab5781c07e00b54b0283d3a2962926f75935caedc80eceb23264cb388be257/ipfs_datasets_py/logic/intent_ir/decoder.py"
|
| 163 |
+
},
|
| 164 |
+
{
|
| 165 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.formalize.rich_grammar",
|
| 166 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
|
| 167 |
+
"original_pin": {
|
| 168 |
+
"bytes": 11527,
|
| 169 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py",
|
| 170 |
+
"sha256": "6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b"
|
| 171 |
+
},
|
| 172 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/6c40ac99d7e339651b6029764f94b12430ca515d4c5f7426770b013499efe92b/ipfs_datasets_py/logic/intent_ir/formalize/rich_grammar.py"
|
| 173 |
+
},
|
| 174 |
+
{
|
| 175 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.intent_ir.schema",
|
| 176 |
+
"expected_relative_path": "ipfs_datasets_py/logic/intent_ir/schema.py",
|
| 177 |
+
"original_pin": {
|
| 178 |
+
"bytes": 27163,
|
| 179 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/intent_ir/schema.py",
|
| 180 |
+
"sha256": "93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56"
|
| 181 |
+
},
|
| 182 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/93d38e4724c5f34aab7f39f050742e98ef0c8d80e2ff70459d2401541505fc56/ipfs_datasets_py/logic/intent_ir/schema.py"
|
| 183 |
+
},
|
| 184 |
+
{
|
| 185 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.security_ir.model",
|
| 186 |
+
"expected_relative_path": "ipfs_datasets_py/logic/security_ir/model.py",
|
| 187 |
+
"original_pin": {
|
| 188 |
+
"bytes": 37220,
|
| 189 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/security_ir/model.py",
|
| 190 |
+
"sha256": "abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39"
|
| 191 |
+
},
|
| 192 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/abc3aea9c2f4d1ce513ee2c9fc4c304d8bd387ded18e0d646247417422225d39/ipfs_datasets_py/logic/security_ir/model.py"
|
| 193 |
+
},
|
| 194 |
+
{
|
| 195 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.software_verification.program",
|
| 196 |
+
"expected_relative_path": "ipfs_datasets_py/logic/software_verification/program.py",
|
| 197 |
+
"original_pin": {
|
| 198 |
+
"bytes": 58065,
|
| 199 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/software_verification/program.py",
|
| 200 |
+
"sha256": "f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91"
|
| 201 |
+
},
|
| 202 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f051f42d64c5f993451972924953cc7eaa6d17df097235ddabfd5d791d406f91/ipfs_datasets_py/logic/software_verification/program.py"
|
| 203 |
+
},
|
| 204 |
+
{
|
| 205 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.decoder",
|
| 206 |
+
"expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
|
| 207 |
+
"original_pin": {
|
| 208 |
+
"bytes": 8008,
|
| 209 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/ui_ux_ir/decoder.py",
|
| 210 |
+
"sha256": "d7be6bff3a1f1464d4783567b90942258ef718bc1c2b7e02938698ed4e619e57"
|
| 211 |
+
},
|
| 212 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/d7be6bff3a1f1464d4783567b90942258ef718bc1c2b7e02938698ed4e619e57/ipfs_datasets_py/logic/ui_ux_ir/decoder.py"
|
| 213 |
+
},
|
| 214 |
+
{
|
| 215 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.logic.ui_ux_ir.schema",
|
| 216 |
+
"expected_relative_path": "ipfs_datasets_py/logic/ui_ux_ir/schema.py",
|
| 217 |
+
"original_pin": {
|
| 218 |
+
"bytes": 120714,
|
| 219 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/ui_ux_ir/schema.py",
|
| 220 |
+
"sha256": "8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855"
|
| 221 |
+
},
|
| 222 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8a7b0cc90151043514d263b1a2655d6d41a2835dacd6b56018ba5c0c89961855/ipfs_datasets_py/logic/ui_ux_ir/schema.py"
|
| 223 |
+
},
|
| 224 |
+
{
|
| 225 |
+
"declaration_pointer": "/shared_runtime/native/dependencies/ipfs_datasets_py.optimizers.logic_theorem_optimizer.modal_latent_formula",
|
| 226 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 227 |
+
"original_pin": {
|
| 228 |
+
"bytes": 35427,
|
| 229 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 230 |
+
"sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
|
| 231 |
+
},
|
| 232 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
|
| 233 |
+
},
|
| 234 |
+
{
|
| 235 |
+
"declaration_pointer": "/shared_runtime/native/runtime",
|
| 236 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
|
| 237 |
+
"original_pin": {
|
| 238 |
+
"bytes": 34679,
|
| 239 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py",
|
| 240 |
+
"sha256": "66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6"
|
| 241 |
+
},
|
| 242 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/66c5ee320f9c7aacd3b246d0666c7fc3ee928e4679892e1e90c838e1b291dbc6/ipfs_datasets_py/optimizers/logic_theorem_optimizer/domain_384_autoencoder.py"
|
| 243 |
+
},
|
| 244 |
+
{
|
| 245 |
+
"declaration_pointer": "/shared_runtime/numerical/files/canonical_contracts.py",
|
| 246 |
+
"expected_relative_path": "ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
|
| 247 |
+
"original_pin": {
|
| 248 |
+
"bytes": 109257,
|
| 249 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py",
|
| 250 |
+
"sha256": "d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b"
|
| 251 |
+
},
|
| 252 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/d66ecfaa2c967cda40a1cf4b82936a34039e38ccdb3044468697a4f90af2844b/ipfs_datasets_py/logic/legal_ir/canonical_contracts.py"
|
| 253 |
+
},
|
| 254 |
+
{
|
| 255 |
+
"declaration_pointer": "/shared_runtime/numerical/files/legal_formula_codec.py",
|
| 256 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 257 |
+
"original_pin": {
|
| 258 |
+
"bytes": 14622,
|
| 259 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py",
|
| 260 |
+
"sha256": "f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290"
|
| 261 |
+
},
|
| 262 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/f90769a3d99131da5ba48bb84c6f830f521c92d98122bdaaa8dd88fc65042290/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_formula_codec.py"
|
| 263 |
+
},
|
| 264 |
+
{
|
| 265 |
+
"declaration_pointer": "/shared_runtime/numerical/files/legal_ir_grammar_decoder.py",
|
| 266 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
|
| 267 |
+
"original_pin": {
|
| 268 |
+
"bytes": 146870,
|
| 269 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py",
|
| 270 |
+
"sha256": "0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd"
|
| 271 |
+
},
|
| 272 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/0b1eae24b00157ae74a2700f23ca95c7f9957dc755078caaf179e64070fdeffd/ipfs_datasets_py/optimizers/logic_theorem_optimizer/legal_ir_grammar_decoder.py"
|
| 273 |
+
},
|
| 274 |
+
{
|
| 275 |
+
"declaration_pointer": "/shared_runtime/numerical/files/modal_latent_formula.py",
|
| 276 |
+
"expected_relative_path": "ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 277 |
+
"original_pin": {
|
| 278 |
+
"bytes": 35427,
|
| 279 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py",
|
| 280 |
+
"sha256": "ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36"
|
| 281 |
+
},
|
| 282 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/ec5bdcd752d157c9fc0257a45551cfe9ce7be172af767e8ed769bf1bc8a31d36/ipfs_datasets_py/optimizers/logic_theorem_optimizer/modal_latent_formula.py"
|
| 283 |
+
},
|
| 284 |
+
{
|
| 285 |
+
"declaration_pointer": "/shared_runtime/numerical/files/tree_pin.py",
|
| 286 |
+
"expected_relative_path": "ipfs_datasets_py/logic/autoformal/tree_pin.py",
|
| 287 |
+
"original_pin": {
|
| 288 |
+
"bytes": 1948,
|
| 289 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/autoformal/tree_pin.py",
|
| 290 |
+
"sha256": "587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d"
|
| 291 |
+
},
|
| 292 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/587165942fb06ea9effc836b555e0ac0606c5876b013a374a1e76d25ee069e4d/ipfs_datasets_py/logic/autoformal/tree_pin.py"
|
| 293 |
+
},
|
| 294 |
+
{
|
| 295 |
+
"declaration_pointer": "/shared_runtime/runtime_sha256",
|
| 296 |
+
"expected_relative_path": "ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
|
| 297 |
+
"original_pin": {
|
| 298 |
+
"bytes": 31851,
|
| 299 |
+
"path": "/home/barberb/lift_coding/artifacts/legal-ir-inference-speed-review/audit/baseline_tree/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py",
|
| 300 |
+
"sha256": "8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4"
|
| 301 |
+
},
|
| 302 |
+
"path_in_repo": "releases/20261004-retained-checkpoints-v1/source/8de8096e895de9df08ccf5352dfd704806823296821d98b5badf08bb553a52e4/ipfs_datasets_py/logic/formalization/autoencoder/source_training_v2.py"
|
| 303 |
+
}
|
| 304 |
+
],
|
| 305 |
+
"unknown_schema_task_profile_policy": "Unknown fields remain null; no family-only alias or default serving route."
|
| 306 |
+
}
|
releases/retained-checkpoints/cc025fbc017849b806d60f191397fa03759f732a8406cbdcb3558ba3871b2a6f/checkpoint.json
ADDED
|
The diff for this file is too large to render.
See raw diff
|
|
|