snapkitty
machine-learning
python
SNAPKITTYWEST commited on
Commit
1817730
·
verified ·
1 Parent(s): 4dc0b6c

push from SNAPKITTYWEST/sovlm

Browse files
.github/scripts/agent.py ADDED
@@ -0,0 +1,180 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Sovereign autonomous agent — runs inside GitHub Actions.
4
+ Reads the repo, finds work, calls DeepSeek-R1, writes fixes back.
5
+ Self-modifying loop. No Claude. No GPU. Free tier OpenRouter.
6
+
7
+ U-MATRIX:
8
+ Scan → Think → Write → Commit (handled by workflow)
9
+
10
+ Ahmad Ali Parr · SnapKitty Collective · 2026
11
+ """
12
+ import os, sys, json, re, glob, requests
13
+ from pathlib import Path
14
+
15
+ KEY = os.environ.get("OPENROUTER_API_KEY", "")
16
+ ROOT = Path(os.environ.get("GITHUB_WORKSPACE", "."))
17
+ TASK = os.environ.get("OVERRIDE_TASK", "")
18
+ MODEL = "qwen/qwen-2.5-coder-32b-instruct" # fast + free quota
19
+
20
+ SCAN_PATTERNS = {
21
+ "sorry": (["*.lean"], r'\bsorry\b'),
22
+ "todo": (["*.py", "*.rs", "*.hs", "*.ml"], r'#\s*TODO|--\s*TODO|//\s*TODO'),
23
+ "stub": (["*.py"], r'raise NotImplementedError|pass\s*$'),
24
+ "fixme": (["*.py", "*.rs", "*.lean"], r'FIXME|HACK|XXX'),
25
+ }
26
+
27
+
28
+ def or_call(prompt: str, model: str = MODEL) -> str:
29
+ if not KEY:
30
+ print("No OPENROUTER_API_KEY set"); sys.exit(1)
31
+ resp = requests.post(
32
+ "https://openrouter.ai/api/v1/chat/completions",
33
+ headers={"Authorization": f"Bearer {KEY}", "HTTP-Referer": "https://snapkittywest.io", "X-Title": "SNAPKITTY-AGENT"},
34
+ json={"model": model, "messages": [{"role": "user", "content": prompt}],
35
+ "temperature": 0.1, "max_tokens": 8192},
36
+ timeout=300)
37
+ resp.raise_for_status()
38
+ return resp.json()["choices"][0]["message"]["content"]
39
+
40
+
41
+ def scan_repo() -> list[dict]:
42
+ """Find all actionable items in the repo."""
43
+ findings = []
44
+ for tag, (globs, pattern) in SCAN_PATTERNS.items():
45
+ for g in globs:
46
+ for path in ROOT.rglob(g):
47
+ # skip .github, node_modules, .git
48
+ if any(p in str(path) for p in [".github", "node_modules", ".git", "__pycache__", ".sovlm_model"]):
49
+ continue
50
+ try:
51
+ text = path.read_text(encoding="utf-8", errors="ignore")
52
+ lines = text.split("\n")
53
+ for i, line in enumerate(lines):
54
+ if re.search(pattern, line):
55
+ findings.append({
56
+ "tag": tag,
57
+ "file": str(path.relative_to(ROOT)),
58
+ "line": i + 1,
59
+ "content": line.strip(),
60
+ "context": "\n".join(lines[max(0,i-3):i+4]),
61
+ })
62
+ except Exception:
63
+ pass
64
+ return findings
65
+
66
+
67
+ def build_task(findings: list[dict]) -> str:
68
+ if TASK:
69
+ return TASK
70
+
71
+ if not findings:
72
+ # No open items — generate next feature
73
+ return (
74
+ "The sovlm repo is clean. Generate the next most valuable feature: "
75
+ "a FastAPI `/generate` endpoint in `src/sovlm/api.py` that exposes the Generator. "
76
+ "Output ONLY the complete Python file."
77
+ )
78
+
79
+ # Pick highest-value finding
80
+ # Priority: sorry > stub > todo > fixme
81
+ priority = {"sorry": 0, "stub": 1, "todo": 2, "fixme": 3}
82
+ findings.sort(key=lambda f: priority.get(f["tag"], 9))
83
+ top = findings[:5] # batch up to 5
84
+
85
+ items = "\n".join(
86
+ f"[{f['tag'].upper()}] {f['file']}:{f['line']}\n{f['context']}\n"
87
+ for f in top
88
+ )
89
+
90
+ # Read full file for first finding
91
+ first = top[0]
92
+ try:
93
+ full_file = (ROOT / first["file"]).read_text(encoding="utf-8", errors="ignore")
94
+ except Exception:
95
+ full_file = first["context"]
96
+
97
+ return f"""You are a sovereign coding agent for SnapKitty Collective.
98
+ Fix the following issues in {first['file']}.
99
+ Output ONLY the complete corrected file. No markdown. No explanation.
100
+
101
+ ISSUES FOUND:
102
+ {items}
103
+
104
+ CURRENT FILE CONTENT:
105
+ {full_file}
106
+ """
107
+
108
+
109
+ def apply_result(task: str, result: str) -> None:
110
+ # Extract code block if present
111
+ m = re.search(r'```[\w]*\n(.*?)```', result, re.DOTALL)
112
+ if m:
113
+ result = m.group(1).strip()
114
+ else:
115
+ # Strip leading prose
116
+ m2 = re.search(r'^(import |from |#!|namespace |theorem |def |class |pub )', result, re.MULTILINE)
117
+ if m2:
118
+ result = result[m2.start():]
119
+
120
+ if not result.strip() or len(result) < 50:
121
+ print(f"Agent returned too little ({len(result)} chars), skipping write.")
122
+ return
123
+
124
+ # If task mentions a specific file, write there
125
+ file_match = re.search(r'\b(src/[\w/]+\.py|[\w/]+\.lean|[\w/]+\.rs|[\w/]+\.hs)\b', task)
126
+ if file_match:
127
+ target = ROOT / file_match.group(1)
128
+ target.parent.mkdir(parents=True, exist_ok=True)
129
+ target.write_text(result, encoding="utf-8")
130
+ print(f"Written: {target} ({len(result)} chars)")
131
+ return
132
+
133
+ # Otherwise detect from result content
134
+ if result.strip().startswith("import Mathlib") or "namespace " in result[:200]:
135
+ # Lean file — find which one was being fixed
136
+ lean_match = re.search(r'([\w/]+\.lean)', task)
137
+ if lean_match:
138
+ target = ROOT / lean_match.group(1)
139
+ target.write_text(result, encoding="utf-8")
140
+ print(f"Written (lean): {target}")
141
+ elif result.strip().startswith("from __future__") or result.strip().startswith("import "):
142
+ # Python — find which file
143
+ py_match = re.search(r'(src/[\w/]+\.py|[\w/]+\.py)', task)
144
+ if py_match:
145
+ target = ROOT / py_match.group(1)
146
+ target.write_text(result, encoding="utf-8")
147
+ print(f"Written (py): {target}")
148
+ else:
149
+ # Default: write new api.py
150
+ target = ROOT / "src/sovlm/api.py"
151
+ target.write_text(result, encoding="utf-8")
152
+ print(f"Written (new): {target}")
153
+ else:
154
+ print("Could not determine target file. Dumping to agent_output.txt")
155
+ (ROOT / "agent_output.txt").write_text(result, encoding="utf-8")
156
+
157
+
158
+ def main():
159
+ print("=" * 60)
160
+ print("SNAPKITTY AUTONOMOUS AGENT")
161
+ print(f"Model: {MODEL}")
162
+ print(f"Root: {ROOT}")
163
+ print("=" * 60)
164
+
165
+ findings = scan_repo()
166
+ print(f"Found {len(findings)} open items: {[f['tag'] for f in findings[:10]]}")
167
+
168
+ task = build_task(findings)
169
+ print(f"\nTask (first 200 chars): {task[:200]}...")
170
+
171
+ print("\nCalling agent...")
172
+ result = or_call(task)
173
+ print(f"Got {len(result)} chars")
174
+
175
+ apply_result(task, result)
176
+ print("\nDone. Workflow will commit any changes.")
177
+
178
+
179
+ if __name__ == "__main__":
180
+ main()
.github/workflows/autonomous-agent.yml ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ name: Autonomous Agent — Self-Modifying Loop
2
+
3
+ on:
4
+ push:
5
+ branches: [master, main]
6
+ schedule:
7
+ - cron: '0 */4 * * *' # every 4 hours
8
+ workflow_dispatch:
9
+ inputs:
10
+ task:
11
+ description: 'Override task prompt'
12
+ required: false
13
+ default: ''
14
+
15
+ permissions:
16
+ contents: write
17
+
18
+ jobs:
19
+ agent:
20
+ runs-on: ubuntu-latest
21
+ steps:
22
+ - uses: actions/checkout@v4
23
+ with:
24
+ token: ${{ secrets.GITHUB_TOKEN }}
25
+ fetch-depth: 0
26
+
27
+ - uses: actions/setup-python@v5
28
+ with:
29
+ python-version: '3.11'
30
+
31
+ - name: Install deps
32
+ run: pip install requests orjson
33
+
34
+ - name: Run sovereign agent
35
+ env:
36
+ OPENROUTER_API_KEY: ${{ secrets.OPENROUTER_API_KEY }}
37
+ GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
38
+ OVERRIDE_TASK: ${{ github.event.inputs.task }}
39
+ run: python .github/scripts/agent.py
40
+
41
+ - name: Commit changes
42
+ run: |
43
+ git config user.name "SNAPKITTY-AGENT"
44
+ git config user.email "agent@snapkittywest.io"
45
+ git add -A
46
+ if git diff --cached --quiet; then
47
+ echo "Nothing to commit."
48
+ else
49
+ git commit -m "⟦Ω⟧ agent: $(date -u +%Y-%m-%dT%H:%M:%SZ)"
50
+ git push origin HEAD
51
+ fi
LICENSE.tri ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ TRI-LICENSE STRUCTURE
2
+ =====================
3
+
4
+ This project is available under THREE licensing options:
5
+
6
+ 1. Business Source License 1.1 (BSL-1.1)
7
+ - Source-available with commercial restrictions
8
+ - No managed service offerings at enterprise scale
9
+ - Converts to AGPL-3.0 after transition period (Change Date: 2028-08-08)
10
+ - Full text: LICENSE.BSL
11
+
12
+ 2. GNU Affero General Public License v3.0 (AGPL-3.0)
13
+ - Strong network copyleft
14
+ - SaaS/network distribution triggers source disclosure
15
+ - All modifications must be AGPL-3.0
16
+ - Full text: LICENSE.AGPL
17
+
18
+ 3. Mozilla Public License 2.0 (MPL-2.0) + Commercial Dual License
19
+ - Weak copyleft (file-level)
20
+ - Can combine with proprietary code
21
+ - Modified files must remain MPL-2.0
22
+ - Commercial license available for copyleft bypass
23
+ - Full text: LICENSE.MPL
24
+
25
+ ================================================================================
26
+
27
+ WHICH LICENSE APPLIES TO MY USE CASE?
28
+
29
+ ├─ Deploying as managed service / SaaS wrapper?
30
+ │ └─> AGPL-3.0 (network copyleft triggers disclosure)
31
+ │
32
+ ├─ Enterprise scale without managed service?
33
+ │ └─> BSL-1.1 (source-available, restricted commercial use)
34
+ │
35
+ ├─ Modifying specific files only?
36
+ │ └─> MPL-2.0 (file-level copyleft)
37
+ │
38
+ ├─ Want to bypass copyleft restrictions?
39
+ │ └─> Commercial License (contact: ahmedparr93@gmail.com)
40
+ │
41
+ └─ Open source contribution / redistribution?
42
+ └─> AGPL-3.0 (default copyleft path)
43
+
44
+ ================================================================================
45
+
46
+ COPYRIGHT HOLDER
47
+
48
+ Copyright (C) 2026 Ahmad Ali Parr
49
+ Bel Esprit D'Accord Irrevocable Trust
50
+ SnapKitty Collective Limited (FLP)
51
+
52
+ Contact: ahmedparr93@gmail.com
53
+ Web: https://github.com/SNAPKITTYWEST
54
+
55
+ ================================================================================
56
+
57
+ LICENSE COMPATIBILITY ENGINE
58
+
59
+ This project includes a Prolog-based license compatibility reasoner:
60
+ backends/license_policy.pl
61
+
62
+ Query compatibility:
63
+ swipl -q -t halt -f backends/license_policy.pl -- matrix
64
+
65
+ Check dependencies:
66
+ swipl -q -t halt -f backends/license_policy.pl -- check agpl3 deps.json
67
+
68
+ Select license for use case:
69
+ swipl -q -t halt -f backends/license_policy.pl -- select saas_wrapper
70
+
71
+ ================================================================================
72
+
73
+ WHY TRI-LICENSE?
74
+
75
+ 1. BSL Layer: Protects commercial interests while keeping code source-available.
76
+ Prevents hyperscaler cloud vendors from offering managed services without
77
+ contributing back. Converts to AGPL after transition period.
78
+
79
+ 2. AGPL Layer: Ensures network copyleft. Anyone wrapping this in a SaaS product
80
+ or exposing it over a network API must open-source their entire stack under
81
+ the same terms. Strongest copyleft available.
82
+
83
+ 3. MPL + Dual License Layer: Provides flexibility for enterprises that want to
84
+ use specific components without full copyleft infection. File-level copyleft
85
+ allows combining with proprietary code. Commercial license available to
86
+ bypass all copyleft restrictions.
87
+
88
+ This structure mirrors Mozilla's historic tri-licensing strategy (MPL/GPL/LGPL)
89
+ adapted for modern SaaS/cloud distribution models.
90
+
91
+ ================================================================================
92
+
93
+ TRANSITION TIMELINE
94
+
95
+ 2026-08-08: BSL-1.1 + AGPL-3.0 + MPL-2.0 tri-license effective
96
+ 2028-08-08: BSL converts to AGPL-3.0 (Change Date)
97
+ 2028-08-08+: Code available under AGPL-3.0 or MPL-2.0 or Commercial
98
+
99
+ After the Change Date, the BSL restriction is lifted and code becomes available
100
+ under AGPL-3.0 for all use cases (or MPL-2.0 for file-level use, or Commercial
101
+ for copyleft bypass).
README.md ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # sovlm
2
+
3
+ ![Python](https://img.shields.io/badge/python-3.11+-blue?style=flat-square)
4
+ ![Zero GPU](https://img.shields.io/badge/GPU-zero-black?style=flat-square)
5
+ ![Zero Training](https://img.shields.io/badge/training-zero-black?style=flat-square)
6
+ ![License](https://img.shields.io/badge/license-SOVEREIGN-gold?style=flat-square)
7
+ ![Author](https://img.shields.io/badge/author-Ahmad_Ali_Parr-red?style=flat-square)
8
+
9
+ **Sovereign Statistical Language Model.**
10
+ N-grams + Kneser-Ney + BM25 Retrieval + QRNG sampling.
11
+ No training. No backprop. No GPU. Pure governance.
12
+
13
+ Part of the SnapKitty Collective sovereign AI stack.
14
+
15
+ ---
16
+
17
+ ## Install
18
+
19
+ ```bash
20
+ pip install -e ".[dev]"
21
+ # or
22
+ uv pip install -e ".[dev]"
23
+ ```
24
+
25
+ ## Usage
26
+
27
+ ```bash
28
+ # Build from your corpus (Lean proofs, Prolog, docs, anything)
29
+ sovlm build data/*.lean data/*.pl data/*.md --order 4
30
+
31
+ # Generate
32
+ sovlm generate -p "theorem main : " -m 200
33
+
34
+ # Stream
35
+ sovlm generate -p "The 49th Call is" --stream
36
+
37
+ # Quantum RNG sampling
38
+ sovlm generate -p "lemma " --qrng
39
+
40
+ # Serve HTTP API
41
+ sovlm serve --port 8080
42
+ ```
43
+
44
+ ## Python API
45
+
46
+ ```python
47
+ from sovlm import Generator, build_from_paths
48
+ from pathlib import Path
49
+
50
+ # Build
51
+ d, ng, sg, inv, fz = build_from_paths([Path("corpus.md")], ...)
52
+
53
+ # Generate
54
+ gen = Generator(d, kn, sg, fz, inv, blender, sampler)
55
+ result = gen.generate("theorem xor_assoc : ", max_tokens=100)
56
+ ```
57
+
58
+ ## Architecture
59
+
60
+ | Component | Role |
61
+ |---|---|
62
+ | `Dictionary` | Vocabulary sovereignty — you own the tokens |
63
+ | `NGramIndex` | Local coherence — what follows what |
64
+ | `KneserNey` | Smoothing — handle unseen contexts |
65
+ | `SkipGramIndex` | Structural patterns at distance |
66
+ | `FuzzyPrefixIndex` | LSH near-miss — graceful degradation |
67
+ | `InvertedIndex + BM25` | Retrieval — what's relevant in corpus |
68
+ | `Blender` | Arbitration — Markov vs retrieval |
69
+ | `Sampler + QRNG` | Entropy — unbiased, quantum-seeded choice |
70
+
71
+ ## SnapKitty Stack Integration
72
+
73
+ ```
74
+ sovlm ──► abjad-machine (SUBLEQ address space)
75
+ ──► sovereign-transformer (plasma gate)
76
+ ──► the-49th-call (Lean 4 verified)
77
+ ──► bob-orchestrator (Byzantine council)
78
+ ```
79
+
80
+ ---
81
+
82
+ *Ahmad Ali Parr · SnapKitty Collective · 2026*
pyproject.toml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [project]
2
+ name = "sovlm"
3
+ version = "0.1.0"
4
+ description = "Sovereign Statistical LM — N-grams + Kneser-Ney + BM25 Retrieval, zero training, zero GPU"
5
+ readme = "README.md"
6
+ requires-python = ">=3.11"
7
+ dependencies = [
8
+ "click",
9
+ "rich",
10
+ "pydantic",
11
+ "pyyaml",
12
+ "numpy",
13
+ "scipy",
14
+ "xxhash",
15
+ "orjson",
16
+ "gitpython",
17
+ "httpx",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ qrng = ["qiskit-ibm-runtime"]
22
+ dev = ["pytest", "pytest-cov", "ruff", "mypy"]
23
+
24
+ [project.scripts]
25
+ sovlm = "sovlm.cli:app"
26
+
27
+ [build-system]
28
+ requires = ["hatchling"]
29
+ build-backend = "hatchling.build"
30
+
31
+ [tool.hatch.build.targets.wheel]
32
+ packages = ["src/sovlm"]
33
+
34
+ [tool.ruff]
35
+ line-length = 100
36
+ target-version = "py311"
src/sovlm/__init__.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from .dictionary import Dictionary
2
+ from .ngram_index import NGramIndex
3
+ from .kneser_ney import KneserNey
4
+ from .skipgram import SkipGramIndex
5
+ from .fuzzy_prefix import FuzzyPrefixIndex
6
+ from .inverted_index import InvertedIndex
7
+ from .sampler import Sampler, SystemRNG
8
+ from .blender import Blender
9
+ from .generator import Generator
10
+ from .corpus import build_from_paths
11
+
12
+ __all__ = [
13
+ "Dictionary", "NGramIndex", "KneserNey", "SkipGramIndex",
14
+ "FuzzyPrefixIndex", "InvertedIndex", "Sampler", "SystemRNG",
15
+ "Blender", "Generator", "build_from_paths",
16
+ ]
src/sovlm/blender.py ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass
3
+
4
+
5
+ @dataclass(slots=True)
6
+ class Blender:
7
+ markov: object
8
+ retrieval: object
9
+ dictionary: object
10
+ sampler: object
11
+ min_markov_count: int = 5
12
+
13
+ def _markov_confidence(self, context: tuple[int, ...]) -> float:
14
+ bucket = self.markov.index.get_bucket(context) if hasattr(self.markov, 'index') else {}
15
+ total = sum(bucket.values()) if bucket else 0
16
+ return min(1.0, total / (self.min_markov_count * 2))
17
+
18
+ def _retrieval_distribution(self, context: tuple[int, ...]) -> dict[int, float]:
19
+ results = self.retrieval.retrieve(list(context), top_k=3)
20
+ if not results:
21
+ return {}
22
+ _, chunk_id, _ = results[0]
23
+ chunk_tokens = self.retrieval.chunk_token_ids[chunk_id]
24
+ if len(chunk_tokens) > len(context):
25
+ return {chunk_tokens[len(context)]: 1.0}
26
+ return {}
27
+
28
+ def blended_distribution(self, context: tuple[int, ...], temperature: float) -> dict[int, float]:
29
+ alpha = self._markov_confidence(context)
30
+ p_markov = self.markov.distribution(context, temperature)
31
+ p_retrieval = self._retrieval_distribution(context)
32
+ if not p_retrieval:
33
+ return p_markov
34
+ if not p_markov:
35
+ return p_retrieval
36
+ blended = {}
37
+ for tok in set(p_markov) | set(p_retrieval):
38
+ blended[tok] = alpha * p_markov.get(tok, 0) + (1 - alpha) * p_retrieval.get(tok, 0)
39
+ total = sum(blended.values())
40
+ return {k: v / total for k, v in blended.items()} if total > 0 else blended
41
+
42
+ def sample_next(self, context: tuple[int, ...], temperature: float = 1.0) -> int:
43
+ return self.sampler.sample(self.blended_distribution(context, temperature))
src/sovlm/cli.py ADDED
@@ -0,0 +1,96 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import click
3
+ from rich.console import Console
4
+ from pathlib import Path
5
+ import sys
6
+
7
+ console = Console()
8
+
9
+ MODEL_DIR = Path(".sovlm_model")
10
+ DICT_PATH = MODEL_DIR / "dictionary.bin"
11
+ NGRAM_PATH = MODEL_DIR / "ngram.bin"
12
+ SKIPGRAM_PATH = MODEL_DIR / "skipgram.bin"
13
+ INVERTED_PATH = MODEL_DIR / "inverted.bin"
14
+ FUZZY_PATH = MODEL_DIR / "fuzzy.bin"
15
+
16
+
17
+ def load_model():
18
+ from sovlm.dictionary import Dictionary
19
+ from sovlm.ngram_index import NGramIndex
20
+ from sovlm.skipgram import SkipGramIndex
21
+ from sovlm.kneser_ney import KneserNey
22
+ from sovlm.fuzzy_prefix import FuzzyPrefixIndex
23
+ from sovlm.inverted_index import InvertedIndex
24
+ from sovlm.blender import Blender
25
+ from sovlm.sampler import Sampler, SystemRNG
26
+ from sovlm.generator import Generator
27
+
28
+ dictionary = Dictionary.load(DICT_PATH)
29
+ ngram = NGramIndex.load(NGRAM_PATH)
30
+ skipgram = SkipGramIndex.load(SKIPGRAM_PATH)
31
+ inverted = InvertedIndex.load(INVERTED_PATH)
32
+ fuzzy = FuzzyPrefixIndex()
33
+ fuzzy.build_from_index(ngram)
34
+ kn = KneserNey(ngram)
35
+ sampler = Sampler(rng=SystemRNG(), temperature=0.8)
36
+ blender = Blender(kn, inverted, dictionary, sampler)
37
+ return Generator(dictionary, kn, skipgram, fuzzy, inverted, blender, sampler)
38
+
39
+
40
+ @click.group()
41
+ def app():
42
+ """SovLM — Sovereign Statistical Language Model. No training. No GPU. Pure governance."""
43
+ pass
44
+
45
+
46
+ @app.command()
47
+ @click.argument("paths", nargs=-1, type=click.Path(exists=True, path_type=Path))
48
+ @click.option("--order", "-n", default=4, help="N-gram order (default 4)")
49
+ @click.option("--chunk-size", default=256, help="Retrieval chunk size")
50
+ def build(paths, order, chunk_size):
51
+ """Build model from corpus files (.txt .md .lean .pl .jsonl)."""
52
+ if not paths:
53
+ console.print("[red]Provide corpus paths[/red]"); sys.exit(1)
54
+ MODEL_DIR.mkdir(exist_ok=True)
55
+ from sovlm.corpus import build_from_paths
56
+ console.print(f"[green]Building from {len(paths)} files (order={order})...[/green]")
57
+ d, ng, sg, inv, fz = build_from_paths(
58
+ list(paths), DICT_PATH, NGRAM_PATH, SKIPGRAM_PATH, INVERTED_PATH, FUZZY_PATH,
59
+ ngram_order=order, chunk_size=chunk_size)
60
+ console.print(f"[green]Done.[/green] vocab={len(d)} buckets={len(ng.buckets)} chunks={inv.total_chunks}")
61
+
62
+
63
+ @app.command()
64
+ @click.option("--prompt", "-p", default="", help="Prompt")
65
+ @click.option("--max-tokens", "-m", default=128)
66
+ @click.option("--temperature", "-t", default=0.8)
67
+ @click.option("--stream", "do_stream", is_flag=True, help="Stream output token by token")
68
+ @click.option("--qrng", is_flag=True, help="Use quantum RNG (ANU)")
69
+ def generate(prompt, max_tokens, temperature, do_stream, qrng):
70
+ """Generate text from a prompt."""
71
+ gen = load_model()
72
+ if qrng:
73
+ from sovlm.sampler import QRNGClient
74
+ gen.sampler.rng = QRNGClient()
75
+ console.print("[yellow]QRNG active[/yellow]")
76
+ if do_stream:
77
+ console.print(f"[bold]{prompt}[/bold]", end="")
78
+ for tok in gen.stream(prompt, max_tokens=max_tokens, temperature=temperature):
79
+ console.print(tok + " ", end="")
80
+ console.print()
81
+ else:
82
+ out = gen.generate(prompt, max_tokens=max_tokens, temperature=temperature)
83
+ console.print(f"[bold]{prompt}[/bold]{out}")
84
+
85
+
86
+ @app.command()
87
+ @click.option("--port", default=8080)
88
+ def serve(port):
89
+ """HTTP API server (FastAPI + uvicorn)."""
90
+ try:
91
+ import uvicorn
92
+ from sovlm.api import create_app
93
+ gen = load_model()
94
+ uvicorn.run(create_app(gen), host="0.0.0.0", port=port)
95
+ except ImportError:
96
+ console.print("[red]Install uvicorn + fastapi: pip install uvicorn fastapi[/red]")
src/sovlm/corpus.py ADDED
@@ -0,0 +1,74 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from pathlib import Path
3
+ import orjson
4
+ import re
5
+
6
+ from .dictionary import Dictionary
7
+ from .ngram_index import NGramIndex
8
+ from .skipgram import SkipGramIndex
9
+ from .inverted_index import InvertedIndex
10
+ from .fuzzy_prefix import FuzzyPrefixIndex
11
+
12
+
13
+ def chunk_text(text: str, chunk_size: int = 256, overlap: int = 32) -> list[str]:
14
+ words = text.split()
15
+ return [" ".join(words[i:i + chunk_size]) for i in range(0, len(words), chunk_size - overlap) if words[i:i + chunk_size]]
16
+
17
+
18
+ def tokenize(text: str) -> list[str]:
19
+ text = re.sub(r'([.,!?;:()\[\]{}"\'])', r' \1 ', text)
20
+ return text.split()
21
+
22
+
23
+ def build_from_paths(
24
+ paths: list[Path],
25
+ dict_path: Path,
26
+ ngram_path: Path,
27
+ skipgram_path: Path,
28
+ inverted_path: Path,
29
+ fuzzy_path: Path,
30
+ ngram_order: int = 4,
31
+ chunk_size: int = 256,
32
+ ) -> tuple[Dictionary, NGramIndex, SkipGramIndex, InvertedIndex, FuzzyPrefixIndex]:
33
+ dictionary = Dictionary()
34
+ ngram = NGramIndex(order=ngram_order)
35
+ skipgram = SkipGramIndex()
36
+ inverted = InvertedIndex()
37
+ all_seqs: list[list[int]] = []
38
+ chunk_id = 0
39
+
40
+ for path in paths:
41
+ text = path.read_text(encoding="utf-8", errors="ignore")
42
+ if path.suffix == ".jsonl":
43
+ for line in text.strip().split("\n"):
44
+ try:
45
+ item = orjson.loads(line)
46
+ t = item.get("text", "") or item.get("content", "")
47
+ ids = [dictionary.add(tok) for tok in tokenize(t)]
48
+ all_seqs.append(ids)
49
+ for chunk in chunk_text(t, chunk_size):
50
+ cids = [dictionary.add(tok) for tok in tokenize(chunk)]
51
+ inverted.add_chunk(chunk_id, chunk, cids); chunk_id += 1
52
+ except Exception:
53
+ pass
54
+ else:
55
+ ids = [dictionary.add(tok) for tok in tokenize(text)]
56
+ all_seqs.append(ids)
57
+ for chunk in chunk_text(text, chunk_size):
58
+ cids = [dictionary.add(tok) for tok in tokenize(chunk)]
59
+ inverted.add_chunk(chunk_id, chunk, cids); chunk_id += 1
60
+
61
+ dictionary.freeze()
62
+ for seq in all_seqs:
63
+ ngram.add_sequence(seq)
64
+ skipgram.add_sequence(seq)
65
+
66
+ fuzzy = FuzzyPrefixIndex()
67
+ fuzzy.build_from_index(ngram)
68
+
69
+ dictionary.save(dict_path)
70
+ ngram.save(ngram_path)
71
+ skipgram.save(skipgram_path)
72
+ inverted.save(inverted_path)
73
+
74
+ return dictionary, ngram, skipgram, inverted, fuzzy
src/sovlm/dictionary.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ import orjson
3
+ from pathlib import Path
4
+ from dataclasses import dataclass, field
5
+
6
+
7
+ @dataclass(slots=True)
8
+ class Dictionary:
9
+ token2id: dict[str, int] = field(default_factory=dict)
10
+ id2token: list[str] = field(default_factory=list)
11
+ _frozen: bool = False
12
+
13
+ SPECIAL_TOKENS = ["<PAD>", "<UNK>", "<BOS>", "<EOS>"]
14
+ PAD_ID, UNK_ID, BOS_ID, EOS_ID = 0, 1, 2, 3
15
+
16
+ def __post_init__(self):
17
+ for tok in self.SPECIAL_TOKENS:
18
+ if tok not in self.token2id:
19
+ self._add(tok)
20
+
21
+ def _add(self, token: str) -> int:
22
+ if self._frozen:
23
+ raise RuntimeError("Dictionary is frozen")
24
+ idx = len(self.id2token)
25
+ self.token2id[token] = idx
26
+ self.id2token.append(token)
27
+ return idx
28
+
29
+ def add(self, token: str) -> int:
30
+ return self.token2id.get(token) if token in self.token2id else self._add(token)
31
+
32
+ def __getitem__(self, token: str) -> int:
33
+ return self.token2id.get(token, self.UNK_ID)
34
+
35
+ def token(self, idx: int) -> str:
36
+ return self.id2token[idx] if 0 <= idx < len(self.id2token) else "<UNK>"
37
+
38
+ def freeze(self) -> None:
39
+ self._frozen = True
40
+
41
+ def __len__(self) -> int:
42
+ return len(self.id2token)
43
+
44
+ def save(self, path: Path) -> None:
45
+ path.write_bytes(orjson.dumps({"token2id": self.token2id, "id2token": self.id2token}))
46
+
47
+ @classmethod
48
+ def load(cls, path: Path) -> Dictionary:
49
+ data = orjson.loads(path.read_bytes())
50
+ d = cls()
51
+ d.token2id = data["token2id"]
52
+ d.id2token = data["id2token"]
53
+ d._frozen = True
54
+ return d
55
+
56
+ def encode(self, text: str) -> list[int]:
57
+ return [self[tok] for tok in text.split()]
58
+
59
+ def decode(self, ids: list[int]) -> str:
60
+ skip = {self.PAD_ID, self.BOS_ID, self.EOS_ID}
61
+ return " ".join(self.token(i) for i in ids if i not in skip)
src/sovlm/fuzzy_prefix.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from collections import defaultdict
3
+ from dataclasses import dataclass, field
4
+ import xxhash
5
+ import numpy as np
6
+
7
+
8
+ @dataclass(slots=True)
9
+ class FuzzyPrefixIndex:
10
+ num_hashes: int = 16
11
+ num_bands: int = 4
12
+ band_size: int = 4
13
+ buckets: dict[int, list[tuple[int, ...]]] = field(default_factory=lambda: defaultdict(list))
14
+ prefixes: set[tuple[int, ...]] = field(default_factory=set)
15
+
16
+ def _seeds(self) -> np.ndarray:
17
+ return np.arange(self.num_hashes, dtype=np.uint64) * 0x9e3779b97f4a7c15 + 0xbf58476d1ce4e5b9
18
+
19
+ def _signature(self, prefix: tuple[int, ...]) -> np.ndarray:
20
+ seeds = self._seeds()
21
+ sig = np.full(self.num_hashes, np.iinfo(np.uint64).max, dtype=np.uint64)
22
+ for pos, token in enumerate(prefix):
23
+ for h in range(self.num_hashes):
24
+ val = xxhash.xxh64(token.to_bytes(8, 'little', signed=False), seed=int(seeds[h] + pos)).intdigest()
25
+ if val < sig[h]:
26
+ sig[h] = val
27
+ return sig
28
+
29
+ def _band_key(self, sig: np.ndarray, band: int) -> int:
30
+ start = band * self.band_size
31
+ key = 0
32
+ for v in sig[start:start + self.band_size]:
33
+ key = (key * 0x9e3779b97f4a7c15 + v) & 0xFFFFFFFFFFFFFFFF
34
+ return key
35
+
36
+ def add(self, prefix: tuple[int, ...]) -> None:
37
+ if prefix in self.prefixes:
38
+ return
39
+ self.prefixes.add(prefix)
40
+ sig = self._signature(prefix)
41
+ for band in range(self.num_bands):
42
+ self.buckets[self._band_key(sig, band)].append(prefix)
43
+
44
+ def query(self, prefix: tuple[int, ...], max_candidates: int = 50) -> list[tuple[int, ...]]:
45
+ sig = self._signature(prefix)
46
+ candidates: set[tuple[int, ...]] = set()
47
+ for band in range(self.num_bands):
48
+ candidates.update(self.buckets.get(self._band_key(sig, band), []))
49
+ scored = sorted([(np.sum(sig == self._signature(c)) / self.num_hashes, c) for c in candidates], reverse=True)
50
+ return [c for _, c in scored[:max_candidates]]
51
+
52
+ def build_from_index(self, ngram_index) -> None:
53
+ for prefix in ngram_index.buckets.keys():
54
+ self.add(prefix)
src/sovlm/generator.py ADDED
@@ -0,0 +1,64 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from dataclasses import dataclass
3
+ from typing import Iterator
4
+
5
+
6
+ @dataclass
7
+ class Generator:
8
+ dictionary: object
9
+ kn: object
10
+ skipgram: object
11
+ fuzzy: object
12
+ inverted: object
13
+ blender: object
14
+ sampler: object
15
+
16
+ def generate(self, prompt: str = "", max_tokens: int = 128, temperature: float = 0.8,
17
+ stop_tokens: set[str] | None = None) -> str:
18
+ stop_ids = {self.dictionary[tok] for tok in (stop_tokens or {"<EOS>"})}
19
+ context_ids = [self.dictionary.BOS_ID] + self.dictionary.encode(prompt)
20
+ generated = []
21
+ order = self.kn.index.order
22
+
23
+ for _ in range(max_tokens):
24
+ context = tuple(context_ids[-(order - 1):])
25
+ if not self.kn.index.has_prefix(context) and self.fuzzy.prefixes:
26
+ candidates = self.fuzzy.query(context, max_candidates=5)
27
+ if candidates:
28
+ dists = [self.kn.distribution(c, temperature) for c in candidates]
29
+ blended: dict[int, float] = {}
30
+ for d in dists:
31
+ for k, v in d.items():
32
+ blended[k] = blended.get(k, 0) + v
33
+ total = sum(blended.values())
34
+ dist = {k: v / total for k, v in blended.items()} if total > 0 else {}
35
+ else:
36
+ dist = self.kn.distribution(context, temperature)
37
+ else:
38
+ dist = self.kn.distribution(context, temperature)
39
+
40
+ if self.inverted.total_chunks > 0:
41
+ next_id = self.blender.sample_next(context, temperature)
42
+ else:
43
+ next_id = self.sampler.sample(dist)
44
+
45
+ if next_id in stop_ids:
46
+ break
47
+ generated.append(next_id)
48
+ context_ids.append(next_id)
49
+
50
+ return self.dictionary.decode(generated)
51
+
52
+ def stream(self, prompt: str = "", **kwargs) -> Iterator[str]:
53
+ stop_ids = {self.dictionary[tok] for tok in kwargs.get("stop_tokens", {"<EOS>"})}
54
+ context_ids = [self.dictionary.BOS_ID] + self.dictionary.encode(prompt)
55
+ order = self.kn.index.order
56
+ temperature = kwargs.get("temperature", 0.8)
57
+ for _ in range(kwargs.get("max_tokens", 128)):
58
+ context = tuple(context_ids[-(order - 1):])
59
+ dist = self.kn.distribution(context, temperature)
60
+ next_id = self.sampler.sample(dist)
61
+ if next_id in stop_ids:
62
+ break
63
+ context_ids.append(next_id)
64
+ yield self.dictionary.token(next_id)
src/sovlm/inverted_index.py ADDED
@@ -0,0 +1,75 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from collections import Counter, defaultdict
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ import math
6
+ import orjson
7
+
8
+
9
+ @dataclass(slots=True)
10
+ class InvertedIndex:
11
+ postings: dict[int, list[tuple[int, int]]] = field(default_factory=lambda: defaultdict(list))
12
+ chunk_lengths: list[int] = field(default_factory=list)
13
+ chunk_texts: list[str] = field(default_factory=list)
14
+ chunk_token_ids: list[list[int]] = field(default_factory=list)
15
+ total_chunks: int = 0
16
+ avg_chunk_len: float = 0.0
17
+ BM25_K1: float = 1.5
18
+ BM25_B: float = 0.75
19
+
20
+ def add_chunk(self, chunk_id: int, text: str, token_ids: list[int]) -> None:
21
+ self.chunk_texts.append(text)
22
+ self.chunk_token_ids.append(token_ids)
23
+ self.chunk_lengths.append(len(token_ids))
24
+ self.total_chunks += 1
25
+ for tok, count in Counter(token_ids).items():
26
+ self.postings[tok].append((chunk_id, count))
27
+ self.avg_chunk_len = sum(self.chunk_lengths) / self.total_chunks
28
+
29
+ def bm25_score(self, query_ids: list[int], chunk_id: int) -> float:
30
+ score = 0.0
31
+ chunk_len = self.chunk_lengths[chunk_id]
32
+ for tok, qf in Counter(query_ids).items():
33
+ postings = self.postings.get(tok, [])
34
+ df = len(postings)
35
+ if df == 0:
36
+ continue
37
+ idf = math.log((self.total_chunks - df + 0.5) / (df + 0.5) + 1.0)
38
+ tf = next((c for cid, c in postings if cid == chunk_id), 0)
39
+ if tf == 0:
40
+ continue
41
+ denom = tf + self.BM25_K1 * (1 - self.BM25_B + self.BM25_B * chunk_len / self.avg_chunk_len)
42
+ score += idf * (tf * (self.BM25_K1 + 1)) / denom
43
+ return score
44
+
45
+ def retrieve(self, query_ids: list[int], top_k: int = 5) -> list[tuple[float, int, str]]:
46
+ if not query_ids:
47
+ return []
48
+ candidates = set()
49
+ for tok in query_ids:
50
+ for cid, _ in self.postings.get(tok, []):
51
+ candidates.add(cid)
52
+ scored = sorted([(self.bm25_score(query_ids, cid), cid) for cid in candidates], reverse=True)
53
+ return [(score, cid, self.chunk_texts[cid]) for score, cid in scored[:top_k]]
54
+
55
+ def save(self, path: Path) -> None:
56
+ path.write_bytes(orjson.dumps({
57
+ "postings": {str(k): v for k, v in self.postings.items()},
58
+ "chunk_lengths": self.chunk_lengths,
59
+ "chunk_texts": self.chunk_texts,
60
+ "chunk_token_ids": self.chunk_token_ids,
61
+ "total_chunks": self.total_chunks,
62
+ "avg_chunk_len": self.avg_chunk_len,
63
+ }))
64
+
65
+ @classmethod
66
+ def load(cls, path: Path) -> InvertedIndex:
67
+ data = orjson.loads(path.read_bytes())
68
+ idx = cls()
69
+ idx.postings = defaultdict(list, {int(k): v for k, v in data["postings"].items()})
70
+ idx.chunk_lengths = data["chunk_lengths"]
71
+ idx.chunk_texts = data["chunk_texts"]
72
+ idx.chunk_token_ids = data["chunk_token_ids"]
73
+ idx.total_chunks = data["total_chunks"]
74
+ idx.avg_chunk_len = data["avg_chunk_len"]
75
+ return idx
src/sovlm/kneser_ney.py ADDED
@@ -0,0 +1,57 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from collections import Counter
3
+ from dataclasses import dataclass
4
+
5
+
6
+ @dataclass(slots=True)
7
+ class KneserNey:
8
+ index: object
9
+ discount: float = 0.75
10
+
11
+ def _discounted_prob(self, prefix: tuple[int, ...], tail: int) -> float:
12
+ bucket = self.index.get_bucket(prefix)
13
+ if not bucket:
14
+ return 0.0
15
+ total = self.index.context_counts[prefix]
16
+ return max(bucket.get(tail, 0) - self.discount, 0) / total
17
+
18
+ def _lambda(self, prefix: tuple[int, ...]) -> float:
19
+ bucket = self.index.get_bucket(prefix)
20
+ if not bucket:
21
+ return 1.0
22
+ total = self.index.context_counts[prefix]
23
+ return (self.discount * len(bucket)) / total
24
+
25
+ def _continuation_prob(self, tail: int) -> float:
26
+ total = sum(self.index.continuation_counts.values())
27
+ if total == 0:
28
+ return 1.0 / max(self.index.vocab_size(), 1)
29
+ return self.index.continuation_counts.get(tail, 0) / total
30
+
31
+ def prob(self, context: tuple[int, ...], tail: int, temperature: float = 1.0) -> float:
32
+ order = self.index.order
33
+ if len(context) > order - 1:
34
+ context = context[-(order - 1):]
35
+ if len(context) == 0:
36
+ p = self._continuation_prob(tail)
37
+ return p ** (1.0 / temperature) if temperature != 1.0 else p
38
+ if self.index.has_prefix(context):
39
+ p = self._discounted_prob(context, tail) + self._lambda(context) * self.prob(context[1:], tail, temperature)
40
+ return p ** (1.0 / temperature) if temperature != 1.0 else p
41
+ return self.prob(context[1:], tail, temperature)
42
+
43
+ def distribution(self, context: tuple[int, ...], temperature: float = 1.0) -> dict[int, float]:
44
+ candidates: set[int] = set()
45
+ ctx = context
46
+ while True:
47
+ if self.index.has_prefix(ctx):
48
+ candidates.update(self.index.get_bucket(ctx).keys())
49
+ if len(ctx) == 0:
50
+ candidates.update(self.index.continuation_counts.keys())
51
+ break
52
+ ctx = ctx[1:]
53
+ probs = {t: self.prob(context, t, temperature) for t in candidates}
54
+ total = sum(probs.values())
55
+ if total > 0:
56
+ probs = {k: v / total for k, v in probs.items()}
57
+ return probs
src/sovlm/ngram_index.py ADDED
@@ -0,0 +1,56 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from collections import Counter, defaultdict
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ import orjson
6
+
7
+
8
+ @dataclass(slots=True)
9
+ class NGramIndex:
10
+ order: int
11
+ buckets: dict[tuple[int, ...], Counter] = field(default_factory=lambda: defaultdict(Counter))
12
+ context_counts: Counter = field(default_factory=Counter)
13
+ continuation_counts: Counter = field(default_factory=Counter)
14
+
15
+ def add_sequence(self, ids: list[int]) -> None:
16
+ if len(ids) < self.order:
17
+ return
18
+ for i in range(len(ids) - self.order + 1):
19
+ prefix = tuple(ids[i:i + self.order - 1])
20
+ tail = ids[i + self.order - 1]
21
+ self.buckets[prefix][tail] += 1
22
+ self.context_counts[prefix] += 1
23
+ self._compute_continuation_counts()
24
+
25
+ def _compute_continuation_counts(self) -> None:
26
+ self.continuation_counts.clear()
27
+ for prefix, counter in self.buckets.items():
28
+ for tail in counter:
29
+ self.continuation_counts[tail] += 1
30
+
31
+ def get_bucket(self, prefix: tuple[int, ...]) -> Counter:
32
+ return self.buckets.get(prefix, Counter())
33
+
34
+ def has_prefix(self, prefix: tuple[int, ...]) -> bool:
35
+ return prefix in self.buckets
36
+
37
+ def vocab_size(self) -> int:
38
+ return len(self.continuation_counts)
39
+
40
+ def save(self, path: Path) -> None:
41
+ data = {
42
+ "order": self.order,
43
+ "buckets": [[list(k), [[t, c] for t, c in v.items()]] for k, v in self.buckets.items()],
44
+ }
45
+ path.write_bytes(orjson.dumps(data))
46
+
47
+ @classmethod
48
+ def load(cls, path: Path) -> NGramIndex:
49
+ data = orjson.loads(path.read_bytes())
50
+ idx = cls(order=data["order"])
51
+ for prefix_list, tail_counts in data["buckets"]:
52
+ prefix = tuple(prefix_list)
53
+ idx.buckets[prefix] = Counter({t: c for t, c in tail_counts})
54
+ idx.context_counts[prefix] = sum(c for _, c in tail_counts)
55
+ idx._compute_continuation_counts()
56
+ return idx
src/sovlm/sampler.py ADDED
@@ -0,0 +1,80 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from collections import deque
3
+ from dataclasses import dataclass, field
4
+ import numpy as np
5
+ import os
6
+ import httpx
7
+
8
+
9
+ class SystemRNG:
10
+ def random(self) -> float:
11
+ return int.from_bytes(os.urandom(8), 'little') / 2**64
12
+ def bytes(self, n: int) -> bytes:
13
+ return os.urandom(n)
14
+
15
+
16
+ class QRNGClient:
17
+ def __init__(self, url: str = "https://qrng.anu.edu.au/API/jsonI.php", api_key: str | None = None):
18
+ self.url = url
19
+ self.api_key = api_key
20
+ self._buffer: bytearray = bytearray()
21
+ self._client = httpx.Client(timeout=10.0)
22
+
23
+ def _refill(self, n: int) -> None:
24
+ params = {"length": max(n, 1024), "type": "uint8"}
25
+ if self.api_key:
26
+ params["api_key"] = self.api_key
27
+ resp = self._client.get(self.url, params=params)
28
+ resp.raise_for_status()
29
+ self._buffer.extend(bytes(resp.json()["data"]))
30
+
31
+ def random(self) -> float:
32
+ if len(self._buffer) < 8:
33
+ self._refill(1024)
34
+ val = int.from_bytes(self._buffer[:8], 'little')
35
+ self._buffer = self._buffer[8:]
36
+ return val / 2**64
37
+
38
+ def bytes(self, n: int) -> bytes:
39
+ while len(self._buffer) < n:
40
+ self._refill(n)
41
+ out = bytes(self._buffer[:n])
42
+ self._buffer = self._buffer[n:]
43
+ return out
44
+
45
+
46
+ @dataclass(slots=True)
47
+ class Sampler:
48
+ rng: object
49
+ temperature: float = 1.0
50
+ repetition_penalty: float = 1.1
51
+ decay_window: int = 64
52
+ decay_factor: float = 0.95
53
+ _recent: deque = field(default_factory=deque)
54
+ _penalties: dict[int, float] = field(default_factory=dict)
55
+
56
+ def sample(self, probs: dict[int, float]) -> int:
57
+ if not probs:
58
+ return 0
59
+ adjusted = {tok: p / self._penalties.get(tok, 1.0) if self._penalties.get(tok, 1.0) > 1.0
60
+ else p * self._penalties.get(tok, 1.0) for tok, p in probs.items()}
61
+ if self.temperature != 1.0:
62
+ adjusted = {k: v ** (1.0 / self.temperature) for k, v in adjusted.items()}
63
+ total = sum(adjusted.values())
64
+ if total == 0:
65
+ return max(probs, key=probs.get)
66
+ tokens, weights = zip(*adjusted.items())
67
+ weights = np.array(weights, dtype=np.float64) / total
68
+ r = self.rng.random()
69
+ idx = int(np.searchsorted(np.cumsum(weights), r))
70
+ chosen = tokens[min(idx, len(tokens) - 1)]
71
+ self._recent.append(chosen)
72
+ if len(self._recent) > self.decay_window:
73
+ old = self._recent.popleft()
74
+ self._penalties[old] = max(1.0, self._penalties.get(old, 1.0) * self.decay_factor)
75
+ self._penalties[chosen] = self._penalties.get(chosen, 1.0) * self.repetition_penalty
76
+ return chosen
77
+
78
+ def reset(self) -> None:
79
+ self._recent.clear()
80
+ self._penalties.clear()
src/sovlm/skipgram.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from __future__ import annotations
2
+ from collections import Counter, defaultdict
3
+ from dataclasses import dataclass, field
4
+ from pathlib import Path
5
+ import orjson
6
+
7
+ DEFAULT_SKIP_PATTERNS = [(-1,), (-2,), (-1, -2), (-1, -3), (-2, -3), (-1, -2, -3), (-1, -2, -4)]
8
+
9
+
10
+ @dataclass(slots=True)
11
+ class SkipGramIndex:
12
+ patterns: list[tuple[int, ...]] = field(default_factory=lambda: DEFAULT_SKIP_PATTERNS)
13
+ buckets: dict[tuple[int, ...], Counter] = field(default_factory=lambda: defaultdict(Counter))
14
+ context_counts: Counter = field(default_factory=Counter)
15
+
16
+ def add_sequence(self, ids: list[int]) -> None:
17
+ for i in range(len(ids)):
18
+ target = ids[i]
19
+ for pattern in self.patterns:
20
+ parts = []
21
+ valid = True
22
+ for offset in pattern:
23
+ pos = i + offset
24
+ if pos < 0 or pos >= len(ids):
25
+ valid = False
26
+ break
27
+ parts.append(ids[pos])
28
+ if not valid:
29
+ continue
30
+ prefix = tuple(parts)
31
+ self.buckets[prefix][target] += 1
32
+ self.context_counts[prefix] += 1
33
+
34
+ def get_bucket(self, prefix: tuple[int, ...]) -> Counter:
35
+ return self.buckets.get(prefix, Counter())
36
+
37
+ def has_prefix(self, prefix: tuple[int, ...]) -> bool:
38
+ return prefix in self.buckets
39
+
40
+ def vocab_size(self) -> int:
41
+ vocab = set()
42
+ for c in self.buckets.values():
43
+ vocab.update(c.keys())
44
+ return len(vocab)
45
+
46
+ def save(self, path: Path) -> None:
47
+ data = {
48
+ "patterns": [list(p) for p in self.patterns],
49
+ "buckets": [[list(k), [[t, c] for t, c in v.items()]] for k, v in self.buckets.items()],
50
+ }
51
+ path.write_bytes(orjson.dumps(data))
52
+
53
+ @classmethod
54
+ def load(cls, path: Path) -> SkipGramIndex:
55
+ data = orjson.loads(path.read_bytes())
56
+ idx = cls(patterns=[tuple(p) for p in data["patterns"]])
57
+ for prefix_list, tail_counts in data["buckets"]:
58
+ prefix = tuple(prefix_list)
59
+ idx.buckets[prefix] = Counter({t: c for t, c in tail_counts})
60
+ idx.context_counts[prefix] = sum(c for _, c in tail_counts)
61
+ return idx
tests/test_bm25.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sovlm.dictionary import Dictionary
2
+ from sovlm.inverted_index import InvertedIndex
3
+ from sovlm.corpus import tokenize
4
+
5
+
6
+ def test_bm25_retrieval():
7
+ d = Dictionary()
8
+ inv = InvertedIndex()
9
+
10
+ chunks = [
11
+ "the cat sat on the mat",
12
+ "the dog ran in the park",
13
+ "quantum mechanics governs atomic transitions",
14
+ ]
15
+ for i, text in enumerate(chunks):
16
+ ids = [d.add(tok) for tok in tokenize(text)]
17
+ inv.add_chunk(i, text, ids)
18
+ d.freeze()
19
+
20
+ query = [d["the"], d["cat"]]
21
+ results = inv.retrieve(query, top_k=2)
22
+ assert len(results) > 0
23
+ assert results[0][1] == 0 # chunk 0 has "cat"
tests/test_kn_smoothing.py ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from sovlm.dictionary import Dictionary
2
+ from sovlm.ngram_index import NGramIndex
3
+ from sovlm.kneser_ney import KneserNey
4
+
5
+
6
+ def test_kn_basic():
7
+ d = Dictionary()
8
+ corpus = "the cat sat on the mat the cat ate the rat"
9
+ ids = [d.add(t) for t in corpus.split()]
10
+ d.freeze()
11
+
12
+ ng = NGramIndex(order=3)
13
+ ng.add_sequence(ids)
14
+ kn = KneserNey(ng)
15
+
16
+ context = (d["the"], d["cat"])
17
+ dist = kn.distribution(context)
18
+ assert len(dist) > 0
19
+ assert abs(sum(dist.values()) - 1.0) < 1e-6
20
+
21
+
22
+ def test_kn_backoff():
23
+ d = Dictionary()
24
+ ids = [d.add(t) for t in "a b c d e".split()]
25
+ d.freeze()
26
+ ng = NGramIndex(order=2)
27
+ ng.add_sequence(ids)
28
+ kn = KneserNey(ng)
29
+ # unseen context should backoff gracefully
30
+ dist = kn.distribution((d["e"],))
31
+ assert isinstance(dist, dict)