sperner 0.1.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.
Files changed (47) hide show
  1. sperner-0.1.0/.gitattributes +35 -0
  2. sperner-0.1.0/.github/workflows/publish.yml +45 -0
  3. sperner-0.1.0/.github/workflows/test.yml +30 -0
  4. sperner-0.1.0/.gitignore +167 -0
  5. sperner-0.1.0/LICENSE +22 -0
  6. sperner-0.1.0/PKG-INFO +219 -0
  7. sperner-0.1.0/README.md +175 -0
  8. sperner-0.1.0/app.py +15 -0
  9. sperner-0.1.0/data/sperner_dataset.json +98692 -0
  10. sperner-0.1.0/docs/API_REFERENCE.md +123 -0
  11. sperner-0.1.0/docs/ARCHITECTURE.md +32 -0
  12. sperner-0.1.0/docs/MODEL_CARD_INTEGRATION.md +31 -0
  13. sperner-0.1.0/docs/THEORY.md +32 -0
  14. sperner-0.1.0/examples/README.md +12 -0
  15. sperner-0.1.0/examples/generate_sperner_dataset.py +125 -0
  16. sperner-0.1.0/examples/moe_routing_example.py +36 -0
  17. sperner-0.1.0/examples/quickstart.py +49 -0
  18. sperner-0.1.0/examples/surrogate_example.py +41 -0
  19. sperner-0.1.0/pyproject.toml +62 -0
  20. sperner-0.1.0/requirements.txt +14 -0
  21. sperner-0.1.0/scripts/publish_to_hf.py +93 -0
  22. sperner-0.1.0/sperner/__init__.py +78 -0
  23. sperner-0.1.0/sperner/adaptive_solver.py +129 -0
  24. sperner-0.1.0/sperner/agentic_judge.py +53 -0
  25. sperner-0.1.0/sperner/analytics.py +47 -0
  26. sperner-0.1.0/sperner/human_ui.py +224 -0
  27. sperner-0.1.0/sperner/industrial.py +112 -0
  28. sperner-0.1.0/sperner/moe_router.py +101 -0
  29. sperner-0.1.0/sperner/ndim_solver.py +372 -0
  30. sperner-0.1.0/sperner/plotting.py +143 -0
  31. sperner-0.1.0/sperner/py.typed +0 -0
  32. sperner-0.1.0/sperner/rlhf_steering_demo.py +212 -0
  33. sperner-0.1.0/sperner/solver.py +254 -0
  34. sperner-0.1.0/sperner/sperner_trainer.py +159 -0
  35. sperner-0.1.0/sperner/surrogate_solver.py +326 -0
  36. sperner-0.1.0/tests/benchmark.py +183 -0
  37. sperner-0.1.0/tests/conftest.py +6 -0
  38. sperner-0.1.0/tests/test_adaptive_solver.py +47 -0
  39. sperner-0.1.0/tests/test_analytics.py +37 -0
  40. sperner-0.1.0/tests/test_integration.py +108 -0
  41. sperner-0.1.0/tests/test_moe_router.py +42 -0
  42. sperner-0.1.0/tests/test_ndim_solver.py +108 -0
  43. sperner-0.1.0/tests/test_plotting.py +46 -0
  44. sperner-0.1.0/tests/test_solver.py +71 -0
  45. sperner-0.1.0/tests/test_sperner_trainer.py +62 -0
  46. sperner-0.1.0/tools/equilib_login.py +29 -0
  47. sperner-0.1.0/tools/equilib_merge.py +61 -0
@@ -0,0 +1,35 @@
1
+ *.7z filter=lfs diff=lfs merge=lfs -text
2
+ *.arrow filter=lfs diff=lfs merge=lfs -text
3
+ *.bin filter=lfs diff=lfs merge=lfs -text
4
+ *.bz2 filter=lfs diff=lfs merge=lfs -text
5
+ *.ckpt filter=lfs diff=lfs merge=lfs -text
6
+ *.ftz filter=lfs diff=lfs merge=lfs -text
7
+ *.gz filter=lfs diff=lfs merge=lfs -text
8
+ *.h5 filter=lfs diff=lfs merge=lfs -text
9
+ *.joblib filter=lfs diff=lfs merge=lfs -text
10
+ *.lfs.* filter=lfs diff=lfs merge=lfs -text
11
+ *.mlmodel filter=lfs diff=lfs merge=lfs -text
12
+ *.model filter=lfs diff=lfs merge=lfs -text
13
+ *.msgpack filter=lfs diff=lfs merge=lfs -text
14
+ *.npy filter=lfs diff=lfs merge=lfs -text
15
+ *.npz filter=lfs diff=lfs merge=lfs -text
16
+ *.onnx filter=lfs diff=lfs merge=lfs -text
17
+ *.ot filter=lfs diff=lfs merge=lfs -text
18
+ *.parquet filter=lfs diff=lfs merge=lfs -text
19
+ *.pb filter=lfs diff=lfs merge=lfs -text
20
+ *.pickle filter=lfs diff=lfs merge=lfs -text
21
+ *.pkl filter=lfs diff=lfs merge=lfs -text
22
+ *.pt filter=lfs diff=lfs merge=lfs -text
23
+ *.pth filter=lfs diff=lfs merge=lfs -text
24
+ *.rar filter=lfs diff=lfs merge=lfs -text
25
+ *.safetensors filter=lfs diff=lfs merge=lfs -text
26
+ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
27
+ *.tar.* filter=lfs diff=lfs merge=lfs -text
28
+ *.tar filter=lfs diff=lfs merge=lfs -text
29
+ *.tflite filter=lfs diff=lfs merge=lfs -text
30
+ *.tgz filter=lfs diff=lfs merge=lfs -text
31
+ *.wasm filter=lfs diff=lfs merge=lfs -text
32
+ *.xz filter=lfs diff=lfs merge=lfs -text
33
+ *.zip filter=lfs diff=lfs merge=lfs -text
34
+ *.zst filter=lfs diff=lfs merge=lfs -text
35
+ *tfevents* filter=lfs diff=lfs merge=lfs -text
@@ -0,0 +1,45 @@
1
+ name: Publish to PyPI
2
+
3
+ on:
4
+ release:
5
+ types: [published]
6
+ workflow_dispatch:
7
+
8
+ jobs:
9
+ build:
10
+ runs-on: ubuntu-latest
11
+ steps:
12
+ - uses: actions/checkout@v4
13
+
14
+ - name: Set up Python
15
+ uses: actions/setup-python@v5
16
+ with:
17
+ python-version: "3.12"
18
+
19
+ - name: Install build tools
20
+ run: pip install build
21
+
22
+ - name: Build package
23
+ run: python -m build
24
+
25
+ - name: Upload build artifacts
26
+ uses: actions/upload-artifact@v4
27
+ with:
28
+ name: dist
29
+ path: dist/
30
+
31
+ publish:
32
+ needs: build
33
+ runs-on: ubuntu-latest
34
+ environment: pypi
35
+ permissions:
36
+ id-token: write
37
+ steps:
38
+ - name: Download build artifacts
39
+ uses: actions/download-artifact@v4
40
+ with:
41
+ name: dist
42
+ path: dist/
43
+
44
+ - name: Publish to PyPI
45
+ uses: pypa/gh-action-pypi-publish@release/v1
@@ -0,0 +1,30 @@
1
+ name: Tests
2
+
3
+ on:
4
+ push:
5
+ branches: [main]
6
+ pull_request:
7
+ branches: [main]
8
+
9
+ jobs:
10
+ test:
11
+ runs-on: ubuntu-latest
12
+ strategy:
13
+ matrix:
14
+ python-version: ["3.10", "3.11", "3.12"]
15
+
16
+ steps:
17
+ - uses: actions/checkout@v4
18
+
19
+ - name: Set up Python ${{ matrix.python-version }}
20
+ uses: actions/setup-python@v5
21
+ with:
22
+ python-version: ${{ matrix.python-version }}
23
+
24
+ - name: Install dependencies
25
+ run: |
26
+ python -m pip install --upgrade pip
27
+ pip install -e ".[dev]"
28
+
29
+ - name: Run tests
30
+ run: pytest tests/ -v --timeout=60
@@ -0,0 +1,167 @@
1
+ # Byte-compiled / optimized / DLL files
2
+ __pycache__/
3
+ *.py[cod]
4
+ *$py.class
5
+
6
+ # C extensions
7
+ *.so
8
+
9
+ # Distribution / packaging
10
+ bin/
11
+ build/
12
+ develop-eggs/
13
+ dist/
14
+ downloads/
15
+ eggs/
16
+ .eggs/
17
+ lib/
18
+ lib64/
19
+ parts/
20
+ sdist/
21
+ var/
22
+ wheels/
23
+ share/python-wheels/
24
+ *.egg-info/
25
+ .installed.cfg
26
+ *.egg
27
+ MANIFEST
28
+
29
+ # PyInstaller
30
+ # Usually these files are written by a python script from a template
31
+ # before PyInstaller builds the exe, so as to inject date/other infos into it.
32
+ *.manifest
33
+ *.spec
34
+
35
+ # Installer logs
36
+ pip-log.txt
37
+ pip-delete-this-directory.txt
38
+
39
+ # Unit test / coverage reports
40
+ htmlcov/
41
+ .tox/
42
+ .nox/
43
+ .coverage
44
+ .coverage.*
45
+ .cache
46
+ nosetests.xml
47
+ coverage.xml
48
+ *.cover
49
+ *.py,cover
50
+ .reports/
51
+ pytestdebug.log
52
+
53
+ # Translations
54
+ *.mo
55
+ *.pot
56
+
57
+ # Django stuff:
58
+ *.log
59
+ local_settings.py
60
+ db.sqlite3
61
+ db.sqlite3-journal
62
+
63
+ # Flask stuff:
64
+ instance/
65
+ .webassets-cache
66
+
67
+ # Scrapy stuff:
68
+ .scrapy
69
+
70
+ # Sphinx documentation
71
+ docs/_build/
72
+
73
+ # PyBuilder
74
+ .pybuilder/
75
+ target/
76
+
77
+ # Jupyter Notebook
78
+ .ipynb_checkpoints
79
+
80
+ # IPython
81
+ profile_default/
82
+ ipython_config.py
83
+
84
+ # pyenv
85
+ # For a library or package, you might want to ignore these files since the Python version
86
+ # is generally managed by the user. However, for a specific project, you might want
87
+ # to include them.
88
+ # .python-version
89
+
90
+ # pipenv
91
+ # According to pypa/pipenv#1185, it is recommended to include Pipfile.lock in version control.
92
+ # However, in case of collaboration, if having platform-specific dependencies or dependencies
93
+ # having no cross-platform support, pipenv may install dependencies that don't work, or even
94
+ # fail to install them.
95
+ # Pipfile.lock
96
+
97
+ # poetry
98
+ # Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
99
+ # poetry.lock
100
+
101
+ # pdm
102
+ # Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
103
+ # pdm.lock
104
+ # pdm envs
105
+ .pdm-python
106
+ .pdm-build/
107
+
108
+ # PEP 582; used by e.g. github.com/pdm-project/pdm
109
+ __pypackages__/
110
+
111
+ # Celery stuff
112
+ celerybeat-schedule
113
+ celerybeat.pid
114
+
115
+ # SageMath parsed files
116
+ *.sage.py
117
+
118
+ # Environments
119
+ .env
120
+ .venv
121
+ env/
122
+ venv/
123
+ ENV/
124
+ env.bak/
125
+ venv.bak/
126
+
127
+ # Spyder project settings
128
+ .spyderproject
129
+ .spytermcss
130
+
131
+ # Rope project settings
132
+ .ropeproject
133
+
134
+ # mkdocs documentation
135
+ /site
136
+
137
+ # mypy
138
+ .mypy_cache/
139
+ .dmypy.json
140
+ dmypy.json
141
+
142
+ # Pyre type checker
143
+ .pyre/
144
+
145
+ # pytype static type analyzer
146
+ .pytype/
147
+
148
+ # Cython debug symbols
149
+ cython_debug/
150
+
151
+ # PyCharm
152
+ .idea/
153
+
154
+ # VS Code
155
+ .vscode/
156
+
157
+ # Project specifics
158
+ *.txt
159
+ !requirements.txt
160
+ *.pyc
161
+ .system_generated/
162
+ .gemini/
163
+ brain/
164
+ debug_output_*.txt
165
+ verify_output.txt
166
+ reproduce_slowness.py
167
+ test_human_ui_fix.py
sperner-0.1.0/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Oussama Mesbah
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.
22
+ SOFTWARE.
sperner-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,219 @@
1
+ Metadata-Version: 2.4
2
+ Name: sperner
3
+ Version: 0.1.0
4
+ Summary: Gradient-free multi-objective alignment via Sperner's Lemma and implicit Freudenthal triangulation.
5
+ Project-URL: Homepage, https://github.com/OussamaMesbah/sperner
6
+ Project-URL: Repository, https://github.com/OussamaMesbah/sperner
7
+ Project-URL: Documentation, https://github.com/OussamaMesbah/sperner/tree/main/docs
8
+ Author-email: Oussama Mesbah <omesbah@users.noreply.github.com>
9
+ License: MIT
10
+ License-File: LICENSE
11
+ Keywords: alignment,llm,multi-objective,nash-equilibrium,pytorch,sperner,topological
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3.10
18
+ Classifier: Programming Language :: Python :: 3.11
19
+ Classifier: Programming Language :: Python :: 3.12
20
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
21
+ Classifier: Typing :: Typed
22
+ Requires-Python: >=3.10
23
+ Requires-Dist: matplotlib>=3.5
24
+ Requires-Dist: numpy>=1.24
25
+ Requires-Dist: requests>=2.28
26
+ Requires-Dist: scikit-learn>=1.3
27
+ Requires-Dist: scipy>=1.10
28
+ Requires-Dist: torch>=2.0
29
+ Provides-Extra: all
30
+ Requires-Dist: peft>=0.5; extra == 'all'
31
+ Requires-Dist: pytest-timeout>=2.0; extra == 'all'
32
+ Requires-Dist: pytest>=7.0; extra == 'all'
33
+ Requires-Dist: streamlit>=1.28; extra == 'all'
34
+ Requires-Dist: transformers>=4.30; extra == 'all'
35
+ Provides-Extra: dev
36
+ Requires-Dist: pytest-timeout>=2.0; extra == 'dev'
37
+ Requires-Dist: pytest>=7.0; extra == 'dev'
38
+ Provides-Extra: peft
39
+ Requires-Dist: peft>=0.5; extra == 'peft'
40
+ Requires-Dist: transformers>=4.30; extra == 'peft'
41
+ Provides-Extra: ui
42
+ Requires-Dist: streamlit>=1.28; extra == 'ui'
43
+ Description-Content-Type: text/markdown
44
+
45
+ # Sperner
46
+
47
+ **Find the optimal balance between competing objectives — without gradients, without grid search, with a mathematical guarantee.**
48
+
49
+ [![Tests](https://github.com/OussamaMesbah/sperner/actions/workflows/test.yml/badge.svg)](https://github.com/OussamaMesbah/sperner/actions/workflows/test.yml)
50
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
51
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
52
+
53
+ ---
54
+
55
+ ## What does Sperner do?
56
+
57
+ You have an LLM (or any system) with **N competing objectives** — Safety vs. Helpfulness vs. Creativity, or Precision vs. Recall vs. Latency. You need to find the weight mix where everything is "good enough" simultaneously.
58
+
59
+ **Sperner solves this in O(N) evaluations** using a topological fixed-point algorithm (Sperner's Lemma), instead of the O(X^N) brute-force grid search.
60
+
61
+ ```python
62
+ # Find the optimal balance between 3 objectives in ~50 evaluations
63
+ from sperner import solve_equilibrium
64
+
65
+ weights = solve_equilibrium(
66
+ n_objs=3,
67
+ oracle=lambda w: my_benchmark(w), # returns index of weakest objective
68
+ )
69
+ # weights ≈ [0.35, 0.40, 0.25] — the Nash equilibrium
70
+ ```
71
+
72
+ ### When to use Sperner
73
+
74
+ | Use case | Example |
75
+ | :------------------------------ | :------------------------------------------------- |
76
+ | **LLM alignment** | Balance safety, helpfulness, and creativity |
77
+ | **Model merging** | Find optimal LoRA adapter mix weights |
78
+ | **MoE routing** | Allocate experts without softmax collapse |
79
+ | **Benchmark tuning** | Hit multiple non-differentiable metrics at once |
80
+ | **Any multi-objective problem** | Where you can answer "which objective is weakest?" |
81
+
82
+ The only requirement: you need an oracle that, given a weight vector, tells you **which objective is currently the most underserved**. That's it — no gradients, no loss surfaces, no hyperparameter sweeps.
83
+
84
+ ---
85
+
86
+ ## How it works (30-second version)
87
+
88
+ 1. Sperner places your N objectives on an **N-simplex** (triangle for 3, tetrahedron for 4, etc.)
89
+ 2. It subdivides the simplex into a fine grid and labels each point by asking your oracle: "at these weights, which objective is weakest?"
90
+ 3. It performs a **Sperner walk** — a combinatorial path through the grid that is *mathematically guaranteed* to find a cell where all labels meet (a "panchromatic simplex")
91
+ 4. The centroid of that cell is your equilibrium — the weight mix where no single objective dominates
92
+
93
+ This works because of **Sperner's Lemma** (1928): any valid labeling of a triangulated simplex *must* contain at least one fully-labeled cell. Sperner exploits this to find it in linear time.
94
+
95
+ ---
96
+
97
+ ## Installation
98
+
99
+ ```bash
100
+ pip install .
101
+
102
+ # With LoRA/PEFT support
103
+ pip install ".[peft]"
104
+
105
+ # With Streamlit human-in-the-loop UI
106
+ pip install ".[ui]"
107
+
108
+ # Everything
109
+ pip install ".[all]"
110
+ ```
111
+
112
+ ## Quick start
113
+
114
+ ### Automated (programmatic oracle)
115
+
116
+ ```python
117
+ import numpy as np
118
+ from sperner import NDimEquilibSolver
119
+ import torch
120
+
121
+ solver = NDimEquilibSolver(n_objs=4, subdivision=50)
122
+
123
+ def judge(weights_batch: torch.Tensor) -> torch.Tensor:
124
+ """Return index of the weakest objective for each weight vector."""
125
+ labels = []
126
+ for w in weights_batch:
127
+ scores = run_my_benchmarks(w.numpy()) # your eval function
128
+ labels.append(int(np.argmin(scores)))
129
+ return torch.tensor(labels)
130
+
131
+ optimal = solver.solve(oracle_fn=judge)
132
+ print(f"Optimal weights: {optimal[0]}")
133
+ ```
134
+
135
+ ### Human-in-the-loop (Streamlit UI)
136
+
137
+ For qualitative "vibe check" alignment — the solver proposes weights, your local LLM generates a response, and you click which objective needs more work:
138
+
139
+ ```bash
140
+ streamlit run app.py
141
+ ```
142
+
143
+ The UI supports 2–10 configurable objectives and works with any OpenAI-compatible API (LM Studio, Ollama, vLLM).
144
+
145
+ ### LoRA adapter merging
146
+
147
+ ```python
148
+ from sperner import SpernerTrainer
149
+
150
+ trainer = SpernerTrainer(
151
+ base_model=my_peft_model,
152
+ adapters=["safety-lora", "code-lora", "chat-lora"],
153
+ objectives=[safety_score, code_score, chat_score],
154
+ mock=False,
155
+ )
156
+ optimal_mix = trainer.train(grid_size=50)
157
+ ```
158
+
159
+ ### MoE expert routing
160
+
161
+ ```python
162
+ from sperner import TopologicalMoERouter
163
+
164
+ router = TopologicalMoERouter(num_experts=8, latent_dim=4096)
165
+ weights = router.forward_route(hidden_states, precision=20)
166
+ # weights = [0.18, 0.12, 0.15, ...] — no routing collapse
167
+ ```
168
+
169
+ ---
170
+
171
+ ## Comparison
172
+
173
+ | | Grid Search | Bayesian Opt | **Sperner** |
174
+ | :------------------------------ | :----------------- | :------------ | :--------------- |
175
+ | **Oracle calls** | O(X^N) exponential | O(N²) typical | **O(N) linear** |
176
+ | **Needs gradients** | No | No | **No** |
177
+ | **Scales to 10+ objectives** | No | Poorly | **Yes** |
178
+ | **Convergence guarantee** | Exhaustive only | Probabilistic | **Mathematical** |
179
+ | **Works with discrete metrics** | Yes | Awkward | **Native** |
180
+
181
+ ---
182
+
183
+ ## Project structure
184
+
185
+ ```
186
+ sperner/
187
+ ndim_solver.py # Core N-dimensional Sperner walk (PyTorch)
188
+ solver.py # Legacy 2D solver
189
+ adaptive_solver.py # Iterative zoom refinement
190
+ surrogate_solver.py # KNN active-learning wrapper (fewer oracle calls)
191
+ sperner_trainer.py # PEFT/LoRA adapter integration
192
+ moe_router.py # Topological MoE routing
193
+ agentic_judge.py # LLM-as-a-Judge orchestrator
194
+ human_ui.py # Streamlit UI for manual alignment
195
+ analytics.py # Frustration score & path analysis
196
+ plotting.py # Simplex heatmap visualization
197
+ ```
198
+
199
+ ## Docs
200
+
201
+ - [API Reference](docs/API_REFERENCE.md)
202
+ - [Architecture & Theory](docs/ARCHITECTURE.md)
203
+ - [Sperner's Lemma Theory](docs/THEORY.md)
204
+ - [Model Card Integration](docs/MODEL_CARD_INTEGRATION.md)
205
+
206
+ ## Citation
207
+
208
+ ```bibtex
209
+ @software{mesbah2026sperner,
210
+ author = {Mesbah, Oussama},
211
+ title = {Sperner: Gradient-Free Multi-Objective Alignment via Sperner's Lemma},
212
+ year = {2026},
213
+ url = {https://github.com/OussamaMesbah/sperner}
214
+ }
215
+ ```
216
+
217
+ ## License
218
+
219
+ MIT
@@ -0,0 +1,175 @@
1
+ # Sperner
2
+
3
+ **Find the optimal balance between competing objectives — without gradients, without grid search, with a mathematical guarantee.**
4
+
5
+ [![Tests](https://github.com/OussamaMesbah/sperner/actions/workflows/test.yml/badge.svg)](https://github.com/OussamaMesbah/sperner/actions/workflows/test.yml)
6
+ [![Python 3.10+](https://img.shields.io/badge/python-3.10+-blue.svg)](https://www.python.org/downloads/)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
8
+
9
+ ---
10
+
11
+ ## What does Sperner do?
12
+
13
+ You have an LLM (or any system) with **N competing objectives** — Safety vs. Helpfulness vs. Creativity, or Precision vs. Recall vs. Latency. You need to find the weight mix where everything is "good enough" simultaneously.
14
+
15
+ **Sperner solves this in O(N) evaluations** using a topological fixed-point algorithm (Sperner's Lemma), instead of the O(X^N) brute-force grid search.
16
+
17
+ ```python
18
+ # Find the optimal balance between 3 objectives in ~50 evaluations
19
+ from sperner import solve_equilibrium
20
+
21
+ weights = solve_equilibrium(
22
+ n_objs=3,
23
+ oracle=lambda w: my_benchmark(w), # returns index of weakest objective
24
+ )
25
+ # weights ≈ [0.35, 0.40, 0.25] — the Nash equilibrium
26
+ ```
27
+
28
+ ### When to use Sperner
29
+
30
+ | Use case | Example |
31
+ | :------------------------------ | :------------------------------------------------- |
32
+ | **LLM alignment** | Balance safety, helpfulness, and creativity |
33
+ | **Model merging** | Find optimal LoRA adapter mix weights |
34
+ | **MoE routing** | Allocate experts without softmax collapse |
35
+ | **Benchmark tuning** | Hit multiple non-differentiable metrics at once |
36
+ | **Any multi-objective problem** | Where you can answer "which objective is weakest?" |
37
+
38
+ The only requirement: you need an oracle that, given a weight vector, tells you **which objective is currently the most underserved**. That's it — no gradients, no loss surfaces, no hyperparameter sweeps.
39
+
40
+ ---
41
+
42
+ ## How it works (30-second version)
43
+
44
+ 1. Sperner places your N objectives on an **N-simplex** (triangle for 3, tetrahedron for 4, etc.)
45
+ 2. It subdivides the simplex into a fine grid and labels each point by asking your oracle: "at these weights, which objective is weakest?"
46
+ 3. It performs a **Sperner walk** — a combinatorial path through the grid that is *mathematically guaranteed* to find a cell where all labels meet (a "panchromatic simplex")
47
+ 4. The centroid of that cell is your equilibrium — the weight mix where no single objective dominates
48
+
49
+ This works because of **Sperner's Lemma** (1928): any valid labeling of a triangulated simplex *must* contain at least one fully-labeled cell. Sperner exploits this to find it in linear time.
50
+
51
+ ---
52
+
53
+ ## Installation
54
+
55
+ ```bash
56
+ pip install .
57
+
58
+ # With LoRA/PEFT support
59
+ pip install ".[peft]"
60
+
61
+ # With Streamlit human-in-the-loop UI
62
+ pip install ".[ui]"
63
+
64
+ # Everything
65
+ pip install ".[all]"
66
+ ```
67
+
68
+ ## Quick start
69
+
70
+ ### Automated (programmatic oracle)
71
+
72
+ ```python
73
+ import numpy as np
74
+ from sperner import NDimEquilibSolver
75
+ import torch
76
+
77
+ solver = NDimEquilibSolver(n_objs=4, subdivision=50)
78
+
79
+ def judge(weights_batch: torch.Tensor) -> torch.Tensor:
80
+ """Return index of the weakest objective for each weight vector."""
81
+ labels = []
82
+ for w in weights_batch:
83
+ scores = run_my_benchmarks(w.numpy()) # your eval function
84
+ labels.append(int(np.argmin(scores)))
85
+ return torch.tensor(labels)
86
+
87
+ optimal = solver.solve(oracle_fn=judge)
88
+ print(f"Optimal weights: {optimal[0]}")
89
+ ```
90
+
91
+ ### Human-in-the-loop (Streamlit UI)
92
+
93
+ For qualitative "vibe check" alignment — the solver proposes weights, your local LLM generates a response, and you click which objective needs more work:
94
+
95
+ ```bash
96
+ streamlit run app.py
97
+ ```
98
+
99
+ The UI supports 2–10 configurable objectives and works with any OpenAI-compatible API (LM Studio, Ollama, vLLM).
100
+
101
+ ### LoRA adapter merging
102
+
103
+ ```python
104
+ from sperner import SpernerTrainer
105
+
106
+ trainer = SpernerTrainer(
107
+ base_model=my_peft_model,
108
+ adapters=["safety-lora", "code-lora", "chat-lora"],
109
+ objectives=[safety_score, code_score, chat_score],
110
+ mock=False,
111
+ )
112
+ optimal_mix = trainer.train(grid_size=50)
113
+ ```
114
+
115
+ ### MoE expert routing
116
+
117
+ ```python
118
+ from sperner import TopologicalMoERouter
119
+
120
+ router = TopologicalMoERouter(num_experts=8, latent_dim=4096)
121
+ weights = router.forward_route(hidden_states, precision=20)
122
+ # weights = [0.18, 0.12, 0.15, ...] — no routing collapse
123
+ ```
124
+
125
+ ---
126
+
127
+ ## Comparison
128
+
129
+ | | Grid Search | Bayesian Opt | **Sperner** |
130
+ | :------------------------------ | :----------------- | :------------ | :--------------- |
131
+ | **Oracle calls** | O(X^N) exponential | O(N²) typical | **O(N) linear** |
132
+ | **Needs gradients** | No | No | **No** |
133
+ | **Scales to 10+ objectives** | No | Poorly | **Yes** |
134
+ | **Convergence guarantee** | Exhaustive only | Probabilistic | **Mathematical** |
135
+ | **Works with discrete metrics** | Yes | Awkward | **Native** |
136
+
137
+ ---
138
+
139
+ ## Project structure
140
+
141
+ ```
142
+ sperner/
143
+ ndim_solver.py # Core N-dimensional Sperner walk (PyTorch)
144
+ solver.py # Legacy 2D solver
145
+ adaptive_solver.py # Iterative zoom refinement
146
+ surrogate_solver.py # KNN active-learning wrapper (fewer oracle calls)
147
+ sperner_trainer.py # PEFT/LoRA adapter integration
148
+ moe_router.py # Topological MoE routing
149
+ agentic_judge.py # LLM-as-a-Judge orchestrator
150
+ human_ui.py # Streamlit UI for manual alignment
151
+ analytics.py # Frustration score & path analysis
152
+ plotting.py # Simplex heatmap visualization
153
+ ```
154
+
155
+ ## Docs
156
+
157
+ - [API Reference](docs/API_REFERENCE.md)
158
+ - [Architecture & Theory](docs/ARCHITECTURE.md)
159
+ - [Sperner's Lemma Theory](docs/THEORY.md)
160
+ - [Model Card Integration](docs/MODEL_CARD_INTEGRATION.md)
161
+
162
+ ## Citation
163
+
164
+ ```bibtex
165
+ @software{mesbah2026sperner,
166
+ author = {Mesbah, Oussama},
167
+ title = {Sperner: Gradient-Free Multi-Objective Alignment via Sperner's Lemma},
168
+ year = {2026},
169
+ url = {https://github.com/OussamaMesbah/sperner}
170
+ }
171
+ ```
172
+
173
+ ## License
174
+
175
+ MIT