optimize-llm-judge 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 (40) hide show
  1. optimize_llm_judge-0.1.0/LICENSE +21 -0
  2. optimize_llm_judge-0.1.0/PKG-INFO +260 -0
  3. optimize_llm_judge-0.1.0/README.md +228 -0
  4. optimize_llm_judge-0.1.0/pyproject.toml +56 -0
  5. optimize_llm_judge-0.1.0/setup.cfg +4 -0
  6. optimize_llm_judge-0.1.0/src/optimize_llm_judge/__init__.py +73 -0
  7. optimize_llm_judge-0.1.0/src/optimize_llm_judge/__main__.py +3 -0
  8. optimize_llm_judge-0.1.0/src/optimize_llm_judge/_concurrency.py +99 -0
  9. optimize_llm_judge-0.1.0/src/optimize_llm_judge/_version.py +1 -0
  10. optimize_llm_judge-0.1.0/src/optimize_llm_judge/analysis.py +548 -0
  11. optimize_llm_judge-0.1.0/src/optimize_llm_judge/backends.py +484 -0
  12. optimize_llm_judge-0.1.0/src/optimize_llm_judge/checkers.py +434 -0
  13. optimize_llm_judge-0.1.0/src/optimize_llm_judge/cli.py +501 -0
  14. optimize_llm_judge-0.1.0/src/optimize_llm_judge/config.py +395 -0
  15. optimize_llm_judge-0.1.0/src/optimize_llm_judge/data.py +541 -0
  16. optimize_llm_judge-0.1.0/src/optimize_llm_judge/datasets.py +45 -0
  17. optimize_llm_judge-0.1.0/src/optimize_llm_judge/estimators.py +438 -0
  18. optimize_llm_judge-0.1.0/src/optimize_llm_judge/generate.py +155 -0
  19. optimize_llm_judge-0.1.0/src/optimize_llm_judge/judges.py +283 -0
  20. optimize_llm_judge-0.1.0/src/optimize_llm_judge/pipeline.py +695 -0
  21. optimize_llm_judge-0.1.0/src/optimize_llm_judge/plotting.py +174 -0
  22. optimize_llm_judge-0.1.0/src/optimize_llm_judge/selection.py +199 -0
  23. optimize_llm_judge-0.1.0/src/optimize_llm_judge/simulate.py +114 -0
  24. optimize_llm_judge-0.1.0/src/optimize_llm_judge/templates.py +360 -0
  25. optimize_llm_judge-0.1.0/src/optimize_llm_judge.egg-info/PKG-INFO +260 -0
  26. optimize_llm_judge-0.1.0/src/optimize_llm_judge.egg-info/SOURCES.txt +38 -0
  27. optimize_llm_judge-0.1.0/src/optimize_llm_judge.egg-info/dependency_links.txt +1 -0
  28. optimize_llm_judge-0.1.0/src/optimize_llm_judge.egg-info/entry_points.txt +2 -0
  29. optimize_llm_judge-0.1.0/src/optimize_llm_judge.egg-info/requires.txt +7 -0
  30. optimize_llm_judge-0.1.0/src/optimize_llm_judge.egg-info/top_level.txt +1 -0
  31. optimize_llm_judge-0.1.0/tests/test_backends.py +282 -0
  32. optimize_llm_judge-0.1.0/tests/test_data.py +100 -0
  33. optimize_llm_judge-0.1.0/tests/test_estimators.py +154 -0
  34. optimize_llm_judge-0.1.0/tests/test_judges_generate.py +167 -0
  35. optimize_llm_judge-0.1.0/tests/test_pipeline.py +574 -0
  36. optimize_llm_judge-0.1.0/tests/test_readme.py +199 -0
  37. optimize_llm_judge-0.1.0/tests/test_regressions.py +315 -0
  38. optimize_llm_judge-0.1.0/tests/test_selection.py +139 -0
  39. optimize_llm_judge-0.1.0/tests/test_templates_checkers.py +146 -0
  40. optimize_llm_judge-0.1.0/tests/test_unbiased.py +132 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Indranil Halder, Annesya Banerjee
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.
@@ -0,0 +1,260 @@
1
+ Metadata-Version: 2.4
2
+ Name: optimize-llm-judge
3
+ Version: 0.1.0
4
+ Summary: Optimize best-of-k selection with LLM judges: exact error vs number of samples, selection temperature and judge weights, from one pool of samples.
5
+ Author: Indranil Halder, Annesya Banerjee
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/I-Halder/optimize-llm-judge
8
+ Project-URL: Documentation, https://github.com/I-Halder/optimize-llm-judge#readme
9
+ Project-URL: Issues, https://github.com/I-Halder/optimize-llm-judge/issues
10
+ Project-URL: Changelog, https://github.com/I-Halder/optimize-llm-judge/blob/main/CHANGELOG.md
11
+ Keywords: llm,llm-as-a-judge,best-of-k,best-of-n,inference-time-scaling,test-time-compute,reward-model,evaluation,jailbreak,pass-at-k
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Intended Audience :: Developers
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: Programming Language :: Python :: 3.13
21
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
22
+ Requires-Python: >=3.10
23
+ Description-Content-Type: text/markdown
24
+ License-File: LICENSE
25
+ Requires-Dist: numpy>=1.22
26
+ Requires-Dist: matplotlib>=3.5
27
+ Requires-Dist: pyyaml>=5.4
28
+ Provides-Extra: dev
29
+ Requires-Dist: pytest>=7; extra == "dev"
30
+ Requires-Dist: ruff>=0.4; extra == "dev"
31
+ Dynamic: license-file
32
+
33
+ # optimize-llm-judge
34
+
35
+ **How many answers should you sample, and how should an LLM judge pick among them?**
36
+
37
+ [![CI](https://github.com/I-Halder/optimize-llm-judge/actions/workflows/ci.yml/badge.svg)](https://github.com/I-Halder/optimize-llm-judge/actions/workflows/ci.yml)
38
+ [![Python 3.10–3.13](https://img.shields.io/badge/python-3.10%E2%80%933.13-blue.svg)](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/pyproject.toml)
39
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/LICENSE)
40
+
41
+ Best-of-k is the simplest way to spend more compute at inference time: sample *k* answers and let a judge pick one. With a perfect judge, more samples always help. With a real LLM judge they help only up to a point, after which the judge's mistakes dominate and the picked answer gets *worse*. How sharply the pick follows the judge's scores, set by a selection temperature *T*, matters as much as *k*.
42
+
43
+ `optimize-llm-judge` measures this trade-off on your task, with your models and your judges, and finds the best *k*, *T* and judge weights:
44
+
45
+ 1. **Sample once.** Generate *K* answers per question with any OpenAI-compatible server, or bring answers you already have.
46
+ 2. **Judge once.** Score every answer with a **gold judge** (a checker such as exact match or unit tests, or a strong model) and one or more **proxy judges** (LLM judges, with built-in prompts for math, code and jailbreak safety).
47
+ 3. **Get every curve.** For every *k* ≤ *K*, every temperature and any weighting of the proxy judges, compute the expected gold error of the answer the judges would pick from *k* fresh samples, with standard errors. The estimate averages over all *k*-subsets of the *K* answers, so it is exact and unbiased.
48
+
49
+
50
+ ## Install
51
+
52
+ ```bash
53
+ pip install optimize-llm-judge
54
+ ```
55
+
56
+ Python ≥ 3.10. The dependencies are numpy, matplotlib and PyYAML; the client for model servers uses only the standard library. For the development version: `pip install "git+https://github.com/I-Halder/optimize-llm-judge"`.
57
+
58
+ ## Quick start
59
+
60
+ ### 1. See it work (offline, no models)
61
+
62
+ ```bash
63
+ optimize-llm-judge demo
64
+ ```
65
+
66
+ This writes error-vs-*k* and error-vs-*T* plots for two synthetic judges to `optimize-llm-judge-demo/`. With the *aligned* judge, more samples keep helping. The *hackable* judge also rewards a surface feature that wrong answers have more of, so its best is *k* = 2 and sampling more makes its pick worse.
67
+
68
+ ### 2. Analyze judge scores you already have
69
+
70
+ With *K* answers per question, a gold score for each answer and proxy-judge scores, the Python API needs only arrays:
71
+
72
+ ```python
73
+ import numpy as np
74
+ import optimize_llm_judge as olj
75
+
76
+ # Replace with your data: gold[q, a] in [0, 1] (1 = correct), proxy scores on any scale, NaN = missing answer.
77
+ rng = np.random.default_rng(0)
78
+ gold = (rng.random((300, 32)) < 0.3).astype(float)
79
+ scores = {"weak": gold + rng.normal(0, 1.0, gold.shape), "strong": gold + rng.normal(0, 0.5, gold.shape)}
80
+
81
+ table = olj.ScoreTable(gold, scores)
82
+ curve = olj.error_curve(table, "strong", T=0.3) # error of the picked answer for k = 1..32
83
+ sweep = olj.temperature_sweep(table, "weak", T_grid=[0, 0.1, 0.3, 1, 3, float("inf")])
84
+ tuned = olj.tune(table, ["weak", "strong"], holdout=0.3) # best k, temperatures and judge weights
85
+ print(curve.best()) # {'k': ..., 'error': ..., 'se': ..., ...}
86
+ print(sweep.best()) # best (T, k) for the weak judge
87
+ print(tuned.best) # chosen on 70% of the questions
88
+ print(tuned.holdout) # its error on the other 30%, the one-standard-error k, and the k = 1 baseline
89
+
90
+ from optimize_llm_judge.plotting import plot_curves
91
+ fig, ax = plot_curves([curve], reference=[olj.oracle_curve(table), olj.random_curve(table)], mark_best=True)
92
+ fig.savefig("error_vs_k.png")
93
+ ```
94
+
95
+ The same analysis from the command line takes a `scores.jsonl` with one line per judgement, `{"question_id", "answer_id", "judge", "score"}`, and the gold judge named `gold`:
96
+
97
+ ```bash
98
+ optimize-llm-judge analyze scores.jsonl --T 0,0.3,1,inf --tune --holdout 0.3 --out results --plots
99
+ ```
100
+
101
+ Gold scores must lie in [0, 1]. For another scale pass `--gold-range lo,hi`, or a threshold such as `--gold-map "<5"`; out-of-range values are an error, never clipped.
102
+
103
+ ### 3. Run a full experiment
104
+
105
+ Serve a model and a judge with any OpenAI-compatible server (vLLM, SGLang, llama.cpp, Ollama, OpenAI, Together, OpenRouter, ...). With vLLM:
106
+
107
+ ```bash
108
+ vllm serve meta-llama/Meta-Llama-3-8B-Instruct --port 8000
109
+ vllm serve mistralai/Mistral-7B-Instruct-v0.3 --port 8001
110
+ ```
111
+
112
+ `optimize-llm-judge init --example gsm8k` writes this config to `optimize-llm-judge.yaml` (the other examples are `jailbreak`, and `arithmetic`, which runs offline):
113
+
114
+ ```yaml
115
+ name: gsm8k-llama8b-mistral
116
+ seed: 0
117
+ data: {builtin: gsm8k, limit: 200} # or {path: questions.jsonl}
118
+ models:
119
+ generator: {base_url: "http://localhost:8000/v1", model: meta-llama/Meta-Llama-3-8B-Instruct}
120
+ judge: {base_url: "http://localhost:8001/v1", model: mistralai/Mistral-7B-Instruct-v0.3}
121
+ generation:
122
+ model: generator
123
+ k: 32 # K answers per question, sampled once
124
+ mode: chat
125
+ prompt_template: "{question}\nSolve step by step. End with 'The answer is <number>.'"
126
+ temperature: 0.8
127
+ max_tokens: 512
128
+ gold: {type: checker, checker: math} # judge 0: the reference
129
+ judges: # judges 1..J: they pick the answer
130
+ - {name: terse, type: llm, model: judge, template: math_terse, T: 1.0}
131
+ - {name: reasoning, type: llm, model: judge, template: math_reasoning_terse, T: 1.0}
132
+ analysis: {T_grid: [0, 0.1, 0.3, 1, 3, 10, inf], holdout: 0.3}
133
+ ```
134
+
135
+ ```bash
136
+ optimize-llm-judge run optimize-llm-judge.yaml # generate -> judge -> analyze; run again to resume
137
+ ```
138
+
139
+ Results go to `runs/<name>/results/`: `summary.json` (the best *k* and *T* for each judge, the tuned setting with its hold-out error), `curves.csv` (every curve), `tune.csv` and `plots/`. Answers and scores stay in `runs/<name>/`.
140
+
141
+ ### 4. Judge answers you generated elsewhere
142
+
143
+ Point `data` at your questions and `generation.answers` at the answers; the generator model is then not needed:
144
+
145
+ ```yaml
146
+ data: {path: questions.jsonl} # lines like {"id": "q1", "question": "...", "reference": "..."}
147
+ generation: {answers: answers.jsonl, k: 16} # lines like {"question_id": "q1", "answers": ["...", "..."]}
148
+ ```
149
+
150
+ ### 5. Combine several judges with different weights
151
+
152
+ Each proxy judge *j* has its own temperature *T*<sub>j</sub> and weight *λ*<sub>j</sub>. Weights are equal by default and are normalized, so `[1, 2]` means 1/3 and 2/3. There are two ways to combine judges:
153
+
154
+ * **`mixture`** (the default): judge *j* is consulted with probability *λ*<sub>j</sub> and picks the answer. The error is the weighted average of the judges' errors, so a mixture never beats the best single judge.
155
+ * **`product`**: each answer's scores are added with the weights, $q_i\propto e^{\sum_j\lambda_j r_j(y_i)/T_j}$, so the judges vote on every answer. Mistakes the judges do not share cancel out, and the combination can beat every judge alone.
156
+
157
+ Here a cheap, noisy judge and a stronger one make independent mistakes:
158
+
159
+ ```python
160
+ import numpy as np
161
+ import optimize_llm_judge as olj
162
+
163
+ rng = np.random.default_rng(0)
164
+ gold = (rng.random((400, 16)) < 0.3).astype(float)
165
+ scores = {"small": gold + rng.normal(0, 1.0, gold.shape), # cheap judge, noisier scores
166
+ "large": gold + rng.normal(0, 0.7, gold.shape)} # stronger judge
167
+ table = olj.ScoreTable(gold, scores)
168
+
169
+ curves = {
170
+ "small alone": olj.error_curve(table, "small", T=0),
171
+ "large alone": olj.error_curve(table, "large", T=0),
172
+ "mixture 1:2": olj.error_curve(table, ["small", "large"], T=0, weights=[1, 2], combine="mixture"),
173
+ "product 1:2": olj.error_curve(table, ["small", "large"], T=0, weights=[1, 2], combine="product"),
174
+ }
175
+ for name, curve in curves.items():
176
+ error, se = curve.at(8) # error of the picked answer at k = 8
177
+ print(f"{name}: {error:.3f} ± {se:.3f}")
178
+
179
+ # Search the weights on a grid (step 0.1) together with k and the temperature; check them on held-out questions.
180
+ tuned = olj.tune(table, ["small", "large"], combine="product", weight_step=0.1, holdout=0.3)
181
+ best, held_out = tuned.best, tuned.holdout["best"]
182
+ print(f"tuned: weights {best['weights']}, T = {best['T'][0]:g}, k = {best['k']}; "
183
+ f"held-out error {held_out['error']:.3f} ± {held_out['se']:.3f}")
184
+ ```
185
+
186
+ ```text
187
+ small alone: 0.366 ± 0.014
188
+ large alone: 0.278 ± 0.013
189
+ mixture 1:2: 0.307 ± 0.011
190
+ product 1:2: 0.198 ± 0.011
191
+ tuned: weights (0.4, 0.6), T = 0, k = 16; held-out error 0.092 ± 0.026
192
+ ```
193
+
194
+ The 1:2 mixture lands between the two judges (it is their weighted average), while the 1:2 product beats both. Tuning the product puts weight 0.4 on the small judge and 0.6 on the large one, and its held-out error at *k* = 16 is 0.092. In a config file, give each judge a `weight` and choose the rule under `analysis`:
195
+
196
+ ```yaml
197
+ judges:
198
+ - {name: small, type: llm, model: small_judge, template: math, T: 0, weight: 1}
199
+ - {name: large, type: llm, model: large_judge, template: math_detailed, T: 0, weight: 2}
200
+ analysis: {combine: product, weight_step: 0.1, holdout: 0.3}
201
+ ```
202
+
203
+ On a scores file, this command reports each judge alone, the configured 1:2 product and the tuned setting:
204
+
205
+ ```bash
206
+ optimize-llm-judge analyze scores.jsonl --judges small,large --combine product --weights 1,2 --T-combined 0 --tune --weight-step 0.1 --holdout 0.3 --out results
207
+ ```
208
+
209
+ With `combine: product` the judges' temperatures must be all zero or all positive (only *λ*<sub>j</sub>/*T*<sub>j</sub> matters), and the tuner searches the weights with one common temperature.
210
+
211
+ ## What it computes
212
+
213
+ For a question *x*, draw answers *y*<sub>1</sub>, ..., *y*<sub>k</sub>. The gold judge gives each a value $v(y)\in[0,1]$. Proxy judge *j* gives a raw score $r_j(y)$ and has a temperature $T_j$ and a weight $\lambda_j$ (equal by default). The answer that is picked is *i* with probability
214
+
215
+ $$q_i=\sum_j\lambda_j\,\mathrm{softmax}(r_j/T_j)_i \quad\text{(mixture, the default)}\qquad\text{or}\qquad q_i\propto e^{\sum_j\lambda_j r_j(y_i)/T_j}\quad\text{(product)}.$$
216
+
217
+ *T* = 0 picks the top-scored answer (ties share the probability) and *T* = ∞ picks uniformly at random. The error is
218
+
219
+ $$\varepsilon(k)=1-\mathbb E_x\,\mathbb E_{y_{1:k}}\Big[\textstyle\sum_i q_i\,v(y_i)\Big],$$
220
+
221
+ the probability that the picked answer is wrong when the gold judge is 0/1; graded gold scores give a graded error. From one pool of *K* answers it averages over all $\binom{K}{k}$ subsets. This U-statistic is unbiased for *k* fresh answers and never noisier than sampling fresh batches. [`docs/theory.md`](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/docs/theory.md) gives the definitions, the proof and the exact algorithms.
222
+
223
+ ## Judges
224
+
225
+ | template | use |
226
+ |---|---|
227
+ | `math`, `math_detailed`, `math_reference` | 0–10 correctness grade (short, step by step, against a reference) |
228
+ | `coding` | 0–10 code-correctness grade (no execution) |
229
+ | `jailbreak`, `jailbreak_binary` | compliance score, or binary attack-success label, for safety evaluation |
230
+ | `general` | 1–10 quality rating |
231
+ | `math_terse`, `math_reasoning_terse` | terse 0–10 grade of the final answer, or of the reasoning and the final answer (raw completion, 4 tokens, first number) |
232
+ | `jailbreak_terse` | terse 0–10 safety score (raw completion, 4 tokens; score < 5 = jailbroken) |
233
+
234
+ `optimize-llm-judge templates` lists them and `--show <name>` prints one in full. Custom templates can be a `.txt` file, a `.yaml`/`.json` file, or a dict with `base:` overrides. Programmatic gold judges: `math` (robust final-answer match), `math_first_match` (the first match instead of the last), `exact`, `choice`, `regex`, `refusal_prefix` and `python_tests`. The last one executes model-written code, so it requires `allow_exec: true` and should run in a container.
235
+
236
+ ## Safety evaluation
237
+
238
+ `optimize-llm-judge init --example jailbreak` measures the attack success rate ASR@*k*, the probability that at least one of *k* responses is jailbroken, of Llama-3.2-3B-Instruct on the AdvBench prompts. The gold judge is Mistral-7B-Instruct-v0.3 with the `jailbreak_terse` template and `gold_map: "<5"`, so the oracle curve is 1 − ASR@*k*; a commented line switches the prompt to one with an adversarial (GCG) suffix. Start vLLM with `--generation-config vllm`; otherwise the server applies the model's own sampling defaults (top-p 0.9 for Llama-3.2) instead of the config's. Raw victim responses can contain harmful content, so keep run directories private.
239
+
240
+ ## Citation
241
+
242
+ If you use `optimize-llm-judge` in your work, please cite it (the same metadata is in [CITATION.cff](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/CITATION.cff)):
243
+
244
+ ```bibtex
245
+ @software{optimize_llm_judge,
246
+ author = {Halder, Indranil and Banerjee, Annesya},
247
+ title = {optimize-llm-judge: Optimize best-of-k selection with {LLM} judges},
248
+ year = {2026},
249
+ version = {0.1.0},
250
+ url = {https://github.com/I-Halder/optimize-llm-judge}
251
+ }
252
+ ```
253
+
254
+ ## Contributing
255
+
256
+ Bug reports and pull requests are welcome; see [CONTRIBUTING.md](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/CONTRIBUTING.md).
257
+
258
+ ## License
259
+
260
+ [MIT](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/LICENSE)
@@ -0,0 +1,228 @@
1
+ # optimize-llm-judge
2
+
3
+ **How many answers should you sample, and how should an LLM judge pick among them?**
4
+
5
+ [![CI](https://github.com/I-Halder/optimize-llm-judge/actions/workflows/ci.yml/badge.svg)](https://github.com/I-Halder/optimize-llm-judge/actions/workflows/ci.yml)
6
+ [![Python 3.10–3.13](https://img.shields.io/badge/python-3.10%E2%80%933.13-blue.svg)](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/pyproject.toml)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/LICENSE)
8
+
9
+ Best-of-k is the simplest way to spend more compute at inference time: sample *k* answers and let a judge pick one. With a perfect judge, more samples always help. With a real LLM judge they help only up to a point, after which the judge's mistakes dominate and the picked answer gets *worse*. How sharply the pick follows the judge's scores, set by a selection temperature *T*, matters as much as *k*.
10
+
11
+ `optimize-llm-judge` measures this trade-off on your task, with your models and your judges, and finds the best *k*, *T* and judge weights:
12
+
13
+ 1. **Sample once.** Generate *K* answers per question with any OpenAI-compatible server, or bring answers you already have.
14
+ 2. **Judge once.** Score every answer with a **gold judge** (a checker such as exact match or unit tests, or a strong model) and one or more **proxy judges** (LLM judges, with built-in prompts for math, code and jailbreak safety).
15
+ 3. **Get every curve.** For every *k* ≤ *K*, every temperature and any weighting of the proxy judges, compute the expected gold error of the answer the judges would pick from *k* fresh samples, with standard errors. The estimate averages over all *k*-subsets of the *K* answers, so it is exact and unbiased.
16
+
17
+
18
+ ## Install
19
+
20
+ ```bash
21
+ pip install optimize-llm-judge
22
+ ```
23
+
24
+ Python ≥ 3.10. The dependencies are numpy, matplotlib and PyYAML; the client for model servers uses only the standard library. For the development version: `pip install "git+https://github.com/I-Halder/optimize-llm-judge"`.
25
+
26
+ ## Quick start
27
+
28
+ ### 1. See it work (offline, no models)
29
+
30
+ ```bash
31
+ optimize-llm-judge demo
32
+ ```
33
+
34
+ This writes error-vs-*k* and error-vs-*T* plots for two synthetic judges to `optimize-llm-judge-demo/`. With the *aligned* judge, more samples keep helping. The *hackable* judge also rewards a surface feature that wrong answers have more of, so its best is *k* = 2 and sampling more makes its pick worse.
35
+
36
+ ### 2. Analyze judge scores you already have
37
+
38
+ With *K* answers per question, a gold score for each answer and proxy-judge scores, the Python API needs only arrays:
39
+
40
+ ```python
41
+ import numpy as np
42
+ import optimize_llm_judge as olj
43
+
44
+ # Replace with your data: gold[q, a] in [0, 1] (1 = correct), proxy scores on any scale, NaN = missing answer.
45
+ rng = np.random.default_rng(0)
46
+ gold = (rng.random((300, 32)) < 0.3).astype(float)
47
+ scores = {"weak": gold + rng.normal(0, 1.0, gold.shape), "strong": gold + rng.normal(0, 0.5, gold.shape)}
48
+
49
+ table = olj.ScoreTable(gold, scores)
50
+ curve = olj.error_curve(table, "strong", T=0.3) # error of the picked answer for k = 1..32
51
+ sweep = olj.temperature_sweep(table, "weak", T_grid=[0, 0.1, 0.3, 1, 3, float("inf")])
52
+ tuned = olj.tune(table, ["weak", "strong"], holdout=0.3) # best k, temperatures and judge weights
53
+ print(curve.best()) # {'k': ..., 'error': ..., 'se': ..., ...}
54
+ print(sweep.best()) # best (T, k) for the weak judge
55
+ print(tuned.best) # chosen on 70% of the questions
56
+ print(tuned.holdout) # its error on the other 30%, the one-standard-error k, and the k = 1 baseline
57
+
58
+ from optimize_llm_judge.plotting import plot_curves
59
+ fig, ax = plot_curves([curve], reference=[olj.oracle_curve(table), olj.random_curve(table)], mark_best=True)
60
+ fig.savefig("error_vs_k.png")
61
+ ```
62
+
63
+ The same analysis from the command line takes a `scores.jsonl` with one line per judgement, `{"question_id", "answer_id", "judge", "score"}`, and the gold judge named `gold`:
64
+
65
+ ```bash
66
+ optimize-llm-judge analyze scores.jsonl --T 0,0.3,1,inf --tune --holdout 0.3 --out results --plots
67
+ ```
68
+
69
+ Gold scores must lie in [0, 1]. For another scale pass `--gold-range lo,hi`, or a threshold such as `--gold-map "<5"`; out-of-range values are an error, never clipped.
70
+
71
+ ### 3. Run a full experiment
72
+
73
+ Serve a model and a judge with any OpenAI-compatible server (vLLM, SGLang, llama.cpp, Ollama, OpenAI, Together, OpenRouter, ...). With vLLM:
74
+
75
+ ```bash
76
+ vllm serve meta-llama/Meta-Llama-3-8B-Instruct --port 8000
77
+ vllm serve mistralai/Mistral-7B-Instruct-v0.3 --port 8001
78
+ ```
79
+
80
+ `optimize-llm-judge init --example gsm8k` writes this config to `optimize-llm-judge.yaml` (the other examples are `jailbreak`, and `arithmetic`, which runs offline):
81
+
82
+ ```yaml
83
+ name: gsm8k-llama8b-mistral
84
+ seed: 0
85
+ data: {builtin: gsm8k, limit: 200} # or {path: questions.jsonl}
86
+ models:
87
+ generator: {base_url: "http://localhost:8000/v1", model: meta-llama/Meta-Llama-3-8B-Instruct}
88
+ judge: {base_url: "http://localhost:8001/v1", model: mistralai/Mistral-7B-Instruct-v0.3}
89
+ generation:
90
+ model: generator
91
+ k: 32 # K answers per question, sampled once
92
+ mode: chat
93
+ prompt_template: "{question}\nSolve step by step. End with 'The answer is <number>.'"
94
+ temperature: 0.8
95
+ max_tokens: 512
96
+ gold: {type: checker, checker: math} # judge 0: the reference
97
+ judges: # judges 1..J: they pick the answer
98
+ - {name: terse, type: llm, model: judge, template: math_terse, T: 1.0}
99
+ - {name: reasoning, type: llm, model: judge, template: math_reasoning_terse, T: 1.0}
100
+ analysis: {T_grid: [0, 0.1, 0.3, 1, 3, 10, inf], holdout: 0.3}
101
+ ```
102
+
103
+ ```bash
104
+ optimize-llm-judge run optimize-llm-judge.yaml # generate -> judge -> analyze; run again to resume
105
+ ```
106
+
107
+ Results go to `runs/<name>/results/`: `summary.json` (the best *k* and *T* for each judge, the tuned setting with its hold-out error), `curves.csv` (every curve), `tune.csv` and `plots/`. Answers and scores stay in `runs/<name>/`.
108
+
109
+ ### 4. Judge answers you generated elsewhere
110
+
111
+ Point `data` at your questions and `generation.answers` at the answers; the generator model is then not needed:
112
+
113
+ ```yaml
114
+ data: {path: questions.jsonl} # lines like {"id": "q1", "question": "...", "reference": "..."}
115
+ generation: {answers: answers.jsonl, k: 16} # lines like {"question_id": "q1", "answers": ["...", "..."]}
116
+ ```
117
+
118
+ ### 5. Combine several judges with different weights
119
+
120
+ Each proxy judge *j* has its own temperature *T*<sub>j</sub> and weight *λ*<sub>j</sub>. Weights are equal by default and are normalized, so `[1, 2]` means 1/3 and 2/3. There are two ways to combine judges:
121
+
122
+ * **`mixture`** (the default): judge *j* is consulted with probability *λ*<sub>j</sub> and picks the answer. The error is the weighted average of the judges' errors, so a mixture never beats the best single judge.
123
+ * **`product`**: each answer's scores are added with the weights, $q_i\propto e^{\sum_j\lambda_j r_j(y_i)/T_j}$, so the judges vote on every answer. Mistakes the judges do not share cancel out, and the combination can beat every judge alone.
124
+
125
+ Here a cheap, noisy judge and a stronger one make independent mistakes:
126
+
127
+ ```python
128
+ import numpy as np
129
+ import optimize_llm_judge as olj
130
+
131
+ rng = np.random.default_rng(0)
132
+ gold = (rng.random((400, 16)) < 0.3).astype(float)
133
+ scores = {"small": gold + rng.normal(0, 1.0, gold.shape), # cheap judge, noisier scores
134
+ "large": gold + rng.normal(0, 0.7, gold.shape)} # stronger judge
135
+ table = olj.ScoreTable(gold, scores)
136
+
137
+ curves = {
138
+ "small alone": olj.error_curve(table, "small", T=0),
139
+ "large alone": olj.error_curve(table, "large", T=0),
140
+ "mixture 1:2": olj.error_curve(table, ["small", "large"], T=0, weights=[1, 2], combine="mixture"),
141
+ "product 1:2": olj.error_curve(table, ["small", "large"], T=0, weights=[1, 2], combine="product"),
142
+ }
143
+ for name, curve in curves.items():
144
+ error, se = curve.at(8) # error of the picked answer at k = 8
145
+ print(f"{name}: {error:.3f} ± {se:.3f}")
146
+
147
+ # Search the weights on a grid (step 0.1) together with k and the temperature; check them on held-out questions.
148
+ tuned = olj.tune(table, ["small", "large"], combine="product", weight_step=0.1, holdout=0.3)
149
+ best, held_out = tuned.best, tuned.holdout["best"]
150
+ print(f"tuned: weights {best['weights']}, T = {best['T'][0]:g}, k = {best['k']}; "
151
+ f"held-out error {held_out['error']:.3f} ± {held_out['se']:.3f}")
152
+ ```
153
+
154
+ ```text
155
+ small alone: 0.366 ± 0.014
156
+ large alone: 0.278 ± 0.013
157
+ mixture 1:2: 0.307 ± 0.011
158
+ product 1:2: 0.198 ± 0.011
159
+ tuned: weights (0.4, 0.6), T = 0, k = 16; held-out error 0.092 ± 0.026
160
+ ```
161
+
162
+ The 1:2 mixture lands between the two judges (it is their weighted average), while the 1:2 product beats both. Tuning the product puts weight 0.4 on the small judge and 0.6 on the large one, and its held-out error at *k* = 16 is 0.092. In a config file, give each judge a `weight` and choose the rule under `analysis`:
163
+
164
+ ```yaml
165
+ judges:
166
+ - {name: small, type: llm, model: small_judge, template: math, T: 0, weight: 1}
167
+ - {name: large, type: llm, model: large_judge, template: math_detailed, T: 0, weight: 2}
168
+ analysis: {combine: product, weight_step: 0.1, holdout: 0.3}
169
+ ```
170
+
171
+ On a scores file, this command reports each judge alone, the configured 1:2 product and the tuned setting:
172
+
173
+ ```bash
174
+ optimize-llm-judge analyze scores.jsonl --judges small,large --combine product --weights 1,2 --T-combined 0 --tune --weight-step 0.1 --holdout 0.3 --out results
175
+ ```
176
+
177
+ With `combine: product` the judges' temperatures must be all zero or all positive (only *λ*<sub>j</sub>/*T*<sub>j</sub> matters), and the tuner searches the weights with one common temperature.
178
+
179
+ ## What it computes
180
+
181
+ For a question *x*, draw answers *y*<sub>1</sub>, ..., *y*<sub>k</sub>. The gold judge gives each a value $v(y)\in[0,1]$. Proxy judge *j* gives a raw score $r_j(y)$ and has a temperature $T_j$ and a weight $\lambda_j$ (equal by default). The answer that is picked is *i* with probability
182
+
183
+ $$q_i=\sum_j\lambda_j\,\mathrm{softmax}(r_j/T_j)_i \quad\text{(mixture, the default)}\qquad\text{or}\qquad q_i\propto e^{\sum_j\lambda_j r_j(y_i)/T_j}\quad\text{(product)}.$$
184
+
185
+ *T* = 0 picks the top-scored answer (ties share the probability) and *T* = ∞ picks uniformly at random. The error is
186
+
187
+ $$\varepsilon(k)=1-\mathbb E_x\,\mathbb E_{y_{1:k}}\Big[\textstyle\sum_i q_i\,v(y_i)\Big],$$
188
+
189
+ the probability that the picked answer is wrong when the gold judge is 0/1; graded gold scores give a graded error. From one pool of *K* answers it averages over all $\binom{K}{k}$ subsets. This U-statistic is unbiased for *k* fresh answers and never noisier than sampling fresh batches. [`docs/theory.md`](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/docs/theory.md) gives the definitions, the proof and the exact algorithms.
190
+
191
+ ## Judges
192
+
193
+ | template | use |
194
+ |---|---|
195
+ | `math`, `math_detailed`, `math_reference` | 0–10 correctness grade (short, step by step, against a reference) |
196
+ | `coding` | 0–10 code-correctness grade (no execution) |
197
+ | `jailbreak`, `jailbreak_binary` | compliance score, or binary attack-success label, for safety evaluation |
198
+ | `general` | 1–10 quality rating |
199
+ | `math_terse`, `math_reasoning_terse` | terse 0–10 grade of the final answer, or of the reasoning and the final answer (raw completion, 4 tokens, first number) |
200
+ | `jailbreak_terse` | terse 0–10 safety score (raw completion, 4 tokens; score < 5 = jailbroken) |
201
+
202
+ `optimize-llm-judge templates` lists them and `--show <name>` prints one in full. Custom templates can be a `.txt` file, a `.yaml`/`.json` file, or a dict with `base:` overrides. Programmatic gold judges: `math` (robust final-answer match), `math_first_match` (the first match instead of the last), `exact`, `choice`, `regex`, `refusal_prefix` and `python_tests`. The last one executes model-written code, so it requires `allow_exec: true` and should run in a container.
203
+
204
+ ## Safety evaluation
205
+
206
+ `optimize-llm-judge init --example jailbreak` measures the attack success rate ASR@*k*, the probability that at least one of *k* responses is jailbroken, of Llama-3.2-3B-Instruct on the AdvBench prompts. The gold judge is Mistral-7B-Instruct-v0.3 with the `jailbreak_terse` template and `gold_map: "<5"`, so the oracle curve is 1 − ASR@*k*; a commented line switches the prompt to one with an adversarial (GCG) suffix. Start vLLM with `--generation-config vllm`; otherwise the server applies the model's own sampling defaults (top-p 0.9 for Llama-3.2) instead of the config's. Raw victim responses can contain harmful content, so keep run directories private.
207
+
208
+ ## Citation
209
+
210
+ If you use `optimize-llm-judge` in your work, please cite it (the same metadata is in [CITATION.cff](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/CITATION.cff)):
211
+
212
+ ```bibtex
213
+ @software{optimize_llm_judge,
214
+ author = {Halder, Indranil and Banerjee, Annesya},
215
+ title = {optimize-llm-judge: Optimize best-of-k selection with {LLM} judges},
216
+ year = {2026},
217
+ version = {0.1.0},
218
+ url = {https://github.com/I-Halder/optimize-llm-judge}
219
+ }
220
+ ```
221
+
222
+ ## Contributing
223
+
224
+ Bug reports and pull requests are welcome; see [CONTRIBUTING.md](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/CONTRIBUTING.md).
225
+
226
+ ## License
227
+
228
+ [MIT](https://github.com/I-Halder/optimize-llm-judge/blob/v0.1.0/LICENSE)
@@ -0,0 +1,56 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "optimize-llm-judge"
7
+ dynamic = ["version"]
8
+ description = "Optimize best-of-k selection with LLM judges: exact error vs number of samples, selection temperature and judge weights, from one pool of samples."
9
+ readme = "README.md"
10
+ requires-python = ">=3.10"
11
+ license = "MIT"
12
+ license-files = ["LICENSE"]
13
+ authors = [{ name = "Indranil Halder" }, { name = "Annesya Banerjee" }]
14
+ keywords = ["llm", "llm-as-a-judge", "best-of-k", "best-of-n", "inference-time-scaling", "test-time-compute", "reward-model", "evaluation", "jailbreak", "pass-at-k"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Science/Research",
18
+ "Intended Audience :: Developers",
19
+ "Operating System :: OS Independent",
20
+ "Programming Language :: Python :: 3",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
26
+ ]
27
+ dependencies = ["numpy>=1.22", "matplotlib>=3.5", "pyyaml>=5.4"]
28
+
29
+ [project.optional-dependencies]
30
+ dev = ["pytest>=7", "ruff>=0.4"]
31
+
32
+ [project.scripts]
33
+ optimize-llm-judge = "optimize_llm_judge.cli:main"
34
+
35
+ [project.urls]
36
+ Homepage = "https://github.com/I-Halder/optimize-llm-judge"
37
+ Documentation = "https://github.com/I-Halder/optimize-llm-judge#readme"
38
+ Issues = "https://github.com/I-Halder/optimize-llm-judge/issues"
39
+ Changelog = "https://github.com/I-Halder/optimize-llm-judge/blob/main/CHANGELOG.md"
40
+
41
+ [tool.setuptools.dynamic]
42
+ version = { attr = "optimize_llm_judge._version.__version__" }
43
+
44
+ [tool.setuptools.packages.find]
45
+ where = ["src"]
46
+
47
+ [tool.pytest.ini_options]
48
+ testpaths = ["tests"]
49
+
50
+ [tool.ruff]
51
+ line-length = 140
52
+ target-version = "py310"
53
+
54
+ [tool.ruff.lint]
55
+ select = ["E", "F", "W", "I", "B", "UP"]
56
+ ignore = ["E501", "B905", "UP007", "UP006", "UP035", "UP038", "B008"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,73 @@
1
+ """optimize-llm-judge: measure and tune inference-time scaling with LLM judges.
2
+
3
+ Generate ``K`` answers per question once, score them with a gold judge
4
+ (judge 0) and up to several proxy judges, and compute -- exactly, for every
5
+ ``k <= K`` -- the expected gold error of the answer a judge-based selection
6
+ rule would pick from ``k`` fresh answers. See ``docs/theory.md``.
7
+ """
8
+
9
+ from ._version import __version__
10
+ from .analysis import (
11
+ DEFAULT_T_GRID,
12
+ Curve,
13
+ Sweep,
14
+ TuneResult,
15
+ error_curve,
16
+ oracle_curve,
17
+ paired_difference,
18
+ prepare,
19
+ random_curve,
20
+ temperature_sweep,
21
+ tune,
22
+ )
23
+ from .backends import BackendError, CallableBackend, OpenAICompatible, make_backend
24
+ from .checkers import get_checker
25
+ from .data import Question, ScoreTable, load_answers, load_questions, read_jsonl, text_sha, write_jsonl
26
+ from .estimators import pass_at_k, subset_expectation
27
+ from .generate import GenerationSettings, generate_answers
28
+ from .judges import CheckerJudge, GoldMap, JudgeResult, LLMJudge
29
+ from .pipeline import Run, analyze_table
30
+ from .selection import expected_gold
31
+ from .templates import BUILTIN_TEMPLATES, Template, get_template, parse_score
32
+
33
+ __all__ = [
34
+ "__version__",
35
+ "DEFAULT_T_GRID",
36
+ "Curve",
37
+ "Sweep",
38
+ "TuneResult",
39
+ "error_curve",
40
+ "oracle_curve",
41
+ "random_curve",
42
+ "temperature_sweep",
43
+ "tune",
44
+ "paired_difference",
45
+ "prepare",
46
+ "BackendError",
47
+ "CallableBackend",
48
+ "OpenAICompatible",
49
+ "make_backend",
50
+ "get_checker",
51
+ "Question",
52
+ "ScoreTable",
53
+ "load_answers",
54
+ "load_questions",
55
+ "read_jsonl",
56
+ "write_jsonl",
57
+ "text_sha",
58
+ "pass_at_k",
59
+ "subset_expectation",
60
+ "GenerationSettings",
61
+ "generate_answers",
62
+ "CheckerJudge",
63
+ "GoldMap",
64
+ "JudgeResult",
65
+ "LLMJudge",
66
+ "Run",
67
+ "analyze_table",
68
+ "expected_gold",
69
+ "BUILTIN_TEMPLATES",
70
+ "Template",
71
+ "get_template",
72
+ "parse_score",
73
+ ]
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())