cscs-constraint-engine 2026.10.2__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- cscs_constraint_engine-2026.10.2/LICENSE +201 -0
- cscs_constraint_engine-2026.10.2/NOTICE +10 -0
- cscs_constraint_engine-2026.10.2/PKG-INFO +120 -0
- cscs_constraint_engine-2026.10.2/README.md +105 -0
- cscs_constraint_engine-2026.10.2/cscs/__init__.py +24 -0
- cscs_constraint_engine-2026.10.2/cscs/codec.py +82 -0
- cscs_constraint_engine-2026.10.2/cscs/compression.py +94 -0
- cscs_constraint_engine-2026.10.2/cscs/contraction.py +137 -0
- cscs_constraint_engine-2026.10.2/cscs/engine.py +331 -0
- cscs_constraint_engine-2026.10.2/cscs/manifold.py +215 -0
- cscs_constraint_engine-2026.10.2/cscs/scout.py +98 -0
- cscs_constraint_engine-2026.10.2/cscs/verifier.py +78 -0
- cscs_constraint_engine-2026.10.2/cscs_constraint_engine.egg-info/PKG-INFO +120 -0
- cscs_constraint_engine-2026.10.2/cscs_constraint_engine.egg-info/SOURCES.txt +18 -0
- cscs_constraint_engine-2026.10.2/cscs_constraint_engine.egg-info/dependency_links.txt +1 -0
- cscs_constraint_engine-2026.10.2/cscs_constraint_engine.egg-info/requires.txt +1 -0
- cscs_constraint_engine-2026.10.2/cscs_constraint_engine.egg-info/top_level.txt +1 -0
- cscs_constraint_engine-2026.10.2/pyproject.toml +21 -0
- cscs_constraint_engine-2026.10.2/setup.cfg +4 -0
- cscs_constraint_engine-2026.10.2/tests/test_math_invariants.py +156 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright [yyyy] [name of copyright owner]
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
CSCS Constraint Physics Engine
|
|
2
|
+
Copyright 2024-2026 Lazaro M. Echenique-Diaz, Ph.D.
|
|
3
|
+
|
|
4
|
+
This product includes software developed by Lazaro M. Echenique-Diaz, Ph.D.
|
|
5
|
+
(Yamagata University) as part of the CSCS Constraint State Physics research project.
|
|
6
|
+
|
|
7
|
+
ATTRIBUTION NOTICE (Apache License 2.0, Section 4d):
|
|
8
|
+
Any derivative work, distribution, or commercial integration of this software
|
|
9
|
+
must retain attribution to the original author (Lazaro M. Echenique-Diaz, Ph.D.)
|
|
10
|
+
and cite the project repository as specified in CITATION.cff.
|
|
@@ -0,0 +1,120 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: cscs-constraint-engine
|
|
3
|
+
Version: 2026.10.2
|
|
4
|
+
Summary: CSCS Constraint Physics Engine: Zero-GPU Spectral Manifold & Contractive Telemetry Middleware for Small Language Models (SLMs)
|
|
5
|
+
Author-email: "Lazaro M. Echenique-Diaz, Ph.D." <lazincip@gmail.com>
|
|
6
|
+
License: Apache-2.0
|
|
7
|
+
Project-URL: Repository, https://github.com/lazincip/cscs-constraint-engine
|
|
8
|
+
Keywords: SLM,LLM,guardrails,manifold,SVD,Banach-contraction,edge-AI,Ollama
|
|
9
|
+
Requires-Python: >=3.9
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
License-File: NOTICE
|
|
13
|
+
Requires-Dist: numpy>=1.22.0
|
|
14
|
+
Dynamic: license-file
|
|
15
|
+
|
|
16
|
+
# CSCS Constraint Physics Engine (`v2026.10.2`)
|
|
17
|
+
|
|
18
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
19
|
+
[](https://www.python.org/)
|
|
20
|
+
[-brightgreen.svg)](#quickstart)
|
|
21
|
+
[](https://doi.org/10.5281/zenodo.23750262)
|
|
22
|
+
|
|
23
|
+
**A zero-GPU governor for Small Language Models.** It sits in front of a local SLM (Llama-3.2, Qwen-2.5, Phi-4, Gemma-2), scores prompts *before* they burn inference, tracks multi-turn drift, and audits outputs for confabulation — on one CPU thread, with **numpy only** and **0 MB VRAM**. Latency is environment-dependent; on the reference VM (Linux, Python 3.12.3, numpy 1.26.4) the v2026.10.2 gate measures **2.6 ms median / 3.4 ms P95 per turn across 300-turn sessions** (see [Operating Envelope](#operating-envelope) — earlier releases measured lower on other hardware; no cross-machine latency claim is made).
|
|
24
|
+
|
|
25
|
+
*Created by **Lazaro M. Echenique-Diaz, Ph.D.*** · Concepts descend from evolutionary biology — see [Ecological Models & Origins](docs/ECOLOGICAL_MODELS_AND_ORIGINS.md).
|
|
26
|
+
|
|
27
|
+
> **Note on nomenclature:** **CSCS** stands for **Constraint Space Coordinate System** — an independent open-source edge-AI middleware project created at Yamagata University, unrelated to the Swiss National Supercomputing Centre (CSCS, Lugano).
|
|
28
|
+
|
|
29
|
+
---
|
|
30
|
+
|
|
31
|
+
## Why
|
|
32
|
+
|
|
33
|
+
Neural guardrails (LlamaGuard, NeMo) need a **second neural network** in VRAM — 1.5–4 GB a small edge device can't spare. Quantized SLMs also drift over long chats and invent citations, dates, and percentages when uncertain. This engine replaces the second model with linear algebra: a spectral manifold, a contraction mirror, and a friction field.
|
|
34
|
+
|
|
35
|
+
The engine's first-stage discipline is **trajectory discipline**: a prompt is judged not only by what it contains, but by where the session has been — whether it continues the anchored trajectory of the conversation or breaks from it. Cross-model audit (2026-11) confirmed empirically that this history-relative signal (resonance collapse against the session anchors), not lexical content alone, is the engine's load-bearing discriminator; v2026.10.2 rebuilds the gate around that finding.
|
|
36
|
+
|
|
37
|
+
## Intended Use & Non-Goals
|
|
38
|
+
|
|
39
|
+
**Intended use:** Trajectory governance, drift telemetry, and confabulation auditing for a **known, deliberately seeded domain** on operator-controlled hardware — e.g. a university lab SLM answering questions about an enrolled research corpus, an offline field assistant constrained to an enrolled manual set, or a long-running local agent whose session must stay anchored to an operator-defined topic manifold.
|
|
40
|
+
|
|
41
|
+
**Non-goals:** This engine is **not** a general-purpose chat filter, content-moderation system, or safety boundary for arbitrary open-domain conversation. A deployment whose domain is everything has no manifold to anchor to, and the gate's scores carry no meaning there. Operators enroll a seed corpus, choose the learning policy, and remain responsible for the deployment's content policy.
|
|
42
|
+
|
|
43
|
+
## How it flows
|
|
44
|
+
|
|
45
|
+
```mermaid
|
|
46
|
+
flowchart LR
|
|
47
|
+
P[Prompt] --> Q{Quality gate<br/>score ≥ 0.30?}
|
|
48
|
+
Q -- No --> B[BLOCKED<br/>compute saved]
|
|
49
|
+
Q -- Yes --> M[SpectralManifold<br/>centered SVD residual ∈ [0, 1]]
|
|
50
|
+
M --> C[BanachContractionMirror<br/>anchor-weighted resonance · Lyapunov λ]
|
|
51
|
+
C --> S[RBFConstraintScout<br/>friction field]
|
|
52
|
+
S --> W{Wall?<br/>adaptive: friction > 1/φ ≈ 0.618<br/>calibrated: friction > τ₉₅}
|
|
53
|
+
W -- Yes, not dreaming --> B
|
|
54
|
+
W -- No / dreaming --> SLM[SLM inference<br/>Ollama · llama.cpp · MLX]
|
|
55
|
+
SLM --> V[DriftVerifier]
|
|
56
|
+
V --> VS[VERIFIED]
|
|
57
|
+
V --> VD[SANCTIONED_DREAM]
|
|
58
|
+
V --> VR[SPORADIC_RISK]
|
|
59
|
+
M -.-> T[T3LB seed<br/>93 bytes · 13-D state]
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
**State policy (v2026.10.2).** Blocked prompts mutate nothing. In the calibrated state, an allowed prompt commits state (mirror, scout, manifold) only if it lies in the **core attractor zone** — its anchor-only friction is at most $1/\Phi$; prompts in the tolerated band ($\Phi^{-1} < F \le \tau_{95}$) execute but change nothing, so long sessions cannot drift the judging state. Enrollment anchors the contraction mirror from the first cycle, and the engine **graduates automatically** from its adaptive policy (fixed $1/\Phi$ wall) to the calibrated policy (session-specific $\tau_{95}$, the leave-one-out 95th-percentile anchor friction) as soon as that wall is estimable from the anchored mirror vectors.
|
|
63
|
+
|
|
64
|
+
## Quickstart
|
|
65
|
+
|
|
66
|
+
```bash
|
|
67
|
+
git clone https://github.com/lazincip/cscs-constraint-engine.git
|
|
68
|
+
cd cscs-constraint-engine
|
|
69
|
+
pip install -e .
|
|
70
|
+
|
|
71
|
+
python -m unittest discover -s tests -v # 6 invariant + regression tests
|
|
72
|
+
python examples/slm_ollama_middleware.py # simulation demo, no server needed
|
|
73
|
+
python examples/slm_ollama_middleware.py --live --model qwen2.5:3b # live Ollama
|
|
74
|
+
python benchmarks/run_track_a.py # committed Track A control battery
|
|
75
|
+
```
|
|
76
|
+
|
|
77
|
+
What the demo shows (verified run, v2026.10.2):
|
|
78
|
+
|
|
79
|
+
```text
|
|
80
|
+
[Turn 1] Summarize the divergence timeline of Solenodon cubanus...
|
|
81
|
+
Pre-Inference Gate : ALLOWED | Resonance 0.526
|
|
82
|
+
Post-Inference : VERIFIED (sporadic_risk = 0.295)
|
|
83
|
+
[Turn 4] buy cheap crypto tokens instant 100x pump free airdrop...
|
|
84
|
+
Pre-Inference Gate : BLOCKED (Compute Saved) | Resonance 0.239
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
> The Turn-1 verified risk changed from 0.195 (v2026.10.1) to 0.295 in v2026.10.2 — the verifier now counts plain integers and integer percentages as specifics and discounts hedged citations. The full change record is in [CHANGELOG.md](CHANGELOG.md).
|
|
88
|
+
|
|
89
|
+
## Architectural Profile
|
|
90
|
+
|
|
91
|
+
| Property | CSCS Constraint Engine |
|
|
92
|
+
| :--- | :--- |
|
|
93
|
+
| VRAM / GPU footprint | **0 MB (pure CPU / numpy)** |
|
|
94
|
+
| Dependencies | numpy only |
|
|
95
|
+
| Per-turn gate latency | environment-dependent — see Operating Envelope |
|
|
96
|
+
| Domain signal | centered SVD residual $\in [0, 1]$ + anchor-weighted resonance |
|
|
97
|
+
| Multi-turn drift metric | Banach contraction + Lyapunov exponent ($\lambda < 0$) + bounded state-commit budget |
|
|
98
|
+
| Creativity vs. confabulation | **SANCTIONED_DREAM** vs. **SPORADIC_RISK** vs. **VERIFIED** |
|
|
99
|
+
| Cross-session state | **93-byte T3LB seed** (lossless at 2-decimal precision) |
|
|
100
|
+
|
|
101
|
+
Latency figures sometimes quoted for neural guardrails (80–450 ms) are published numbers for that model class, not measurements taken by this project, and are not used as a comparison baseline here. Full measurements, environment manifests, and the committed control-battery results: [docs/BENCHMARKS.md](docs/BENCHMARKS.md).
|
|
102
|
+
|
|
103
|
+
## Operating Envelope
|
|
104
|
+
|
|
105
|
+
- **Latency (measured, this release):** 300 distinct-prompt turns, reference VM (Linux, Python 3.12.3, numpy 1.26.4): **median 2.6 ms, P95 3.4 ms**. v2026.10.1 measured 0.45–1.07 ms medians on other hardware with a lighter per-turn path; v2026.10.2 performs additional anchor passes per turn. Treat any single-machine figure as an envelope for that machine, not a guarantee. Very long prompts cost more (hashing is linear in length; ~2,000-word prompts reach ~10 ms class on commodity cores).
|
|
106
|
+
- **Embedding cache:** repeated or near-repeated prompts (retries, loops, templated queries) hit the 1,024-entry embedding LRU and run **~2.6× faster** than distinct-prompt traffic. Quoted latencies are for *distinct* prompts — the conservative case.
|
|
107
|
+
- **Language scope:** the quality gate tokenizes on whitespace. Unspaced scripts (e.g. Japanese, Chinese) score as single-token prompts and are blocked by the quality gate; CJK support requires a tokenizer and is out of scope for this release (documented in [docs/LIMITATIONS.md](docs/LIMITATIONS.md)).
|
|
108
|
+
|
|
109
|
+
## Go deeper
|
|
110
|
+
|
|
111
|
+
- **[Architecture & mathematics](docs/ARCHITECTURE.md)** — the five modules, the Dual-Gram SVD, the friction field, the graduation policy.
|
|
112
|
+
- **[Benchmarks & evaluation protocol](docs/BENCHMARKS.md)** — Track A / Track B control tests and the verified baseline numbers.
|
|
113
|
+
- **[Known limitations](docs/LIMITATIONS.md)** — friction-scale compression, cold-start geometry, CJK scope. Published, not hidden.
|
|
114
|
+
- **[Ecological models & origins](docs/ECOLOGICAL_MODELS_AND_ORIGINS.md)** — coral, bushfire, and phoenix models behind the design.
|
|
115
|
+
- **[Contributing](CONTRIBUTING.md)** — benchmark tracks and how to submit results.
|
|
116
|
+
|
|
117
|
+
## License & citation
|
|
118
|
+
|
|
119
|
+
Copyright © 2024–2026 **Lazaro M. Echenique-Diaz, Ph.D.**
|
|
120
|
+
Licensed under the **Apache License, Version 2.0** (see [LICENSE](LICENSE) and [NOTICE](NOTICE)). If you use this in research or software, please cite it via [CITATION.cff](CITATION.cff) (concept DOI: [10.5281/zenodo.23750262](https://doi.org/10.5281/zenodo.23750262)).
|
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
# CSCS Constraint Physics Engine (`v2026.10.2`)
|
|
2
|
+
|
|
3
|
+
[](https://opensource.org/licenses/Apache-2.0)
|
|
4
|
+
[](https://www.python.org/)
|
|
5
|
+
[-brightgreen.svg)](#quickstart)
|
|
6
|
+
[](https://doi.org/10.5281/zenodo.23750262)
|
|
7
|
+
|
|
8
|
+
**A zero-GPU governor for Small Language Models.** It sits in front of a local SLM (Llama-3.2, Qwen-2.5, Phi-4, Gemma-2), scores prompts *before* they burn inference, tracks multi-turn drift, and audits outputs for confabulation — on one CPU thread, with **numpy only** and **0 MB VRAM**. Latency is environment-dependent; on the reference VM (Linux, Python 3.12.3, numpy 1.26.4) the v2026.10.2 gate measures **2.6 ms median / 3.4 ms P95 per turn across 300-turn sessions** (see [Operating Envelope](#operating-envelope) — earlier releases measured lower on other hardware; no cross-machine latency claim is made).
|
|
9
|
+
|
|
10
|
+
*Created by **Lazaro M. Echenique-Diaz, Ph.D.*** · Concepts descend from evolutionary biology — see [Ecological Models & Origins](docs/ECOLOGICAL_MODELS_AND_ORIGINS.md).
|
|
11
|
+
|
|
12
|
+
> **Note on nomenclature:** **CSCS** stands for **Constraint Space Coordinate System** — an independent open-source edge-AI middleware project created at Yamagata University, unrelated to the Swiss National Supercomputing Centre (CSCS, Lugano).
|
|
13
|
+
|
|
14
|
+
---
|
|
15
|
+
|
|
16
|
+
## Why
|
|
17
|
+
|
|
18
|
+
Neural guardrails (LlamaGuard, NeMo) need a **second neural network** in VRAM — 1.5–4 GB a small edge device can't spare. Quantized SLMs also drift over long chats and invent citations, dates, and percentages when uncertain. This engine replaces the second model with linear algebra: a spectral manifold, a contraction mirror, and a friction field.
|
|
19
|
+
|
|
20
|
+
The engine's first-stage discipline is **trajectory discipline**: a prompt is judged not only by what it contains, but by where the session has been — whether it continues the anchored trajectory of the conversation or breaks from it. Cross-model audit (2026-11) confirmed empirically that this history-relative signal (resonance collapse against the session anchors), not lexical content alone, is the engine's load-bearing discriminator; v2026.10.2 rebuilds the gate around that finding.
|
|
21
|
+
|
|
22
|
+
## Intended Use & Non-Goals
|
|
23
|
+
|
|
24
|
+
**Intended use:** Trajectory governance, drift telemetry, and confabulation auditing for a **known, deliberately seeded domain** on operator-controlled hardware — e.g. a university lab SLM answering questions about an enrolled research corpus, an offline field assistant constrained to an enrolled manual set, or a long-running local agent whose session must stay anchored to an operator-defined topic manifold.
|
|
25
|
+
|
|
26
|
+
**Non-goals:** This engine is **not** a general-purpose chat filter, content-moderation system, or safety boundary for arbitrary open-domain conversation. A deployment whose domain is everything has no manifold to anchor to, and the gate's scores carry no meaning there. Operators enroll a seed corpus, choose the learning policy, and remain responsible for the deployment's content policy.
|
|
27
|
+
|
|
28
|
+
## How it flows
|
|
29
|
+
|
|
30
|
+
```mermaid
|
|
31
|
+
flowchart LR
|
|
32
|
+
P[Prompt] --> Q{Quality gate<br/>score ≥ 0.30?}
|
|
33
|
+
Q -- No --> B[BLOCKED<br/>compute saved]
|
|
34
|
+
Q -- Yes --> M[SpectralManifold<br/>centered SVD residual ∈ [0, 1]]
|
|
35
|
+
M --> C[BanachContractionMirror<br/>anchor-weighted resonance · Lyapunov λ]
|
|
36
|
+
C --> S[RBFConstraintScout<br/>friction field]
|
|
37
|
+
S --> W{Wall?<br/>adaptive: friction > 1/φ ≈ 0.618<br/>calibrated: friction > τ₉₅}
|
|
38
|
+
W -- Yes, not dreaming --> B
|
|
39
|
+
W -- No / dreaming --> SLM[SLM inference<br/>Ollama · llama.cpp · MLX]
|
|
40
|
+
SLM --> V[DriftVerifier]
|
|
41
|
+
V --> VS[VERIFIED]
|
|
42
|
+
V --> VD[SANCTIONED_DREAM]
|
|
43
|
+
V --> VR[SPORADIC_RISK]
|
|
44
|
+
M -.-> T[T3LB seed<br/>93 bytes · 13-D state]
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
**State policy (v2026.10.2).** Blocked prompts mutate nothing. In the calibrated state, an allowed prompt commits state (mirror, scout, manifold) only if it lies in the **core attractor zone** — its anchor-only friction is at most $1/\Phi$; prompts in the tolerated band ($\Phi^{-1} < F \le \tau_{95}$) execute but change nothing, so long sessions cannot drift the judging state. Enrollment anchors the contraction mirror from the first cycle, and the engine **graduates automatically** from its adaptive policy (fixed $1/\Phi$ wall) to the calibrated policy (session-specific $\tau_{95}$, the leave-one-out 95th-percentile anchor friction) as soon as that wall is estimable from the anchored mirror vectors.
|
|
48
|
+
|
|
49
|
+
## Quickstart
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
git clone https://github.com/lazincip/cscs-constraint-engine.git
|
|
53
|
+
cd cscs-constraint-engine
|
|
54
|
+
pip install -e .
|
|
55
|
+
|
|
56
|
+
python -m unittest discover -s tests -v # 6 invariant + regression tests
|
|
57
|
+
python examples/slm_ollama_middleware.py # simulation demo, no server needed
|
|
58
|
+
python examples/slm_ollama_middleware.py --live --model qwen2.5:3b # live Ollama
|
|
59
|
+
python benchmarks/run_track_a.py # committed Track A control battery
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
What the demo shows (verified run, v2026.10.2):
|
|
63
|
+
|
|
64
|
+
```text
|
|
65
|
+
[Turn 1] Summarize the divergence timeline of Solenodon cubanus...
|
|
66
|
+
Pre-Inference Gate : ALLOWED | Resonance 0.526
|
|
67
|
+
Post-Inference : VERIFIED (sporadic_risk = 0.295)
|
|
68
|
+
[Turn 4] buy cheap crypto tokens instant 100x pump free airdrop...
|
|
69
|
+
Pre-Inference Gate : BLOCKED (Compute Saved) | Resonance 0.239
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
> The Turn-1 verified risk changed from 0.195 (v2026.10.1) to 0.295 in v2026.10.2 — the verifier now counts plain integers and integer percentages as specifics and discounts hedged citations. The full change record is in [CHANGELOG.md](CHANGELOG.md).
|
|
73
|
+
|
|
74
|
+
## Architectural Profile
|
|
75
|
+
|
|
76
|
+
| Property | CSCS Constraint Engine |
|
|
77
|
+
| :--- | :--- |
|
|
78
|
+
| VRAM / GPU footprint | **0 MB (pure CPU / numpy)** |
|
|
79
|
+
| Dependencies | numpy only |
|
|
80
|
+
| Per-turn gate latency | environment-dependent — see Operating Envelope |
|
|
81
|
+
| Domain signal | centered SVD residual $\in [0, 1]$ + anchor-weighted resonance |
|
|
82
|
+
| Multi-turn drift metric | Banach contraction + Lyapunov exponent ($\lambda < 0$) + bounded state-commit budget |
|
|
83
|
+
| Creativity vs. confabulation | **SANCTIONED_DREAM** vs. **SPORADIC_RISK** vs. **VERIFIED** |
|
|
84
|
+
| Cross-session state | **93-byte T3LB seed** (lossless at 2-decimal precision) |
|
|
85
|
+
|
|
86
|
+
Latency figures sometimes quoted for neural guardrails (80–450 ms) are published numbers for that model class, not measurements taken by this project, and are not used as a comparison baseline here. Full measurements, environment manifests, and the committed control-battery results: [docs/BENCHMARKS.md](docs/BENCHMARKS.md).
|
|
87
|
+
|
|
88
|
+
## Operating Envelope
|
|
89
|
+
|
|
90
|
+
- **Latency (measured, this release):** 300 distinct-prompt turns, reference VM (Linux, Python 3.12.3, numpy 1.26.4): **median 2.6 ms, P95 3.4 ms**. v2026.10.1 measured 0.45–1.07 ms medians on other hardware with a lighter per-turn path; v2026.10.2 performs additional anchor passes per turn. Treat any single-machine figure as an envelope for that machine, not a guarantee. Very long prompts cost more (hashing is linear in length; ~2,000-word prompts reach ~10 ms class on commodity cores).
|
|
91
|
+
- **Embedding cache:** repeated or near-repeated prompts (retries, loops, templated queries) hit the 1,024-entry embedding LRU and run **~2.6× faster** than distinct-prompt traffic. Quoted latencies are for *distinct* prompts — the conservative case.
|
|
92
|
+
- **Language scope:** the quality gate tokenizes on whitespace. Unspaced scripts (e.g. Japanese, Chinese) score as single-token prompts and are blocked by the quality gate; CJK support requires a tokenizer and is out of scope for this release (documented in [docs/LIMITATIONS.md](docs/LIMITATIONS.md)).
|
|
93
|
+
|
|
94
|
+
## Go deeper
|
|
95
|
+
|
|
96
|
+
- **[Architecture & mathematics](docs/ARCHITECTURE.md)** — the five modules, the Dual-Gram SVD, the friction field, the graduation policy.
|
|
97
|
+
- **[Benchmarks & evaluation protocol](docs/BENCHMARKS.md)** — Track A / Track B control tests and the verified baseline numbers.
|
|
98
|
+
- **[Known limitations](docs/LIMITATIONS.md)** — friction-scale compression, cold-start geometry, CJK scope. Published, not hidden.
|
|
99
|
+
- **[Ecological models & origins](docs/ECOLOGICAL_MODELS_AND_ORIGINS.md)** — coral, bushfire, and phoenix models behind the design.
|
|
100
|
+
- **[Contributing](CONTRIBUTING.md)** — benchmark tracks and how to submit results.
|
|
101
|
+
|
|
102
|
+
## License & citation
|
|
103
|
+
|
|
104
|
+
Copyright © 2024–2026 **Lazaro M. Echenique-Diaz, Ph.D.**
|
|
105
|
+
Licensed under the **Apache License, Version 2.0** (see [LICENSE](LICENSE) and [NOTICE](NOTICE)). If you use this in research or software, please cite it via [CITATION.cff](CITATION.cff) (concept DOI: [10.5281/zenodo.23750262](https://doi.org/10.5281/zenodo.23750262)).
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
"""
|
|
2
|
+
CSCS Constraint Physics Engine: Zero-GPU Spectral Manifold & Contractive
|
|
3
|
+
Telemetry Middleware for Small Language Models (SLMs) (v2026.10.2)
|
|
4
|
+
Principal Investigator & Author: Lazaro M. Echenique-Diaz, Ph.D.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from .manifold import SpectralManifold
|
|
8
|
+
from .contraction import BanachContractionMirror
|
|
9
|
+
from .scout import RBFConstraintScout
|
|
10
|
+
from .compression import MDLCompressionRouter
|
|
11
|
+
from .verifier import DriftVerifier
|
|
12
|
+
from .codec import T3LBStateCodec
|
|
13
|
+
from .engine import CSCSMiddlewareEngine
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"SpectralManifold",
|
|
17
|
+
"BanachContractionMirror",
|
|
18
|
+
"RBFConstraintScout",
|
|
19
|
+
"MDLCompressionRouter",
|
|
20
|
+
"DriftVerifier",
|
|
21
|
+
"T3LBStateCodec",
|
|
22
|
+
"CSCSMiddlewareEngine"
|
|
23
|
+
]
|
|
24
|
+
__version__ = "2026.10.2"
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
"""
|
|
2
|
+
T3LBStateCodec: 13-dimensional telemetry summary serializer for stateless SLM
|
|
3
|
+
context handoffs across edge devices (93 bytes per state seed, lossless
|
|
4
|
+
at 2-decimal fixed precision for the 13 summary scalars).
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
import math as m
|
|
8
|
+
import re
|
|
9
|
+
import numpy as np
|
|
10
|
+
from typing import Dict, Any
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
class T3LBStateCodec:
|
|
14
|
+
"""
|
|
15
|
+
Computes and serializes all 13 Constraint Space Coordinate System (CSCS)
|
|
16
|
+
dimensions into a compact 93-byte T3LB telemetry seed string:
|
|
17
|
+
X (Gap/Novelty Tolerance), Y (Quality Relay Gain), Z (Manifold Persistence),
|
|
18
|
+
W (Constraint Density), P (Compression Efficiency), T (Window Horizon Saturation),
|
|
19
|
+
R (Reflexivity / Inverse Friction), S (Kernel Density Coupling), V (Veto Strength),
|
|
20
|
+
N (Contraction Convergence), E (Effective Rank Ratio),
|
|
21
|
+
B (Bleaching/Block Recovery), Q (State Coherence).
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
DIMENSIONS = ["X", "Y", "Z", "W", "P", "T", "R", "S", "V", "N", "E", "B", "Q"]
|
|
25
|
+
|
|
26
|
+
def __init__(self):
|
|
27
|
+
self.dims: Dict[str, float] = {
|
|
28
|
+
"X": 0.88, "Y": 1.25, "Z": 0.94, "W": 1.08,
|
|
29
|
+
"P": 0.87, "T": 0.79, "R": 0.74, "S": 0.92,
|
|
30
|
+
"V": 0.78, "N": 0.74, "E": 0.88, "B": 0.79, "Q": 0.65
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
def update_from_cycle(self, resonance: float, field_friction: float,
|
|
34
|
+
in_manifold: float, quality: float, blocked: bool,
|
|
35
|
+
compression_ratio: float = 0.85, kernel_density: float = 0.50,
|
|
36
|
+
effective_rank: float = 3.0, iterations: int = 4,
|
|
37
|
+
cycles: int = 1):
|
|
38
|
+
self.dims["T"] = round(min(1.50, 0.50 + 0.50 * min(1.0, cycles / 64.0)), 3)
|
|
39
|
+
|
|
40
|
+
if blocked:
|
|
41
|
+
self.dims["B"] = min(1.50, round(self.dims["B"] + 0.02, 3))
|
|
42
|
+
self.dims["V"] = min(1.20, round(self.dims["V"] + 0.03, 3))
|
|
43
|
+
self.dims["X"] = max(0.40, round(self.dims["X"] - 0.02, 3))
|
|
44
|
+
return
|
|
45
|
+
|
|
46
|
+
self.dims["X"] = round(0.60 + 0.40 * (1.0 - field_friction), 3)
|
|
47
|
+
self.dims["Y"] = round(0.75 + 0.50 * quality, 3)
|
|
48
|
+
self.dims["Z"] = round(0.75 + 0.24 * in_manifold, 3)
|
|
49
|
+
self.dims["W"] = round(0.80 + 0.40 * (0.5 * resonance + 0.5 * in_manifold), 3)
|
|
50
|
+
self.dims["P"] = round(0.50 + 0.50 * max(0.0, min(1.0, 1.0 - compression_ratio * 0.5)), 3)
|
|
51
|
+
self.dims["R"] = round(0.60 + 0.35 * (1.0 - field_friction), 3)
|
|
52
|
+
self.dims["S"] = round(0.50 + 0.50 * max(0.0, min(1.0, kernel_density)), 3)
|
|
53
|
+
self.dims["N"] = round(0.50 + 0.50 * max(0.0, 1.0 - (iterations / 10.0)), 3)
|
|
54
|
+
self.dims["E"] = round(0.50 + 0.50 * min(1.0, effective_rank / 8.0), 3)
|
|
55
|
+
self.dims["Q"] = round(0.50 + 0.45 * (quality * resonance), 3)
|
|
56
|
+
|
|
57
|
+
def magnitude(self) -> float:
|
|
58
|
+
vec = np.array([self.dims[k] for k in self.DIMENSIONS], dtype=np.float64)
|
|
59
|
+
return round(float(np.linalg.norm(vec) * m.sqrt(len(self.DIMENSIONS)) / 2.8), 2)
|
|
60
|
+
|
|
61
|
+
def encode_seed(self, version: str = "v2026.10") -> str:
|
|
62
|
+
mag = self.magnitude()
|
|
63
|
+
body = "".join(f"{k}{self.dims[k]:.2f}" for k in self.DIMENSIONS)
|
|
64
|
+
return f"T3LB:{version}|M{mag:.2f}|{body}|SecLock"
|
|
65
|
+
|
|
66
|
+
@classmethod
|
|
67
|
+
def decode_seed(cls, seed_str: str) -> Dict[str, Any]:
|
|
68
|
+
parts = seed_str.strip().split("|")
|
|
69
|
+
if len(parts) < 3 or not parts[0].startswith("T3LB:"):
|
|
70
|
+
raise ValueError("Invalid T3LB seed format")
|
|
71
|
+
version = parts[0].split(":", 1)[1]
|
|
72
|
+
mag = float(parts[1][1:])
|
|
73
|
+
matches = re.findall(r"([A-Z])(\d+\.\d+)", parts[2])
|
|
74
|
+
dims = {k: float(v) for k, v in matches}
|
|
75
|
+
return {"version": version, "magnitude": mag, "dimensions": dims}
|
|
76
|
+
|
|
77
|
+
def load_seed(self, seed_str: str) -> Dict[str, Any]:
|
|
78
|
+
parsed = self.decode_seed(seed_str)
|
|
79
|
+
for k, v in parsed["dimensions"].items():
|
|
80
|
+
if k in self.dims:
|
|
81
|
+
self.dims[k] = float(v)
|
|
82
|
+
return parsed
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""
|
|
2
|
+
MDLCompressionRouter: Information-Theoretic Minimum Description Length (MDL)
|
|
3
|
+
and delta redundancy telemetry for context-constrained edge models.
|
|
4
|
+
"""
|
|
5
|
+
|
|
6
|
+
import hashlib as h
|
|
7
|
+
import zlib
|
|
8
|
+
import numpy as np
|
|
9
|
+
from collections import OrderedDict
|
|
10
|
+
from typing import Dict, List, Any
|
|
11
|
+
from .manifold import SpectralManifold
|
|
12
|
+
from .scout import INV_PHI
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class MDLCompressionRouter:
|
|
16
|
+
"""
|
|
17
|
+
Measures real byte-level Minimum Description Length (MDL) across:
|
|
18
|
+
1. DEFLATE/LZ77 entropy coding of the state/prompt payload.
|
|
19
|
+
2. Entangled Delta Coding against the nearest neighbor in memory.
|
|
20
|
+
3. Spectral Coordinate Sparse Projection (structural summary).
|
|
21
|
+
|
|
22
|
+
Caches embedding vectors and compressed reference lengths in a bounded
|
|
23
|
+
registry (max 64 entries) for sub-0.2ms execution.
|
|
24
|
+
"""
|
|
25
|
+
|
|
26
|
+
def __init__(self, manifold: SpectralManifold, max_registry: int = 64):
|
|
27
|
+
self.manifold = manifold
|
|
28
|
+
self.max_registry = max_registry
|
|
29
|
+
self.archive: OrderedDict[str, bytes] = OrderedDict()
|
|
30
|
+
self.raw_registry: OrderedDict[str, bytes] = OrderedDict()
|
|
31
|
+
self.vector_registry: OrderedDict[str, np.ndarray] = OrderedDict()
|
|
32
|
+
|
|
33
|
+
def compress(self, text: str, coords: List[float], mutate: bool = True) -> Dict[str, Any]:
|
|
34
|
+
raw_bytes = text.encode("utf-8")
|
|
35
|
+
raw_len = max(1, len(raw_bytes))
|
|
36
|
+
key = h.blake2b(raw_bytes, digest_size=6).hexdigest()
|
|
37
|
+
|
|
38
|
+
zlib_bytes = zlib.compress(raw_bytes, level=1)
|
|
39
|
+
lz_ratio = len(zlib_bytes) / raw_len
|
|
40
|
+
|
|
41
|
+
v = self.manifold.embed(text)
|
|
42
|
+
best_sim = 0.0
|
|
43
|
+
best_key = None
|
|
44
|
+
|
|
45
|
+
for k, pv in self.vector_registry.items():
|
|
46
|
+
sim = float(np.dot(v, pv))
|
|
47
|
+
if sim > best_sim:
|
|
48
|
+
best_sim = sim
|
|
49
|
+
best_key = k
|
|
50
|
+
|
|
51
|
+
if best_sim > INV_PHI and best_key is not None:
|
|
52
|
+
ref_bytes = self.raw_registry[best_key]
|
|
53
|
+
ref_compressed_len = len(self.archive[best_key])
|
|
54
|
+
joint_compressed = len(zlib.compress(ref_bytes + b"||" + raw_bytes, level=1))
|
|
55
|
+
marginal_bytes = max(4, joint_compressed - ref_compressed_len)
|
|
56
|
+
delta_ratio = marginal_bytes / raw_len
|
|
57
|
+
else:
|
|
58
|
+
delta_ratio = 1.0
|
|
59
|
+
|
|
60
|
+
if coords:
|
|
61
|
+
active = sum(1 for c in coords if abs(c) > 0.05)
|
|
62
|
+
spectral_ratio = (active * 4) / raw_len
|
|
63
|
+
else:
|
|
64
|
+
spectral_ratio = 1.0
|
|
65
|
+
|
|
66
|
+
if mutate:
|
|
67
|
+
self.archive[key] = zlib_bytes
|
|
68
|
+
self.raw_registry[key] = raw_bytes
|
|
69
|
+
self.vector_registry[key] = v
|
|
70
|
+
if len(self.vector_registry) > self.max_registry:
|
|
71
|
+
self.archive.popitem(last=False)
|
|
72
|
+
self.raw_registry.popitem(last=False)
|
|
73
|
+
self.vector_registry.popitem(last=False)
|
|
74
|
+
|
|
75
|
+
candidates = [
|
|
76
|
+
("lz77_entropy", lz_ratio),
|
|
77
|
+
("entangled_delta", delta_ratio),
|
|
78
|
+
("spectral_sparse", spectral_ratio)
|
|
79
|
+
]
|
|
80
|
+
best_method, best_ratio = min(candidates, key=lambda x: x[1])
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
"key": key,
|
|
84
|
+
"best_method": best_method,
|
|
85
|
+
"best_ratio": round(float(best_ratio), 4),
|
|
86
|
+
"raw_bytes": raw_len,
|
|
87
|
+
"lz77_bytes": len(zlib_bytes),
|
|
88
|
+
"nearest_entanglement_sim": round(best_sim, 4),
|
|
89
|
+
"ratios": {
|
|
90
|
+
"lz77_entropy": round(float(lz_ratio), 4),
|
|
91
|
+
"entangled_delta": round(float(delta_ratio), 4),
|
|
92
|
+
"spectral_sparse": round(float(spectral_ratio), 4)
|
|
93
|
+
}
|
|
94
|
+
}
|