spnda 0.2.0__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.
- spnda-0.2.0/LICENSE +21 -0
- spnda-0.2.0/PKG-INFO +249 -0
- spnda-0.2.0/README.md +219 -0
- spnda-0.2.0/pyproject.toml +52 -0
- spnda-0.2.0/setup.cfg +4 -0
- spnda-0.2.0/spanda/__init__.py +44 -0
- spnda-0.2.0/spanda/core.py +96 -0
- spnda-0.2.0/spanda/guardrails.py +251 -0
- spnda-0.2.0/spnda.egg-info/PKG-INFO +249 -0
- spnda-0.2.0/spnda.egg-info/SOURCES.txt +12 -0
- spnda-0.2.0/spnda.egg-info/dependency_links.txt +1 -0
- spnda-0.2.0/spnda.egg-info/top_level.txt +1 -0
- spnda-0.2.0/tests/test_guardrails.py +91 -0
- spnda-0.2.0/tests/test_spanda.py +62 -0
spnda-0.2.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Bhupen Nayak, BRHMN Labs Private Limited
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
spnda-0.2.0/PKG-INFO
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: spnda
|
|
3
|
+
Version: 0.2.0
|
|
4
|
+
Summary: Zero-cost epistemic uncertainty quantification & enterprise cascaded guardrails for LLMs
|
|
5
|
+
Author: BRHMN Labs Private Limited
|
|
6
|
+
Author-email: Bhupen Nayak <bhupennayak@icloud.com>
|
|
7
|
+
License: MIT
|
|
8
|
+
Project-URL: Homepage, https://github.com/Adarshent/Spnda
|
|
9
|
+
Project-URL: Repository, https://github.com/Adarshent/Spnda.git
|
|
10
|
+
Project-URL: Bug Tracker, https://github.com/Adarshent/Spnda/issues
|
|
11
|
+
Project-URL: Paper (Zenodo), https://doi.org/10.5281/zenodo.22233648
|
|
12
|
+
Project-URL: ORCID, https://orcid.org/0009-0005-6038-1356
|
|
13
|
+
Keywords: llm,hallucination-detection,guardrails,semantic-entropy,epistemic-uncertainty,ai-safety,self-consistency,rag,agents,tool-calling
|
|
14
|
+
Classifier: Development Status :: 4 - Beta
|
|
15
|
+
Classifier: Intended Audience :: Science/Research
|
|
16
|
+
Classifier: Intended Audience :: Developers
|
|
17
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.8
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
24
|
+
Classifier: Operating System :: OS Independent
|
|
25
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
26
|
+
Requires-Python: >=3.8
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
License-File: LICENSE
|
|
29
|
+
Dynamic: license-file
|
|
30
|
+
|
|
31
|
+
<div align="center">
|
|
32
|
+
|
|
33
|
+
# ⚡ Spanda ($R_{sc}$)
|
|
34
|
+
### Zero-Cost Epistemic Uncertainty Quantification for Large Language Models
|
|
35
|
+
|
|
36
|
+
[](https://opensource.org/licenses/MIT)
|
|
37
|
+
[](https://www.python.org/downloads/)
|
|
38
|
+
[](https://doi.org/10.5281/zenodo.22233648)
|
|
39
|
+
[](https://orcid.org/0009-0005-6038-1356)
|
|
40
|
+
[](#)
|
|
41
|
+
[](#)
|
|
42
|
+
|
|
43
|
+
*Detect LLM hallucinations and quantify uncertainty in microseconds without secondary NLI cross-encoders.*
|
|
44
|
+
|
|
45
|
+
---
|
|
46
|
+
|
|
47
|
+
</div>
|
|
48
|
+
|
|
49
|
+
## 📌 Overview
|
|
50
|
+
|
|
51
|
+
Traditional epistemic uncertainty estimation in LLMs relies on **Semantic Entropy (SE)** ([Kuhn et al., 2023](https://arxiv.org/abs/2302.09664); [Farquhar et al., Nature 2024](https://www.nature.com/articles/s41586-024-07421-0)). While effective, Semantic Entropy requires clustering $K$ sampled generation paths using pairwise bidirectional NLI entailment classifiers (e.g., DeBERTa-v3-base).
|
|
52
|
+
|
|
53
|
+
This introduces two severe production bottlenecks:
|
|
54
|
+
1. **Quadratic Cost:** $\binom{K}{2}$ forward passes per query (45 neural evaluations for $K=10$).
|
|
55
|
+
2. **Serving Latency:** Adds $\sim$90 ms of GPU overhead per inference call, making it unusable for high-throughput production serving.
|
|
56
|
+
|
|
57
|
+
**Spanda** introduces **Exact-Match Normalized Entropy ($R_{sc}$)**: a zero-parameter, zero-GPU metric that computes uncertainty directly over deterministic lexical clusters.
|
|
58
|
+
|
|
59
|
+
Across empirical evaluations spanning two orders of magnitude (**1.5B to 120B parameters**), Spanda matches or exceeds neural Semantic Entropy on structured reasoning while operating **~90,000$\times$ faster** ($< 1\,\mu\text{s}$ vs. $92.4\,\text{ms}$).
|
|
60
|
+
|
|
61
|
+
---
|
|
62
|
+
|
|
63
|
+
## 🔬 Key Empirical Discoveries
|
|
64
|
+
|
|
65
|
+
### 1. The Coherence Scaling Law
|
|
66
|
+
As model capacity increases from 1.5B to 27B parameters, internal reasoning coherence causes correct predictions to naturally converge to identical lexical sequences. On mathematical reasoning (**GSM8K**), exact-match AUROC scales monotonically:
|
|
67
|
+
|
|
68
|
+
$$\text{AUROC}_{\text{GSM8K}}: \underbrace{0.577}_{\text{1.5B}} \longrightarrow \underbrace{0.706}_{\text{7B}} \longrightarrow \mathbf{\underbrace{0.889}_{\text{27B}}} \quad (p = 1.89 \times 10^{-28})$$
|
|
69
|
+
|
|
70
|
+
At **7B+ parameters**, Spanda achieves the exact same discriminative power as heavy DeBERTa-v3 NLI cross-encoders, rendering the neural clustering step redundant for reasoning.
|
|
71
|
+
|
|
72
|
+
### 2. Confident Mode Collapse (Safety Warning)
|
|
73
|
+
At the **120B frontier scale** on ungrounded factual recall (TriviaQA), the model exhibits **Confident Mode Collapse**: its parametric memory and RLHF tuning cause it to hallucinate the *exact same incorrect answer* identically across all $K$ paths. This yields an **inverted AUROC of 0.091** ($d = -2.23, p = 8.28 \times 10^{-15}$).
|
|
74
|
+
|
|
75
|
+
> ⚠️ **Critical Safety Implication:** Any system using self-consistency or agreement as a proxy for truth will be systematically deceived by frontier models on ungrounded factual recall. External grounding (RAG) is mandatory in this regime.
|
|
76
|
+
|
|
77
|
+
---
|
|
78
|
+
|
|
79
|
+
## 📊 Benchmark Results
|
|
80
|
+
|
|
81
|
+
| Model Scale | Benchmark | Accuracy | Spanda ($R_{sc}$) AUROC | Neural SE AUROC | Latency | GPU Req. |
|
|
82
|
+
| :--- | :--- | :---: | :---: | :---: | :---: | :---: |
|
|
83
|
+
| **Qwen-1.5B** | GSM8K | 11.4% | 0.577 | **0.584** | $<1\,\mu\text{s}$ | None |
|
|
84
|
+
| **Qwen-1.5B** | TriviaQA | 32.0% | 0.797 | **0.801** | $<1\,\mu\text{s}$ | None |
|
|
85
|
+
| **Mistral-7B** | GSM8K | 8.2% | **0.706** | 0.705 | $<1\,\mu\text{s}$ | None |
|
|
86
|
+
| **Mistral-7B** | TriviaQA | 45.0% | 0.698 | **0.755** | $<1\,\mu\text{s}$ | None |
|
|
87
|
+
| **Qwen-27B** | GSM8K | 61.2% | **0.889** | --- | $<1\,\mu\text{s}$ | None |
|
|
88
|
+
| **DeBERTa Baseline** | *N/A* | --- | --- | --- | **$\sim$92.4 ms** | Required |
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## 📐 Mathematical Formulation
|
|
93
|
+
|
|
94
|
+
Given $K$ sampled final answers $\{y_1, \dots, y_K\}$ for prompt $x$, deterministic normalization partitions them into $n$ equivalence classes $\{C_1, \dots, C_n\}$ with empirical probabilities $w_i = \frac{|C_i|}{K}$.
|
|
95
|
+
|
|
96
|
+
The **Normalized Shannon Entropy** is:
|
|
97
|
+
$$H_{\text{norm}} = \begin{cases} 0 & \text{if } n = 1 \\ \displaystyle\frac{-\sum_{i=1}^n w_i \ln w_i}{\ln K} & \text{if } n > 1 \end{cases}$$
|
|
98
|
+
|
|
99
|
+
The combined **Spanda Risk Score ($R_{sc}$)** balances entropy dispersion with modal dominance ($w_{\max} = \max_i w_i$):
|
|
100
|
+
$$R_{sc} = \alpha \cdot H_{\text{norm}} + (1 - \alpha) \cdot (1 - w_{\max}), \quad \alpha = 0.5$$
|
|
101
|
+
|
|
102
|
+
- $R_{sc} = 0$: Complete consensus (model is confident).
|
|
103
|
+
- $R_{sc} \to 1$: Maximum epistemic divergence (model is guessing / hallucinating).
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
## ⚡ Installation
|
|
108
|
+
|
|
109
|
+
Spanda is lightweight and requires **zero third-party dependencies** (pure Python standard library).
|
|
110
|
+
|
|
111
|
+
```bash
|
|
112
|
+
pip install spanda
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
Or install from source:
|
|
116
|
+
|
|
117
|
+
```bash
|
|
118
|
+
git clone https://github.com/Adarshent/Spnda.git
|
|
119
|
+
cd Spnda
|
|
120
|
+
pip install -e .
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
---
|
|
124
|
+
|
|
125
|
+
## 🚀 Quick Start
|
|
126
|
+
|
|
127
|
+
### 1. Basic Uncertainty Quantification
|
|
128
|
+
```python
|
|
129
|
+
from spanda import compute_rsc
|
|
130
|
+
|
|
131
|
+
# High-consensus query (Model is confident)
|
|
132
|
+
samples_confident = ["Paris", "paris.", "Paris", "Paris", "Paris"]
|
|
133
|
+
res_conf = compute_rsc(samples_confident)
|
|
134
|
+
|
|
135
|
+
print(f"R_sc Score: {res_conf['rsc']}") # 0.0
|
|
136
|
+
print(f"Dominant Answer: {res_conf['dominant_answer']}") # 'Paris'
|
|
137
|
+
|
|
138
|
+
# Uncertain / guessing query (Model is hallucinating)
|
|
139
|
+
samples_uncertain = ["Berlin", "Rome", "Madrid", "London", "Paris"]
|
|
140
|
+
res_unc = compute_rsc(samples_uncertain)
|
|
141
|
+
|
|
142
|
+
print(f"R_sc Score: {res_unc['rsc']}") # 0.9 (High risk!)
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
### 2. Hallucination Detection Guardrail
|
|
146
|
+
```python
|
|
147
|
+
from spanda import detect_hallucination
|
|
148
|
+
|
|
149
|
+
samples = ["42", "42", "24", "17", "99"]
|
|
150
|
+
guard = detect_hallucination(samples, threshold=0.35)
|
|
151
|
+
|
|
152
|
+
if guard["is_uncertain"]:
|
|
153
|
+
print(f"🚨 Hallucination Warning (R_sc = {guard['rsc']}). Routing to RAG / Human Review.")
|
|
154
|
+
else:
|
|
155
|
+
print(f"✅ Safe output: {guard['dominant_answer']}")
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
### 3. High-Throughput Batch Processing
|
|
159
|
+
```python
|
|
160
|
+
from spanda import batch_compute_rsc
|
|
161
|
+
|
|
162
|
+
batch = [
|
|
163
|
+
["Answer A", "Answer A", "Answer A"],
|
|
164
|
+
["Choice 1", "Choice 2", "Choice 3"]
|
|
165
|
+
]
|
|
166
|
+
|
|
167
|
+
results = batch_compute_rsc(batch)
|
|
168
|
+
for r in results:
|
|
169
|
+
print(r["rsc"], r["dominant_answer"])
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
### 4. Enterprise Cascaded Guardrail (RAG & Autonomous Agents)
|
|
173
|
+
|
|
174
|
+
For mission-critical production pipelines, Spanda provides a **2-Tier Cascaded Guardrail** that combines sub-millisecond consensus filtering with context grounding and tool-call safety:
|
|
175
|
+
|
|
176
|
+
```python
|
|
177
|
+
from spanda import CascadedGuardrail
|
|
178
|
+
|
|
179
|
+
guard = CascadedGuardrail(
|
|
180
|
+
uncertainty_threshold=0.3,
|
|
181
|
+
grounding_threshold=0.15
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
# 1. RAG Query with Mode Collapse Protection
|
|
185
|
+
rag_context = "Documentation: The production cluster runs in us-east-1."
|
|
186
|
+
unanimous_hallucination = ["eu-west-3 Paris", "eu-west-3 Paris", "eu-west-3 Paris"]
|
|
187
|
+
|
|
188
|
+
receipt = guard.evaluate(unanimous_hallucination, context=rag_context)
|
|
189
|
+
print(receipt.decision) # 'MODE_COLLAPSE_RISK'
|
|
190
|
+
print(receipt.is_safe) # False (Unanimous agreement, but 0% grounded in source!)
|
|
191
|
+
print(receipt.tier_executed) # Tier 2
|
|
192
|
+
print(receipt.latency_ms) # < 0.05 ms
|
|
193
|
+
|
|
194
|
+
# 2. Agent Tool Call Argument Verification (e.g. preventing bad 'rm')
|
|
195
|
+
tool_calls = [
|
|
196
|
+
{"command": "rm -rf /var/cache"},
|
|
197
|
+
{"command": "rm -rf /var/log"}, # Conflict detected across parallel paths!
|
|
198
|
+
]
|
|
199
|
+
agent_receipt = guard.evaluate_tool_calls(tool_calls)
|
|
200
|
+
print(agent_receipt.decision) # 'TOOL_ARG_MISMATCH' (Execution blocked!)
|
|
201
|
+
|
|
202
|
+
# 3. Export SOC2 Audit Receipt
|
|
203
|
+
import json
|
|
204
|
+
print(json.dumps(receipt.to_dict(), indent=2))
|
|
205
|
+
```
|
|
206
|
+
|
|
207
|
+
---
|
|
208
|
+
|
|
209
|
+
## 🛡️ Operational Envelope
|
|
210
|
+
|
|
211
|
+
| Use Case / Architecture | Recommendation | Rationale |
|
|
212
|
+
| :--- | :---: | :--- |
|
|
213
|
+
| **Math, Code & Structured QA (7B–70B)** | ✅ **Recommended** | Coherence Scaling Law ensures exact-match matches neural SE at 0 cost. |
|
|
214
|
+
| **High-Throughput Production APIs** | ✅ **Recommended** | 90,000x latency reduction without GPU requirements. |
|
|
215
|
+
| **Free-form Paraphrase QA (<7B)** | ⚠️ **Use Neural SE** | Small models produce inconsistent surface phrasing. |
|
|
216
|
+
| **Ungrounded Facts on Frontier Models (>100B)** | ❌ **Do Not Use Alone** | Subject to **Confident Mode Collapse**; must combine with retrieval (RAG). |
|
|
217
|
+
|
|
218
|
+
---
|
|
219
|
+
|
|
220
|
+
## 🧪 Testing
|
|
221
|
+
|
|
222
|
+
Run the test suite:
|
|
223
|
+
|
|
224
|
+
```bash
|
|
225
|
+
python3 -m unittest discover tests
|
|
226
|
+
```
|
|
227
|
+
|
|
228
|
+
---
|
|
229
|
+
|
|
230
|
+
## 📄 Citation
|
|
231
|
+
|
|
232
|
+
If you use Spanda in your research or production systems, please cite:
|
|
233
|
+
|
|
234
|
+
```bibtex
|
|
235
|
+
@article{nayak2026spanda,
|
|
236
|
+
title={Spanda: Zero-Cost Lexical Entropy Matches Neural Semantic Uncertainty---Until Frontier Models Break It},
|
|
237
|
+
author={Nayak, Bhupen},
|
|
238
|
+
journal={arXiv preprint},
|
|
239
|
+
year={2026},
|
|
240
|
+
doi={10.5281/zenodo.22233648},
|
|
241
|
+
url={https://doi.org/10.5281/zenodo.22233648}
|
|
242
|
+
}
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
---
|
|
246
|
+
|
|
247
|
+
## 📜 License
|
|
248
|
+
|
|
249
|
+
This project is licensed under the [MIT License](LICENSE) - see the LICENSE file for details.
|
spnda-0.2.0/README.md
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
<div align="center">
|
|
2
|
+
|
|
3
|
+
# ⚡ Spanda ($R_{sc}$)
|
|
4
|
+
### Zero-Cost Epistemic Uncertainty Quantification for Large Language Models
|
|
5
|
+
|
|
6
|
+
[](https://opensource.org/licenses/MIT)
|
|
7
|
+
[](https://www.python.org/downloads/)
|
|
8
|
+
[](https://doi.org/10.5281/zenodo.22233648)
|
|
9
|
+
[](https://orcid.org/0009-0005-6038-1356)
|
|
10
|
+
[](#)
|
|
11
|
+
[](#)
|
|
12
|
+
|
|
13
|
+
*Detect LLM hallucinations and quantify uncertainty in microseconds without secondary NLI cross-encoders.*
|
|
14
|
+
|
|
15
|
+
---
|
|
16
|
+
|
|
17
|
+
</div>
|
|
18
|
+
|
|
19
|
+
## 📌 Overview
|
|
20
|
+
|
|
21
|
+
Traditional epistemic uncertainty estimation in LLMs relies on **Semantic Entropy (SE)** ([Kuhn et al., 2023](https://arxiv.org/abs/2302.09664); [Farquhar et al., Nature 2024](https://www.nature.com/articles/s41586-024-07421-0)). While effective, Semantic Entropy requires clustering $K$ sampled generation paths using pairwise bidirectional NLI entailment classifiers (e.g., DeBERTa-v3-base).
|
|
22
|
+
|
|
23
|
+
This introduces two severe production bottlenecks:
|
|
24
|
+
1. **Quadratic Cost:** $\binom{K}{2}$ forward passes per query (45 neural evaluations for $K=10$).
|
|
25
|
+
2. **Serving Latency:** Adds $\sim$90 ms of GPU overhead per inference call, making it unusable for high-throughput production serving.
|
|
26
|
+
|
|
27
|
+
**Spanda** introduces **Exact-Match Normalized Entropy ($R_{sc}$)**: a zero-parameter, zero-GPU metric that computes uncertainty directly over deterministic lexical clusters.
|
|
28
|
+
|
|
29
|
+
Across empirical evaluations spanning two orders of magnitude (**1.5B to 120B parameters**), Spanda matches or exceeds neural Semantic Entropy on structured reasoning while operating **~90,000$\times$ faster** ($< 1\,\mu\text{s}$ vs. $92.4\,\text{ms}$).
|
|
30
|
+
|
|
31
|
+
---
|
|
32
|
+
|
|
33
|
+
## 🔬 Key Empirical Discoveries
|
|
34
|
+
|
|
35
|
+
### 1. The Coherence Scaling Law
|
|
36
|
+
As model capacity increases from 1.5B to 27B parameters, internal reasoning coherence causes correct predictions to naturally converge to identical lexical sequences. On mathematical reasoning (**GSM8K**), exact-match AUROC scales monotonically:
|
|
37
|
+
|
|
38
|
+
$$\text{AUROC}_{\text{GSM8K}}: \underbrace{0.577}_{\text{1.5B}} \longrightarrow \underbrace{0.706}_{\text{7B}} \longrightarrow \mathbf{\underbrace{0.889}_{\text{27B}}} \quad (p = 1.89 \times 10^{-28})$$
|
|
39
|
+
|
|
40
|
+
At **7B+ parameters**, Spanda achieves the exact same discriminative power as heavy DeBERTa-v3 NLI cross-encoders, rendering the neural clustering step redundant for reasoning.
|
|
41
|
+
|
|
42
|
+
### 2. Confident Mode Collapse (Safety Warning)
|
|
43
|
+
At the **120B frontier scale** on ungrounded factual recall (TriviaQA), the model exhibits **Confident Mode Collapse**: its parametric memory and RLHF tuning cause it to hallucinate the *exact same incorrect answer* identically across all $K$ paths. This yields an **inverted AUROC of 0.091** ($d = -2.23, p = 8.28 \times 10^{-15}$).
|
|
44
|
+
|
|
45
|
+
> ⚠️ **Critical Safety Implication:** Any system using self-consistency or agreement as a proxy for truth will be systematically deceived by frontier models on ungrounded factual recall. External grounding (RAG) is mandatory in this regime.
|
|
46
|
+
|
|
47
|
+
---
|
|
48
|
+
|
|
49
|
+
## 📊 Benchmark Results
|
|
50
|
+
|
|
51
|
+
| Model Scale | Benchmark | Accuracy | Spanda ($R_{sc}$) AUROC | Neural SE AUROC | Latency | GPU Req. |
|
|
52
|
+
| :--- | :--- | :---: | :---: | :---: | :---: | :---: |
|
|
53
|
+
| **Qwen-1.5B** | GSM8K | 11.4% | 0.577 | **0.584** | $<1\,\mu\text{s}$ | None |
|
|
54
|
+
| **Qwen-1.5B** | TriviaQA | 32.0% | 0.797 | **0.801** | $<1\,\mu\text{s}$ | None |
|
|
55
|
+
| **Mistral-7B** | GSM8K | 8.2% | **0.706** | 0.705 | $<1\,\mu\text{s}$ | None |
|
|
56
|
+
| **Mistral-7B** | TriviaQA | 45.0% | 0.698 | **0.755** | $<1\,\mu\text{s}$ | None |
|
|
57
|
+
| **Qwen-27B** | GSM8K | 61.2% | **0.889** | --- | $<1\,\mu\text{s}$ | None |
|
|
58
|
+
| **DeBERTa Baseline** | *N/A* | --- | --- | --- | **$\sim$92.4 ms** | Required |
|
|
59
|
+
|
|
60
|
+
---
|
|
61
|
+
|
|
62
|
+
## 📐 Mathematical Formulation
|
|
63
|
+
|
|
64
|
+
Given $K$ sampled final answers $\{y_1, \dots, y_K\}$ for prompt $x$, deterministic normalization partitions them into $n$ equivalence classes $\{C_1, \dots, C_n\}$ with empirical probabilities $w_i = \frac{|C_i|}{K}$.
|
|
65
|
+
|
|
66
|
+
The **Normalized Shannon Entropy** is:
|
|
67
|
+
$$H_{\text{norm}} = \begin{cases} 0 & \text{if } n = 1 \\ \displaystyle\frac{-\sum_{i=1}^n w_i \ln w_i}{\ln K} & \text{if } n > 1 \end{cases}$$
|
|
68
|
+
|
|
69
|
+
The combined **Spanda Risk Score ($R_{sc}$)** balances entropy dispersion with modal dominance ($w_{\max} = \max_i w_i$):
|
|
70
|
+
$$R_{sc} = \alpha \cdot H_{\text{norm}} + (1 - \alpha) \cdot (1 - w_{\max}), \quad \alpha = 0.5$$
|
|
71
|
+
|
|
72
|
+
- $R_{sc} = 0$: Complete consensus (model is confident).
|
|
73
|
+
- $R_{sc} \to 1$: Maximum epistemic divergence (model is guessing / hallucinating).
|
|
74
|
+
|
|
75
|
+
---
|
|
76
|
+
|
|
77
|
+
## ⚡ Installation
|
|
78
|
+
|
|
79
|
+
Spanda is lightweight and requires **zero third-party dependencies** (pure Python standard library).
|
|
80
|
+
|
|
81
|
+
```bash
|
|
82
|
+
pip install spanda
|
|
83
|
+
```
|
|
84
|
+
|
|
85
|
+
Or install from source:
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
git clone https://github.com/Adarshent/Spnda.git
|
|
89
|
+
cd Spnda
|
|
90
|
+
pip install -e .
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
---
|
|
94
|
+
|
|
95
|
+
## 🚀 Quick Start
|
|
96
|
+
|
|
97
|
+
### 1. Basic Uncertainty Quantification
|
|
98
|
+
```python
|
|
99
|
+
from spanda import compute_rsc
|
|
100
|
+
|
|
101
|
+
# High-consensus query (Model is confident)
|
|
102
|
+
samples_confident = ["Paris", "paris.", "Paris", "Paris", "Paris"]
|
|
103
|
+
res_conf = compute_rsc(samples_confident)
|
|
104
|
+
|
|
105
|
+
print(f"R_sc Score: {res_conf['rsc']}") # 0.0
|
|
106
|
+
print(f"Dominant Answer: {res_conf['dominant_answer']}") # 'Paris'
|
|
107
|
+
|
|
108
|
+
# Uncertain / guessing query (Model is hallucinating)
|
|
109
|
+
samples_uncertain = ["Berlin", "Rome", "Madrid", "London", "Paris"]
|
|
110
|
+
res_unc = compute_rsc(samples_uncertain)
|
|
111
|
+
|
|
112
|
+
print(f"R_sc Score: {res_unc['rsc']}") # 0.9 (High risk!)
|
|
113
|
+
```
|
|
114
|
+
|
|
115
|
+
### 2. Hallucination Detection Guardrail
|
|
116
|
+
```python
|
|
117
|
+
from spanda import detect_hallucination
|
|
118
|
+
|
|
119
|
+
samples = ["42", "42", "24", "17", "99"]
|
|
120
|
+
guard = detect_hallucination(samples, threshold=0.35)
|
|
121
|
+
|
|
122
|
+
if guard["is_uncertain"]:
|
|
123
|
+
print(f"🚨 Hallucination Warning (R_sc = {guard['rsc']}). Routing to RAG / Human Review.")
|
|
124
|
+
else:
|
|
125
|
+
print(f"✅ Safe output: {guard['dominant_answer']}")
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
### 3. High-Throughput Batch Processing
|
|
129
|
+
```python
|
|
130
|
+
from spanda import batch_compute_rsc
|
|
131
|
+
|
|
132
|
+
batch = [
|
|
133
|
+
["Answer A", "Answer A", "Answer A"],
|
|
134
|
+
["Choice 1", "Choice 2", "Choice 3"]
|
|
135
|
+
]
|
|
136
|
+
|
|
137
|
+
results = batch_compute_rsc(batch)
|
|
138
|
+
for r in results:
|
|
139
|
+
print(r["rsc"], r["dominant_answer"])
|
|
140
|
+
```
|
|
141
|
+
|
|
142
|
+
### 4. Enterprise Cascaded Guardrail (RAG & Autonomous Agents)
|
|
143
|
+
|
|
144
|
+
For mission-critical production pipelines, Spanda provides a **2-Tier Cascaded Guardrail** that combines sub-millisecond consensus filtering with context grounding and tool-call safety:
|
|
145
|
+
|
|
146
|
+
```python
|
|
147
|
+
from spanda import CascadedGuardrail
|
|
148
|
+
|
|
149
|
+
guard = CascadedGuardrail(
|
|
150
|
+
uncertainty_threshold=0.3,
|
|
151
|
+
grounding_threshold=0.15
|
|
152
|
+
)
|
|
153
|
+
|
|
154
|
+
# 1. RAG Query with Mode Collapse Protection
|
|
155
|
+
rag_context = "Documentation: The production cluster runs in us-east-1."
|
|
156
|
+
unanimous_hallucination = ["eu-west-3 Paris", "eu-west-3 Paris", "eu-west-3 Paris"]
|
|
157
|
+
|
|
158
|
+
receipt = guard.evaluate(unanimous_hallucination, context=rag_context)
|
|
159
|
+
print(receipt.decision) # 'MODE_COLLAPSE_RISK'
|
|
160
|
+
print(receipt.is_safe) # False (Unanimous agreement, but 0% grounded in source!)
|
|
161
|
+
print(receipt.tier_executed) # Tier 2
|
|
162
|
+
print(receipt.latency_ms) # < 0.05 ms
|
|
163
|
+
|
|
164
|
+
# 2. Agent Tool Call Argument Verification (e.g. preventing bad 'rm')
|
|
165
|
+
tool_calls = [
|
|
166
|
+
{"command": "rm -rf /var/cache"},
|
|
167
|
+
{"command": "rm -rf /var/log"}, # Conflict detected across parallel paths!
|
|
168
|
+
]
|
|
169
|
+
agent_receipt = guard.evaluate_tool_calls(tool_calls)
|
|
170
|
+
print(agent_receipt.decision) # 'TOOL_ARG_MISMATCH' (Execution blocked!)
|
|
171
|
+
|
|
172
|
+
# 3. Export SOC2 Audit Receipt
|
|
173
|
+
import json
|
|
174
|
+
print(json.dumps(receipt.to_dict(), indent=2))
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
---
|
|
178
|
+
|
|
179
|
+
## 🛡️ Operational Envelope
|
|
180
|
+
|
|
181
|
+
| Use Case / Architecture | Recommendation | Rationale |
|
|
182
|
+
| :--- | :---: | :--- |
|
|
183
|
+
| **Math, Code & Structured QA (7B–70B)** | ✅ **Recommended** | Coherence Scaling Law ensures exact-match matches neural SE at 0 cost. |
|
|
184
|
+
| **High-Throughput Production APIs** | ✅ **Recommended** | 90,000x latency reduction without GPU requirements. |
|
|
185
|
+
| **Free-form Paraphrase QA (<7B)** | ⚠️ **Use Neural SE** | Small models produce inconsistent surface phrasing. |
|
|
186
|
+
| **Ungrounded Facts on Frontier Models (>100B)** | ❌ **Do Not Use Alone** | Subject to **Confident Mode Collapse**; must combine with retrieval (RAG). |
|
|
187
|
+
|
|
188
|
+
---
|
|
189
|
+
|
|
190
|
+
## 🧪 Testing
|
|
191
|
+
|
|
192
|
+
Run the test suite:
|
|
193
|
+
|
|
194
|
+
```bash
|
|
195
|
+
python3 -m unittest discover tests
|
|
196
|
+
```
|
|
197
|
+
|
|
198
|
+
---
|
|
199
|
+
|
|
200
|
+
## 📄 Citation
|
|
201
|
+
|
|
202
|
+
If you use Spanda in your research or production systems, please cite:
|
|
203
|
+
|
|
204
|
+
```bibtex
|
|
205
|
+
@article{nayak2026spanda,
|
|
206
|
+
title={Spanda: Zero-Cost Lexical Entropy Matches Neural Semantic Uncertainty---Until Frontier Models Break It},
|
|
207
|
+
author={Nayak, Bhupen},
|
|
208
|
+
journal={arXiv preprint},
|
|
209
|
+
year={2026},
|
|
210
|
+
doi={10.5281/zenodo.22233648},
|
|
211
|
+
url={https://doi.org/10.5281/zenodo.22233648}
|
|
212
|
+
}
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
---
|
|
216
|
+
|
|
217
|
+
## 📜 License
|
|
218
|
+
|
|
219
|
+
This project is licensed under the [MIT License](LICENSE) - see the LICENSE file for details.
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=61.0", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "spnda"
|
|
7
|
+
version = "0.2.0"
|
|
8
|
+
authors = [
|
|
9
|
+
{ name = "Bhupen Nayak", email = "bhupennayak@icloud.com" },
|
|
10
|
+
{ name = "BRHMN Labs Private Limited" },
|
|
11
|
+
]
|
|
12
|
+
description = "Zero-cost epistemic uncertainty quantification & enterprise cascaded guardrails for LLMs"
|
|
13
|
+
readme = "README.md"
|
|
14
|
+
license = { text = "MIT" }
|
|
15
|
+
requires-python = ">=3.8"
|
|
16
|
+
keywords = [
|
|
17
|
+
"llm",
|
|
18
|
+
"hallucination-detection",
|
|
19
|
+
"guardrails",
|
|
20
|
+
"semantic-entropy",
|
|
21
|
+
"epistemic-uncertainty",
|
|
22
|
+
"ai-safety",
|
|
23
|
+
"self-consistency",
|
|
24
|
+
"rag",
|
|
25
|
+
"agents",
|
|
26
|
+
"tool-calling"
|
|
27
|
+
]
|
|
28
|
+
classifiers = [
|
|
29
|
+
"Development Status :: 4 - Beta",
|
|
30
|
+
"Intended Audience :: Science/Research",
|
|
31
|
+
"Intended Audience :: Developers",
|
|
32
|
+
"License :: OSI Approved :: MIT License",
|
|
33
|
+
"Programming Language :: Python :: 3",
|
|
34
|
+
"Programming Language :: Python :: 3.8",
|
|
35
|
+
"Programming Language :: Python :: 3.9",
|
|
36
|
+
"Programming Language :: Python :: 3.10",
|
|
37
|
+
"Programming Language :: Python :: 3.11",
|
|
38
|
+
"Programming Language :: Python :: 3.12",
|
|
39
|
+
"Operating System :: OS Independent",
|
|
40
|
+
"Topic :: Scientific/Engineering :: Artificial Intelligence",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
[project.urls]
|
|
44
|
+
"Homepage" = "https://github.com/Adarshent/Spnda"
|
|
45
|
+
"Repository" = "https://github.com/Adarshent/Spnda.git"
|
|
46
|
+
"Bug Tracker" = "https://github.com/Adarshent/Spnda/issues"
|
|
47
|
+
"Paper (Zenodo)" = "https://doi.org/10.5281/zenodo.22233648"
|
|
48
|
+
"ORCID" = "https://orcid.org/0009-0005-6038-1356"
|
|
49
|
+
|
|
50
|
+
[tool.setuptools.packages.find]
|
|
51
|
+
where = ["."]
|
|
52
|
+
include = ["spanda*"]
|
spnda-0.2.0/setup.cfg
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
"""
|
|
2
|
+
Spanda — Zero-Cost Epistemic Uncertainty & Cascaded Guardrails for LLMs.
|
|
3
|
+
|
|
4
|
+
Detect hallucinations in LLM outputs using exact-match normalized entropy.
|
|
5
|
+
90,000x faster than neural Semantic Entropy, zero GPU required.
|
|
6
|
+
|
|
7
|
+
Paper: "Spanda: Zero-Cost Lexical Entropy Matches Neural Semantic Uncertainty
|
|
8
|
+
— Until Frontier Models Break It" (Nayak, 2026)
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
>>> from spanda import compute_rsc, detect_hallucination, CascadedGuardrail
|
|
12
|
+
>>> answers = ["42", "42", "42", "41", "43"]
|
|
13
|
+
>>> result = compute_rsc(answers)
|
|
14
|
+
>>> print(result)
|
|
15
|
+
|
|
16
|
+
>>> # Enterprise Cascaded Guardrail
|
|
17
|
+
>>> guard = CascadedGuardrail(uncertainty_threshold=0.3)
|
|
18
|
+
>>> receipt = guard.evaluate(answers, context="The answer is forty-two.")
|
|
19
|
+
>>> print(receipt)
|
|
20
|
+
"""
|
|
21
|
+
|
|
22
|
+
__version__ = "0.2.0"
|
|
23
|
+
__author__ = "Bhupen Nayak"
|
|
24
|
+
__email__ = "bhupennayak@icloud.com"
|
|
25
|
+
|
|
26
|
+
from spanda.core import (
|
|
27
|
+
compute_rsc,
|
|
28
|
+
normalize_answer,
|
|
29
|
+
detect_hallucination,
|
|
30
|
+
batch_compute_rsc,
|
|
31
|
+
)
|
|
32
|
+
from spanda.guardrails import (
|
|
33
|
+
CascadedGuardrail,
|
|
34
|
+
AuditReceipt,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"compute_rsc",
|
|
39
|
+
"normalize_answer",
|
|
40
|
+
"detect_hallucination",
|
|
41
|
+
"batch_compute_rsc",
|
|
42
|
+
"CascadedGuardrail",
|
|
43
|
+
"AuditReceipt",
|
|
44
|
+
]
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
import re
|
|
2
|
+
import math
|
|
3
|
+
import collections
|
|
4
|
+
from typing import List, Dict, Any, Union
|
|
5
|
+
|
|
6
|
+
def normalize_answer(text: str) -> str:
|
|
7
|
+
"""
|
|
8
|
+
Deterministically normalizes a string for exact-match equivalence.
|
|
9
|
+
Lowercases, strips punctuation, and normalizes whitespace.
|
|
10
|
+
"""
|
|
11
|
+
if not isinstance(text, str):
|
|
12
|
+
text = str(text)
|
|
13
|
+
|
|
14
|
+
# Lowercase
|
|
15
|
+
text = text.lower()
|
|
16
|
+
|
|
17
|
+
# Remove punctuation
|
|
18
|
+
text = re.sub(r'[^\w\s]', '', text)
|
|
19
|
+
|
|
20
|
+
# Normalize whitespace
|
|
21
|
+
text = ' '.join(text.split())
|
|
22
|
+
|
|
23
|
+
return text.strip()
|
|
24
|
+
|
|
25
|
+
def compute_rsc(answers: List[str], alpha: float = 0.5) -> Dict[str, Any]:
|
|
26
|
+
"""
|
|
27
|
+
Computes the Spanda (R_sc) exact-match entropy risk score for a set of sampled answers.
|
|
28
|
+
|
|
29
|
+
Args:
|
|
30
|
+
answers: A list of K string answers sampled from an LLM.
|
|
31
|
+
alpha: The weighting factor for H_norm vs (1 - w_max). Default 0.5.
|
|
32
|
+
|
|
33
|
+
Returns:
|
|
34
|
+
A dictionary containing the rsc score, components, and the dominant answer.
|
|
35
|
+
"""
|
|
36
|
+
if not answers:
|
|
37
|
+
raise ValueError("The answers list cannot be empty.")
|
|
38
|
+
|
|
39
|
+
K = len(answers)
|
|
40
|
+
|
|
41
|
+
# 1. Normalize and cluster
|
|
42
|
+
normalized_answers = [normalize_answer(a) for a in answers]
|
|
43
|
+
counts = collections.Counter(normalized_answers)
|
|
44
|
+
|
|
45
|
+
# 2. Compute probabilities (w_i)
|
|
46
|
+
w = [count / K for count in counts.values()]
|
|
47
|
+
n_clusters = len(counts)
|
|
48
|
+
|
|
49
|
+
# 3. Compute normalized entropy H_norm
|
|
50
|
+
if n_clusters == 1:
|
|
51
|
+
h_norm = 0.0
|
|
52
|
+
else:
|
|
53
|
+
# Avoid math domain error by capping denominator
|
|
54
|
+
denom = math.log(K) if K > 1 else 1.0
|
|
55
|
+
h_norm = sum(-p * math.log(p) for p in w) / denom
|
|
56
|
+
|
|
57
|
+
# 4. Compute modal dominance (w_max)
|
|
58
|
+
w_max = max(w)
|
|
59
|
+
|
|
60
|
+
# 5. Compute R_sc
|
|
61
|
+
rsc = alpha * h_norm + (1 - alpha) * (1 - w_max)
|
|
62
|
+
|
|
63
|
+
# Find the string representation of the dominant cluster
|
|
64
|
+
dominant_cluster_norm = counts.most_common(1)[0][0]
|
|
65
|
+
|
|
66
|
+
# Find original string that mapped to dominant cluster (first occurrence)
|
|
67
|
+
dominant_answer = next(
|
|
68
|
+
ans for ans, norm in zip(answers, normalized_answers)
|
|
69
|
+
if norm == dominant_cluster_norm
|
|
70
|
+
)
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
"rsc": round(rsc, 4),
|
|
74
|
+
"h_norm": round(h_norm, 4),
|
|
75
|
+
"w_max": round(w_max, 4),
|
|
76
|
+
"n_clusters": n_clusters,
|
|
77
|
+
"dominant_answer": dominant_answer,
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
def detect_hallucination(answers: List[str], threshold: float = 0.3) -> Dict[str, Any]:
|
|
81
|
+
"""
|
|
82
|
+
Convenience function that computes R_sc and returns a boolean flagging
|
|
83
|
+
whether the model is likely hallucinating (R_sc > threshold).
|
|
84
|
+
|
|
85
|
+
NOTE: On models > 100B params doing factual recall, confident mode collapse
|
|
86
|
+
may cause R_sc to be near 0 even for hallucinations. Use with caution on frontier models.
|
|
87
|
+
"""
|
|
88
|
+
result = compute_rsc(answers)
|
|
89
|
+
result["is_uncertain"] = result["rsc"] > threshold
|
|
90
|
+
return result
|
|
91
|
+
|
|
92
|
+
def batch_compute_rsc(batch_answers: List[List[str]]) -> List[Dict[str, Any]]:
|
|
93
|
+
"""
|
|
94
|
+
Computes R_sc for a batch of sampled generations.
|
|
95
|
+
"""
|
|
96
|
+
return [compute_rsc(answers) for answers in batch_answers]
|