pcs-annotator 0.2.3__tar.gz → 2.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.
- pcs_annotator-2.1.0/.gitignore +8 -0
- pcs_annotator-2.1.0/CHANGELOG.md +42 -0
- {pcs_annotator-0.2.3 → pcs_annotator-2.1.0}/LICENSE +4 -2
- pcs_annotator-2.1.0/PKG-INFO +283 -0
- pcs_annotator-2.1.0/README.md +254 -0
- pcs_annotator-2.1.0/examples/api_examples.py +31 -0
- pcs_annotator-2.1.0/examples/offline_demo.py +49 -0
- pcs_annotator-2.1.0/pcs_annotator/__init__.py +15 -0
- pcs_annotator-2.1.0/pcs_annotator/backends/__init__.py +6 -0
- pcs_annotator-2.1.0/pcs_annotator/backends/base.py +115 -0
- pcs_annotator-2.1.0/pcs_annotator/backends/cache.py +45 -0
- pcs_annotator-2.1.0/pcs_annotator/backends/openai_compat.py +78 -0
- pcs_annotator-2.1.0/pcs_annotator/cli.py +109 -0
- pcs_annotator-2.1.0/pcs_annotator/core/__init__.py +7 -0
- pcs_annotator-2.1.0/pcs_annotator/core/engine.py +109 -0
- pcs_annotator-2.1.0/pcs_annotator/core/result.py +21 -0
- pcs_annotator-2.1.0/pcs_annotator/core/weights.py +129 -0
- pcs_annotator-2.1.0/pcs_annotator/eval/__init__.py +10 -0
- pcs_annotator-2.1.0/pcs_annotator/eval/baselines.py +246 -0
- pcs_annotator-2.1.0/pcs_annotator/eval/crossval.py +84 -0
- pcs_annotator-2.1.0/pcs_annotator/eval/metrics.py +59 -0
- pcs_annotator-2.1.0/pcs_annotator/pcs.py +119 -0
- pcs_annotator-2.1.0/pcs_annotator/tasks/__init__.py +7 -0
- pcs_annotator-2.1.0/pcs_annotator/tasks/base.py +74 -0
- pcs_annotator-2.1.0/pcs_annotator/tasks/builtin.py +169 -0
- pcs_annotator-2.1.0/pcs_annotator/transforms/__init__.py +8 -0
- pcs_annotator-2.1.0/pcs_annotator/transforms/_refactor_c.py +874 -0
- pcs_annotator-2.1.0/pcs_annotator/transforms/align.py +75 -0
- pcs_annotator-2.1.0/pcs_annotator/transforms/base.py +34 -0
- pcs_annotator-2.1.0/pcs_annotator/transforms/code_c.py +83 -0
- pcs_annotator-2.1.0/pcs_annotator/transforms/text.py +138 -0
- pcs_annotator-2.1.0/pyproject.toml +49 -0
- pcs_annotator-2.1.0/tests/test_backends.py +146 -0
- pcs_annotator-2.1.0/tests/test_cli.py +76 -0
- pcs_annotator-2.1.0/tests/test_core.py +116 -0
- pcs_annotator-2.1.0/tests/test_cpp_behavior.py +260 -0
- pcs_annotator-2.1.0/tests/test_eval.py +98 -0
- pcs_annotator-2.1.0/tests/test_refactor_c.py +322 -0
- pcs_annotator-2.1.0/tests/test_tasks_pcs.py +195 -0
- pcs_annotator-2.1.0/tests/test_transforms.py +130 -0
- pcs_annotator-0.2.3/PKG-INFO +0 -153
- pcs_annotator-0.2.3/README.md +0 -132
- pcs_annotator-0.2.3/pcs_annotator/Annotator.py +0 -39
- pcs_annotator-0.2.3/pcs_annotator/LLM.py +0 -68
- pcs_annotator-0.2.3/pcs_annotator/PCS.py +0 -364
- pcs_annotator-0.2.3/pcs_annotator/TextMutator.py +0 -53
- pcs_annotator-0.2.3/pcs_annotator/Tools.py +0 -43
- pcs_annotator-0.2.3/pcs_annotator/__init__.py +0 -3
- pcs_annotator-0.2.3/pyproject.toml +0 -33
- pcs_annotator-0.2.3/requirements.txt +0 -7
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## 2.1.0
|
|
4
|
+
|
|
5
|
+
**Changed**
|
|
6
|
+
- New default prompts for the text rewrites M1-M3. Each asks for one meaning-preserving edit in every eligible
|
|
7
|
+
sentence and lists the safe forms; a judge model found the meaning kept in 96% (M1), 84% (M2) and 98% (M3) of 50
|
|
8
|
+
rewrites each. The prompts of 2.0.0 stay available as `mr_prompts="original"` (`--mr-prompts original`).
|
|
9
|
+
- Recommended rewriter: `openai/gpt-6-luna` with no temperature, reasoning off and `max_tokens=1500`
|
|
10
|
+
(`transforms.REWRITER_MODEL`, `transforms.REWRITER_SETTINGS`). The command line uses it by default
|
|
11
|
+
(was LLaMA-3.1-8B at temperature 0.2); `--rewriter-temperature` and `--rewriter-max-tokens` change the settings.
|
|
12
|
+
- Author order in the package metadata now follows the paper (and LICENSE): Sina Salimian, Anik Islam, Gias Uddin,
|
|
13
|
+
Shaina Raza, Henry Leung.
|
|
14
|
+
|
|
15
|
+
## 2.0.0
|
|
16
|
+
|
|
17
|
+
A rewrite that extends PCS from text classification to source code.
|
|
18
|
+
|
|
19
|
+
**New**
|
|
20
|
+
- Three built-in tasks: text classification, C/C++ vulnerability classification and C/C++ bug localization.
|
|
21
|
+
- Eight program rewrites for C and C++ (M4-M11), built on tree-sitter and checked for behaviour preservation with
|
|
22
|
+
gcc and g++, and line alignment, so answers that refer to lines of the input can be compared across rewrites.
|
|
23
|
+
- A `Task` interface: a new task needs only its answer space, rewrites, alignment and ground truth.
|
|
24
|
+
- Equal weights by default, so no labelled data is needed. Fitted weights use constrained least squares, which
|
|
25
|
+
replaces the genetic algorithm.
|
|
26
|
+
- Several models with shared version weights and model weights.
|
|
27
|
+
- Any OpenAI-compatible endpoint (OpenRouter, OpenAI, Groq, vLLM, Ollama), with a reply cache, resume and a
|
|
28
|
+
spending cap.
|
|
29
|
+
- `pcs_annotator.eval`: AUROC, ECE, Brier, paired cluster bootstrap, recalibration, and the baselines
|
|
30
|
+
self-consistency, SPUQ, BSDetector, SelfCheckGPT and verbalized 1S top-2.
|
|
31
|
+
- `pcs-annotator` command line.
|
|
32
|
+
|
|
33
|
+
**Removed**
|
|
34
|
+
- The 0.x interface `PCS(prompt=..., dataset_path=..., annotators=...)` and the LangChain dependency.
|
|
35
|
+
|
|
36
|
+
**Fixed (compared with 0.2.3)**
|
|
37
|
+
- "Not vulnerable" is no longer read as "Vulnerable".
|
|
38
|
+
- Custom rewrites are used, not only registered.
|
|
39
|
+
|
|
40
|
+
## 0.2.3 and earlier
|
|
41
|
+
|
|
42
|
+
Text classification with three LLM-written rewrites (see the GitHub history).
|
|
@@ -1,4 +1,6 @@
|
|
|
1
|
-
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2025-2026 Sina Salimian, Anik Islam, Gias Uddin, Shaina Raza, Henry Leung
|
|
2
4
|
|
|
3
5
|
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
4
6
|
of this software and associated documentation files (the "Software"), to deal
|
|
@@ -16,4 +18,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
|
16
18
|
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
17
19
|
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
18
20
|
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
19
|
-
SOFTWARE.
|
|
21
|
+
SOFTWARE.
|
|
@@ -0,0 +1,283 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: pcs-annotator
|
|
3
|
+
Version: 2.1.0
|
|
4
|
+
Summary: Perceived Confidence Scoring (PCS) for black-box LLMs on text classification, C/C++ vulnerability classification and C/C++ bug localization
|
|
5
|
+
Project-URL: Homepage, https://github.com/salsina/PCS-Python-Library
|
|
6
|
+
Project-URL: Issues, https://github.com/salsina/PCS-Python-Library/issues
|
|
7
|
+
Project-URL: Changelog, https://github.com/salsina/PCS-Python-Library/blob/main/CHANGELOG.md
|
|
8
|
+
Author: Sina Salimian, Anik Islam, Gias Uddin, Shaina Raza, Henry Leung
|
|
9
|
+
License-Expression: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: bug localization,confidence,llm,metamorphic testing,uncertainty,vulnerability detection
|
|
12
|
+
Classifier: Intended Audience :: Science/Research
|
|
13
|
+
Classifier: Operating System :: OS Independent
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
16
|
+
Classifier: Topic :: Software Development :: Testing
|
|
17
|
+
Requires-Python: >=3.10
|
|
18
|
+
Requires-Dist: numpy>=1.24
|
|
19
|
+
Requires-Dist: requests>=2.28
|
|
20
|
+
Requires-Dist: scipy>=1.10
|
|
21
|
+
Provides-Extra: code
|
|
22
|
+
Requires-Dist: tree-sitter-c>=0.23; extra == 'code'
|
|
23
|
+
Requires-Dist: tree-sitter-cpp>=0.23; extra == 'code'
|
|
24
|
+
Requires-Dist: tree-sitter>=0.23; extra == 'code'
|
|
25
|
+
Provides-Extra: eval
|
|
26
|
+
Requires-Dist: pandas>=2.0; extra == 'eval'
|
|
27
|
+
Requires-Dist: scikit-learn>=1.3; extra == 'eval'
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
|
|
30
|
+
# PCS Annotator: A Python Library for Confidence Scoring of LLM Answers on Text and Code
|
|
31
|
+
|
|
32
|
+
PCS (Perceived Confidence Scoring) tells you how much to trust an answer from a black-box LLM. It rewrites the input
|
|
33
|
+
in ways that should not change the correct answer (metamorphic relations), asks the LLM about every version, and
|
|
34
|
+
combines the answers in a weighted vote. Version 2 supports three tasks:
|
|
35
|
+
|
|
36
|
+
| Task | Answer | Rewrites |
|
|
37
|
+
|---|---|---|
|
|
38
|
+
| Text classification | a label (e.g. Fake / Real) | M1–M3: voice change, double negation, synonyms |
|
|
39
|
+
| C/C++ vulnerability classification | Vulnerable / Not vulnerable | M4–M11: eight program transformations |
|
|
40
|
+
| C/C++ bug localization | a line number | M4–M11, with answers mapped back to the original lines |
|
|
41
|
+
|
|
42
|
+
## How to Install
|
|
43
|
+
|
|
44
|
+
```bash
|
|
45
|
+
pip install "pcs-annotator[code]"
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
The `[code]` extra adds the C and C++ parsers (tree-sitter) needed for the code tasks. Use `pcs-annotator[code,eval]` to also
|
|
49
|
+
get the evaluation tools.
|
|
50
|
+
|
|
51
|
+
## How to Use
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from pcs_annotator import PCS
|
|
55
|
+
from pcs_annotator.backends import OpenAICompatible
|
|
56
|
+
from pcs_annotator.tasks import TextClassification, VulnClassification, BugLocalization
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
### Choose a Model
|
|
60
|
+
|
|
61
|
+
Any OpenAI-compatible endpoint works: OpenRouter (default), OpenAI, Groq, Together, or a local vLLM or Ollama server.
|
|
62
|
+
|
|
63
|
+
```python
|
|
64
|
+
model = OpenAICompatible("deepseek/deepseek-v4.1-flash", temperature=1.0, max_tokens=32)
|
|
65
|
+
```
|
|
66
|
+
|
|
67
|
+
### Choose a Task
|
|
68
|
+
|
|
69
|
+
```python
|
|
70
|
+
task = BugLocalization() # which line of a C/C++ function holds the bug?
|
|
71
|
+
task = VulnClassification() # is a C/C++ function vulnerable?
|
|
72
|
+
task = TextClassification(["Fake", "Real"], NEWS_PROMPT, rewriter=rewriter) # text: see below
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
### Annotate
|
|
76
|
+
|
|
77
|
+
```python
|
|
78
|
+
pcs = PCS(task, model)
|
|
79
|
+
result = pcs.predict(open("func.c").read())
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## 🔧 Customizing Hyperparameters
|
|
83
|
+
|
|
84
|
+
The `PCS` class lets you choose the task, one or more models, the rewrites, and the weights.
|
|
85
|
+
|
|
86
|
+
### 📌 Example Usage
|
|
87
|
+
|
|
88
|
+
```python
|
|
89
|
+
from pcs_annotator import PCS
|
|
90
|
+
from pcs_annotator.backends import OpenAICompatible
|
|
91
|
+
from pcs_annotator.tasks import NEWS_PROMPT, TextClassification
|
|
92
|
+
|
|
93
|
+
off = {"reasoning": {"enabled": False}}
|
|
94
|
+
rewriter = OpenAICompatible("openai/gpt-6-luna", temperature=None, max_tokens=1500, extra=off)
|
|
95
|
+
annotators = [
|
|
96
|
+
OpenAICompatible("anthropic/claude-haiku-5.5", temperature=None, max_tokens=160, name="haiku"),
|
|
97
|
+
OpenAICompatible("deepseek/deepseek-v4.1-flash", temperature=1.0, max_tokens=32, name="deepseek"),
|
|
98
|
+
]
|
|
99
|
+
|
|
100
|
+
pcs = PCS(
|
|
101
|
+
task=TextClassification(["Fake", "Real"], NEWS_PROMPT, rewriter=rewriter),
|
|
102
|
+
models=annotators,
|
|
103
|
+
)
|
|
104
|
+
|
|
105
|
+
print(pcs.predict("Aliens landed in New York yesterday."))
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
### 🖨️ Output
|
|
109
|
+
|
|
110
|
+
`.predict()` returns a `Result`:
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
result.prediction # 'Fake': the answer on the original input (several models: their majority)
|
|
114
|
+
result.confidence # 0.25: how much weight agrees with that answer
|
|
115
|
+
result.scores # {'Fake': 0.25, 'Real': 0.75}: score of every answer that got a vote
|
|
116
|
+
result.answers # {'haiku': {'original': 'Fake', 'passive_active': 'Real', ...}, ...}
|
|
117
|
+
```
|
|
118
|
+
|
|
119
|
+
For bug localization the answers are line numbers of the original function, e.g. `prediction=11, confidence=0.16`.
|
|
120
|
+
|
|
121
|
+
### 🧪 Try It Without an API Key
|
|
122
|
+
|
|
123
|
+
```bash
|
|
124
|
+
python examples/offline_demo.py
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
A toy model answers line 11 on the original C function but finds the real flaw on most rewrites. PCS gives line 11 a
|
|
128
|
+
confidence of 0.33, where self-consistency would give 1.00.
|
|
129
|
+
|
|
130
|
+
# Configuration
|
|
131
|
+
|
|
132
|
+
## 🔹 Task (`task`)
|
|
133
|
+
Defines what the LLMs are asked and how their answers are compared.
|
|
134
|
+
* **Options**:
|
|
135
|
+
* `TextClassification(labels, prompt, rewriter=...)`: the prompt must contain `{text}` and ask for
|
|
136
|
+
`<label>...</label>`. Ready-made prompts: `NEWS_PROMPT`, `SENTIMENT_PROMPT`.
|
|
137
|
+
* `VulnClassification()`: answers `Vulnerable` or `Not vulnerable`.
|
|
138
|
+
* `BugLocalization()`: answers a line number, counted over the function's non-blank lines from 1.
|
|
139
|
+
* **Customization**:
|
|
140
|
+
* `transforms=[...]` replaces the default rewrites (see below).
|
|
141
|
+
* `lang="auto"` (default) detects C or C++; `lang="c"` or `lang="cpp"` forces one.
|
|
142
|
+
* `braces_first=False` makes M5 (branch swap) swap only, without adding braces first.
|
|
143
|
+
* `assume_builtin_types=True` lets M9 and M10 rewrite C++ expressions too (see Notes).
|
|
144
|
+
* `BugLocalization(lenient=True)` also reads malformed answers such as `<10>N`, which some small local models
|
|
145
|
+
produce.
|
|
146
|
+
|
|
147
|
+
## 🔹 Annotators (`models`)
|
|
148
|
+
Defines the LLM or list of LLMs used for annotation.
|
|
149
|
+
* **Default Value**: none; pass one model or a list.
|
|
150
|
+
* **Customization**:
|
|
151
|
+
* One model: `PCS(task, model)`.
|
|
152
|
+
* Several models: `PCS(task, [model_a, model_b, model_c])`. The prediction is the majority of their answers on the
|
|
153
|
+
original input, and the confidence combines their scores with model weights.
|
|
154
|
+
* Each model needs a unique `name`.
|
|
155
|
+
|
|
156
|
+
## 🔹 Model Settings (`OpenAICompatible`)
|
|
157
|
+
Determines how each model is called.
|
|
158
|
+
|
|
159
|
+
| Parameter | Default | Description |
|
|
160
|
+
|-----------|---------|-------------|
|
|
161
|
+
| `model` | – | Provider model id, e.g. `"anthropic/claude-haiku-5.5"` |
|
|
162
|
+
| `base_url` | OpenRouter | Endpoint root, e.g. `"http://localhost:8000/v1"` for a local vLLM server |
|
|
163
|
+
| `api_key_env` | `"OPENROUTER_API_KEY"` | Name of the environment variable that holds the key |
|
|
164
|
+
| `temperature` | `1.0` | Sampling temperature; `None` leaves it out, for models that reject it (e.g. Claude Haiku) |
|
|
165
|
+
| `max_tokens` | `32` | Output limit; raise it for models that explain before answering |
|
|
166
|
+
| `extra` | `{}` | Extra request fields, e.g. `{"reasoning": {"enabled": False}}` on OpenRouter |
|
|
167
|
+
| `cache` | none | `Cache("file.sqlite")`: stores every reply, so a stopped run resumes without paying twice |
|
|
168
|
+
| `budget` | no cap | `Budget(cap=1.00)`: stops before a new call once this many US dollars are spent |
|
|
169
|
+
|
|
170
|
+
## 🔹 API Keys
|
|
171
|
+
The key is read from an environment variable (or a `.env` file loaded by your own code). It is never stored or cached.
|
|
172
|
+
|
|
173
|
+
| Provider | Set this variable | Then use |
|
|
174
|
+
|----------|-------------------|----------|
|
|
175
|
+
| OpenRouter | `OPENROUTER_API_KEY` | the default `base_url` |
|
|
176
|
+
| OpenAI | `OPENAI_API_KEY` | `base_url="https://api.openai.com/v1", api_key_env="OPENAI_API_KEY"` |
|
|
177
|
+
| Groq | `GROQ_API_KEY` | `base_url="https://api.groq.com/openai/v1", api_key_env="GROQ_API_KEY"` |
|
|
178
|
+
| Local vLLM / Ollama | any value, e.g. `LOCAL_KEY=x` | `base_url="http://localhost:8000/v1", api_key_env="LOCAL_KEY"` |
|
|
179
|
+
|
|
180
|
+
## 🔹 Text Mutator (`rewriter`)
|
|
181
|
+
Determines the LLM that writes the text rewrites M1–M3. The code tasks need no rewriter, because their rewrites are
|
|
182
|
+
rule-based.
|
|
183
|
+
* **Recommended Model**: `"openai/gpt-6-luna"` with no temperature, reasoning off and `max_tokens=1500`, as in the
|
|
184
|
+
paper (`pcs_annotator.transforms.REWRITER_MODEL` and `REWRITER_SETTINGS`).
|
|
185
|
+
* **Prompts**: each prompt asks for one meaning-preserving edit in every eligible sentence and lists the safe forms
|
|
186
|
+
(M1 voice change, M2 double negation such as "did not fail to", M3 true synonyms). A judge model found the meaning
|
|
187
|
+
kept in 96% (M1), 84% (M2) and 98% (M3) of 50 rewrites each.
|
|
188
|
+
* **Customization**:
|
|
189
|
+
* Pass any model as `rewriter=`. With a cache, each text is rewritten only once.
|
|
190
|
+
* `TextClassification(..., mr_prompts="original")` uses the prompts of version 2.0.0 (written for
|
|
191
|
+
`"meta-llama/llama-3.1-8b-instruct"` at temperature 0.2). On the command line: `--mr-prompts original`.
|
|
192
|
+
|
|
193
|
+
## ⚙️ Weights (`weights` and `calibrate`)
|
|
194
|
+
|
|
195
|
+
PCS combines the versions with one weight each (and, for several models, one weight per model).
|
|
196
|
+
|
|
197
|
+
### 🔧 Options
|
|
198
|
+
|
|
199
|
+
| Option | Description |
|
|
200
|
+
|--------|-------------|
|
|
201
|
+
| Equal weights | Every version counts the same. **No labelled data needed.** *(default; as good as fitted weights in the paper)* |
|
|
202
|
+
| `pcs.calibrate(inputs, golds)` | **Constrained least squares**: fits the weights on labelled examples. Weights stay non-negative and sum to 1. |
|
|
203
|
+
| `PCS(task, model, weights=Weights.from_json("w.json"))` | Reuse weights saved with `pcs.weights.to_json("w.json")`. |
|
|
204
|
+
|
|
205
|
+
`golds` are labels for classification and the bug line (or a list of bug lines) for localization.
|
|
206
|
+
|
|
207
|
+
## 🖥️ Command Line
|
|
208
|
+
|
|
209
|
+
```bash
|
|
210
|
+
pcs-annotator predict --task loc --model anthropic/claude-haiku-5.5 --no-temperature --max-tokens 160 --input func.c
|
|
211
|
+
pcs-annotator calibrate --task vuln --model deepseek/deepseek-v4.1-flash --data cal.jsonl --out weights.json
|
|
212
|
+
pcs-annotator predict --task text --preset news --model deepseek/deepseek-v4.1-flash --data test.jsonl
|
|
213
|
+
```
|
|
214
|
+
|
|
215
|
+
Data files are JSONL, one `{"input": ..., "gold": ...}` per line. Run `pcs-annotator predict --help` for all options.
|
|
216
|
+
|
|
217
|
+
## ➕ Adding a Custom Metamorphic Relation (MR)
|
|
218
|
+
|
|
219
|
+
**For text**, give a prompt containing `{text}` that asks for a reply starting with `new text:`:
|
|
220
|
+
|
|
221
|
+
```python
|
|
222
|
+
from pcs_annotator.tasks import NEWS_PROMPT, TextClassification
|
|
223
|
+
from pcs_annotator.transforms import LLMRewrite, text_transforms
|
|
224
|
+
|
|
225
|
+
custom_negation = LLMRewrite(
|
|
226
|
+
"custom_negation",
|
|
227
|
+
"Transform all affirmative statements in the following text into their negated forms.\n"
|
|
228
|
+
"Start the response with 'new text:' and include only the revised text.\n\nOriginal Text:\n{text}",
|
|
229
|
+
rewriter,
|
|
230
|
+
)
|
|
231
|
+
task = TextClassification(["Fake", "Real"], NEWS_PROMPT,
|
|
232
|
+
transforms=text_transforms(rewriter) + [custom_negation])
|
|
233
|
+
```
|
|
234
|
+
|
|
235
|
+
**For code**, subclass `Transform` and return the rewritten function. If the rewrite does not apply, return the input
|
|
236
|
+
unchanged:
|
|
237
|
+
|
|
238
|
+
```python
|
|
239
|
+
from pcs_annotator.tasks import BugLocalization
|
|
240
|
+
from pcs_annotator.transforms import Transform, code_transforms
|
|
241
|
+
|
|
242
|
+
class RenameHelper(Transform):
|
|
243
|
+
name = "rename_helper"
|
|
244
|
+
def apply(self, code):
|
|
245
|
+
return code.replace("helper_0(", "func_a(")
|
|
246
|
+
|
|
247
|
+
task = BugLocalization(transforms=code_transforms() + [RenameHelper()])
|
|
248
|
+
```
|
|
249
|
+
|
|
250
|
+
## ➕ Adding a Custom Task
|
|
251
|
+
|
|
252
|
+
Subclass `Task`, or `ClassificationTask` for a fixed label set, and define four methods:
|
|
253
|
+
* `messages(x)`: the prompt;
|
|
254
|
+
* `parse(raw)`: the answer in a reply, or `None`;
|
|
255
|
+
* `candidates(x)`: the possible answers;
|
|
256
|
+
* `truth(gold)`: the set of correct answers.
|
|
257
|
+
|
|
258
|
+
If answers refer to positions in the input, as line numbers do, also define `align(x, x_k, answer, k)` to map an
|
|
259
|
+
answer on version `k` back to the original. Voting, weights, several models and calibration are shared.
|
|
260
|
+
|
|
261
|
+
## 📊 Evaluation Tools
|
|
262
|
+
|
|
263
|
+
`pcs_annotator.eval` (install with `[eval]`) contains the paper's evaluation:
|
|
264
|
+
* AUROC, ECE and Brier score;
|
|
265
|
+
* paired bootstrap confidence intervals;
|
|
266
|
+
* repeated k-fold PCS and Platt / isotonic recalibration;
|
|
267
|
+
* the baselines self-consistency, SPUQ, BSDetector, SelfCheckGPT and verbalized 1S top-2, with the paper's prompts.
|
|
268
|
+
|
|
269
|
+
## 📝 Notes
|
|
270
|
+
|
|
271
|
+
* **Cost:** each input costs K + 1 queries per model: 4 for text, 9 for code. A version that a rewrite leaves
|
|
272
|
+
unchanged is still queried.
|
|
273
|
+
* **Missing answers:** an answer that cannot be read votes for nothing. If the answer on the original input cannot be
|
|
274
|
+
read, the confidence is 0.
|
|
275
|
+
* **Not probabilities:** PCS scores measure agreement. Use `eval.recalibrate` if you need calibrated probabilities.
|
|
276
|
+
* **Weak models:** when a model performs near chance, no consistency signal, including PCS, is informative.
|
|
277
|
+
* **C and C++:** the program rewrites keep behaviour in both languages: the tests compile C programs with gcc and
|
|
278
|
+
C++ programs with g++ before and after every rewrite. In C++, comparison reversal (M9) and explicit conditions
|
|
279
|
+
(M10) are skipped by default, because the operators may be overloaded; set `assume_builtin_types=True` if your
|
|
280
|
+
code compares only built-in types. Code that does not parse, often because of unexpanded macros, is left unchanged.
|
|
281
|
+
* **Upgrading from 0.x:** version 2 replaces the 0.x interface `PCS(prompt=..., dataset_path=..., annotators=...)`.
|
|
282
|
+
See `CHANGELOG.md`.
|
|
283
|
+
|
|
@@ -0,0 +1,254 @@
|
|
|
1
|
+
# PCS Annotator: A Python Library for Confidence Scoring of LLM Answers on Text and Code
|
|
2
|
+
|
|
3
|
+
PCS (Perceived Confidence Scoring) tells you how much to trust an answer from a black-box LLM. It rewrites the input
|
|
4
|
+
in ways that should not change the correct answer (metamorphic relations), asks the LLM about every version, and
|
|
5
|
+
combines the answers in a weighted vote. Version 2 supports three tasks:
|
|
6
|
+
|
|
7
|
+
| Task | Answer | Rewrites |
|
|
8
|
+
|---|---|---|
|
|
9
|
+
| Text classification | a label (e.g. Fake / Real) | M1–M3: voice change, double negation, synonyms |
|
|
10
|
+
| C/C++ vulnerability classification | Vulnerable / Not vulnerable | M4–M11: eight program transformations |
|
|
11
|
+
| C/C++ bug localization | a line number | M4–M11, with answers mapped back to the original lines |
|
|
12
|
+
|
|
13
|
+
## How to Install
|
|
14
|
+
|
|
15
|
+
```bash
|
|
16
|
+
pip install "pcs-annotator[code]"
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
The `[code]` extra adds the C and C++ parsers (tree-sitter) needed for the code tasks. Use `pcs-annotator[code,eval]` to also
|
|
20
|
+
get the evaluation tools.
|
|
21
|
+
|
|
22
|
+
## How to Use
|
|
23
|
+
|
|
24
|
+
```python
|
|
25
|
+
from pcs_annotator import PCS
|
|
26
|
+
from pcs_annotator.backends import OpenAICompatible
|
|
27
|
+
from pcs_annotator.tasks import TextClassification, VulnClassification, BugLocalization
|
|
28
|
+
```
|
|
29
|
+
|
|
30
|
+
### Choose a Model
|
|
31
|
+
|
|
32
|
+
Any OpenAI-compatible endpoint works: OpenRouter (default), OpenAI, Groq, Together, or a local vLLM or Ollama server.
|
|
33
|
+
|
|
34
|
+
```python
|
|
35
|
+
model = OpenAICompatible("deepseek/deepseek-v4.1-flash", temperature=1.0, max_tokens=32)
|
|
36
|
+
```
|
|
37
|
+
|
|
38
|
+
### Choose a Task
|
|
39
|
+
|
|
40
|
+
```python
|
|
41
|
+
task = BugLocalization() # which line of a C/C++ function holds the bug?
|
|
42
|
+
task = VulnClassification() # is a C/C++ function vulnerable?
|
|
43
|
+
task = TextClassification(["Fake", "Real"], NEWS_PROMPT, rewriter=rewriter) # text: see below
|
|
44
|
+
```
|
|
45
|
+
|
|
46
|
+
### Annotate
|
|
47
|
+
|
|
48
|
+
```python
|
|
49
|
+
pcs = PCS(task, model)
|
|
50
|
+
result = pcs.predict(open("func.c").read())
|
|
51
|
+
```
|
|
52
|
+
|
|
53
|
+
## 🔧 Customizing Hyperparameters
|
|
54
|
+
|
|
55
|
+
The `PCS` class lets you choose the task, one or more models, the rewrites, and the weights.
|
|
56
|
+
|
|
57
|
+
### 📌 Example Usage
|
|
58
|
+
|
|
59
|
+
```python
|
|
60
|
+
from pcs_annotator import PCS
|
|
61
|
+
from pcs_annotator.backends import OpenAICompatible
|
|
62
|
+
from pcs_annotator.tasks import NEWS_PROMPT, TextClassification
|
|
63
|
+
|
|
64
|
+
off = {"reasoning": {"enabled": False}}
|
|
65
|
+
rewriter = OpenAICompatible("openai/gpt-6-luna", temperature=None, max_tokens=1500, extra=off)
|
|
66
|
+
annotators = [
|
|
67
|
+
OpenAICompatible("anthropic/claude-haiku-5.5", temperature=None, max_tokens=160, name="haiku"),
|
|
68
|
+
OpenAICompatible("deepseek/deepseek-v4.1-flash", temperature=1.0, max_tokens=32, name="deepseek"),
|
|
69
|
+
]
|
|
70
|
+
|
|
71
|
+
pcs = PCS(
|
|
72
|
+
task=TextClassification(["Fake", "Real"], NEWS_PROMPT, rewriter=rewriter),
|
|
73
|
+
models=annotators,
|
|
74
|
+
)
|
|
75
|
+
|
|
76
|
+
print(pcs.predict("Aliens landed in New York yesterday."))
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
### 🖨️ Output
|
|
80
|
+
|
|
81
|
+
`.predict()` returns a `Result`:
|
|
82
|
+
|
|
83
|
+
```python
|
|
84
|
+
result.prediction # 'Fake': the answer on the original input (several models: their majority)
|
|
85
|
+
result.confidence # 0.25: how much weight agrees with that answer
|
|
86
|
+
result.scores # {'Fake': 0.25, 'Real': 0.75}: score of every answer that got a vote
|
|
87
|
+
result.answers # {'haiku': {'original': 'Fake', 'passive_active': 'Real', ...}, ...}
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
For bug localization the answers are line numbers of the original function, e.g. `prediction=11, confidence=0.16`.
|
|
91
|
+
|
|
92
|
+
### 🧪 Try It Without an API Key
|
|
93
|
+
|
|
94
|
+
```bash
|
|
95
|
+
python examples/offline_demo.py
|
|
96
|
+
```
|
|
97
|
+
|
|
98
|
+
A toy model answers line 11 on the original C function but finds the real flaw on most rewrites. PCS gives line 11 a
|
|
99
|
+
confidence of 0.33, where self-consistency would give 1.00.
|
|
100
|
+
|
|
101
|
+
# Configuration
|
|
102
|
+
|
|
103
|
+
## 🔹 Task (`task`)
|
|
104
|
+
Defines what the LLMs are asked and how their answers are compared.
|
|
105
|
+
* **Options**:
|
|
106
|
+
* `TextClassification(labels, prompt, rewriter=...)`: the prompt must contain `{text}` and ask for
|
|
107
|
+
`<label>...</label>`. Ready-made prompts: `NEWS_PROMPT`, `SENTIMENT_PROMPT`.
|
|
108
|
+
* `VulnClassification()`: answers `Vulnerable` or `Not vulnerable`.
|
|
109
|
+
* `BugLocalization()`: answers a line number, counted over the function's non-blank lines from 1.
|
|
110
|
+
* **Customization**:
|
|
111
|
+
* `transforms=[...]` replaces the default rewrites (see below).
|
|
112
|
+
* `lang="auto"` (default) detects C or C++; `lang="c"` or `lang="cpp"` forces one.
|
|
113
|
+
* `braces_first=False` makes M5 (branch swap) swap only, without adding braces first.
|
|
114
|
+
* `assume_builtin_types=True` lets M9 and M10 rewrite C++ expressions too (see Notes).
|
|
115
|
+
* `BugLocalization(lenient=True)` also reads malformed answers such as `<10>N`, which some small local models
|
|
116
|
+
produce.
|
|
117
|
+
|
|
118
|
+
## 🔹 Annotators (`models`)
|
|
119
|
+
Defines the LLM or list of LLMs used for annotation.
|
|
120
|
+
* **Default Value**: none; pass one model or a list.
|
|
121
|
+
* **Customization**:
|
|
122
|
+
* One model: `PCS(task, model)`.
|
|
123
|
+
* Several models: `PCS(task, [model_a, model_b, model_c])`. The prediction is the majority of their answers on the
|
|
124
|
+
original input, and the confidence combines their scores with model weights.
|
|
125
|
+
* Each model needs a unique `name`.
|
|
126
|
+
|
|
127
|
+
## 🔹 Model Settings (`OpenAICompatible`)
|
|
128
|
+
Determines how each model is called.
|
|
129
|
+
|
|
130
|
+
| Parameter | Default | Description |
|
|
131
|
+
|-----------|---------|-------------|
|
|
132
|
+
| `model` | – | Provider model id, e.g. `"anthropic/claude-haiku-5.5"` |
|
|
133
|
+
| `base_url` | OpenRouter | Endpoint root, e.g. `"http://localhost:8000/v1"` for a local vLLM server |
|
|
134
|
+
| `api_key_env` | `"OPENROUTER_API_KEY"` | Name of the environment variable that holds the key |
|
|
135
|
+
| `temperature` | `1.0` | Sampling temperature; `None` leaves it out, for models that reject it (e.g. Claude Haiku) |
|
|
136
|
+
| `max_tokens` | `32` | Output limit; raise it for models that explain before answering |
|
|
137
|
+
| `extra` | `{}` | Extra request fields, e.g. `{"reasoning": {"enabled": False}}` on OpenRouter |
|
|
138
|
+
| `cache` | none | `Cache("file.sqlite")`: stores every reply, so a stopped run resumes without paying twice |
|
|
139
|
+
| `budget` | no cap | `Budget(cap=1.00)`: stops before a new call once this many US dollars are spent |
|
|
140
|
+
|
|
141
|
+
## 🔹 API Keys
|
|
142
|
+
The key is read from an environment variable (or a `.env` file loaded by your own code). It is never stored or cached.
|
|
143
|
+
|
|
144
|
+
| Provider | Set this variable | Then use |
|
|
145
|
+
|----------|-------------------|----------|
|
|
146
|
+
| OpenRouter | `OPENROUTER_API_KEY` | the default `base_url` |
|
|
147
|
+
| OpenAI | `OPENAI_API_KEY` | `base_url="https://api.openai.com/v1", api_key_env="OPENAI_API_KEY"` |
|
|
148
|
+
| Groq | `GROQ_API_KEY` | `base_url="https://api.groq.com/openai/v1", api_key_env="GROQ_API_KEY"` |
|
|
149
|
+
| Local vLLM / Ollama | any value, e.g. `LOCAL_KEY=x` | `base_url="http://localhost:8000/v1", api_key_env="LOCAL_KEY"` |
|
|
150
|
+
|
|
151
|
+
## 🔹 Text Mutator (`rewriter`)
|
|
152
|
+
Determines the LLM that writes the text rewrites M1–M3. The code tasks need no rewriter, because their rewrites are
|
|
153
|
+
rule-based.
|
|
154
|
+
* **Recommended Model**: `"openai/gpt-6-luna"` with no temperature, reasoning off and `max_tokens=1500`, as in the
|
|
155
|
+
paper (`pcs_annotator.transforms.REWRITER_MODEL` and `REWRITER_SETTINGS`).
|
|
156
|
+
* **Prompts**: each prompt asks for one meaning-preserving edit in every eligible sentence and lists the safe forms
|
|
157
|
+
(M1 voice change, M2 double negation such as "did not fail to", M3 true synonyms). A judge model found the meaning
|
|
158
|
+
kept in 96% (M1), 84% (M2) and 98% (M3) of 50 rewrites each.
|
|
159
|
+
* **Customization**:
|
|
160
|
+
* Pass any model as `rewriter=`. With a cache, each text is rewritten only once.
|
|
161
|
+
* `TextClassification(..., mr_prompts="original")` uses the prompts of version 2.0.0 (written for
|
|
162
|
+
`"meta-llama/llama-3.1-8b-instruct"` at temperature 0.2). On the command line: `--mr-prompts original`.
|
|
163
|
+
|
|
164
|
+
## ⚙️ Weights (`weights` and `calibrate`)
|
|
165
|
+
|
|
166
|
+
PCS combines the versions with one weight each (and, for several models, one weight per model).
|
|
167
|
+
|
|
168
|
+
### 🔧 Options
|
|
169
|
+
|
|
170
|
+
| Option | Description |
|
|
171
|
+
|--------|-------------|
|
|
172
|
+
| Equal weights | Every version counts the same. **No labelled data needed.** *(default; as good as fitted weights in the paper)* |
|
|
173
|
+
| `pcs.calibrate(inputs, golds)` | **Constrained least squares**: fits the weights on labelled examples. Weights stay non-negative and sum to 1. |
|
|
174
|
+
| `PCS(task, model, weights=Weights.from_json("w.json"))` | Reuse weights saved with `pcs.weights.to_json("w.json")`. |
|
|
175
|
+
|
|
176
|
+
`golds` are labels for classification and the bug line (or a list of bug lines) for localization.
|
|
177
|
+
|
|
178
|
+
## 🖥️ Command Line
|
|
179
|
+
|
|
180
|
+
```bash
|
|
181
|
+
pcs-annotator predict --task loc --model anthropic/claude-haiku-5.5 --no-temperature --max-tokens 160 --input func.c
|
|
182
|
+
pcs-annotator calibrate --task vuln --model deepseek/deepseek-v4.1-flash --data cal.jsonl --out weights.json
|
|
183
|
+
pcs-annotator predict --task text --preset news --model deepseek/deepseek-v4.1-flash --data test.jsonl
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
Data files are JSONL, one `{"input": ..., "gold": ...}` per line. Run `pcs-annotator predict --help` for all options.
|
|
187
|
+
|
|
188
|
+
## ➕ Adding a Custom Metamorphic Relation (MR)
|
|
189
|
+
|
|
190
|
+
**For text**, give a prompt containing `{text}` that asks for a reply starting with `new text:`:
|
|
191
|
+
|
|
192
|
+
```python
|
|
193
|
+
from pcs_annotator.tasks import NEWS_PROMPT, TextClassification
|
|
194
|
+
from pcs_annotator.transforms import LLMRewrite, text_transforms
|
|
195
|
+
|
|
196
|
+
custom_negation = LLMRewrite(
|
|
197
|
+
"custom_negation",
|
|
198
|
+
"Transform all affirmative statements in the following text into their negated forms.\n"
|
|
199
|
+
"Start the response with 'new text:' and include only the revised text.\n\nOriginal Text:\n{text}",
|
|
200
|
+
rewriter,
|
|
201
|
+
)
|
|
202
|
+
task = TextClassification(["Fake", "Real"], NEWS_PROMPT,
|
|
203
|
+
transforms=text_transforms(rewriter) + [custom_negation])
|
|
204
|
+
```
|
|
205
|
+
|
|
206
|
+
**For code**, subclass `Transform` and return the rewritten function. If the rewrite does not apply, return the input
|
|
207
|
+
unchanged:
|
|
208
|
+
|
|
209
|
+
```python
|
|
210
|
+
from pcs_annotator.tasks import BugLocalization
|
|
211
|
+
from pcs_annotator.transforms import Transform, code_transforms
|
|
212
|
+
|
|
213
|
+
class RenameHelper(Transform):
|
|
214
|
+
name = "rename_helper"
|
|
215
|
+
def apply(self, code):
|
|
216
|
+
return code.replace("helper_0(", "func_a(")
|
|
217
|
+
|
|
218
|
+
task = BugLocalization(transforms=code_transforms() + [RenameHelper()])
|
|
219
|
+
```
|
|
220
|
+
|
|
221
|
+
## ➕ Adding a Custom Task
|
|
222
|
+
|
|
223
|
+
Subclass `Task`, or `ClassificationTask` for a fixed label set, and define four methods:
|
|
224
|
+
* `messages(x)`: the prompt;
|
|
225
|
+
* `parse(raw)`: the answer in a reply, or `None`;
|
|
226
|
+
* `candidates(x)`: the possible answers;
|
|
227
|
+
* `truth(gold)`: the set of correct answers.
|
|
228
|
+
|
|
229
|
+
If answers refer to positions in the input, as line numbers do, also define `align(x, x_k, answer, k)` to map an
|
|
230
|
+
answer on version `k` back to the original. Voting, weights, several models and calibration are shared.
|
|
231
|
+
|
|
232
|
+
## 📊 Evaluation Tools
|
|
233
|
+
|
|
234
|
+
`pcs_annotator.eval` (install with `[eval]`) contains the paper's evaluation:
|
|
235
|
+
* AUROC, ECE and Brier score;
|
|
236
|
+
* paired bootstrap confidence intervals;
|
|
237
|
+
* repeated k-fold PCS and Platt / isotonic recalibration;
|
|
238
|
+
* the baselines self-consistency, SPUQ, BSDetector, SelfCheckGPT and verbalized 1S top-2, with the paper's prompts.
|
|
239
|
+
|
|
240
|
+
## 📝 Notes
|
|
241
|
+
|
|
242
|
+
* **Cost:** each input costs K + 1 queries per model: 4 for text, 9 for code. A version that a rewrite leaves
|
|
243
|
+
unchanged is still queried.
|
|
244
|
+
* **Missing answers:** an answer that cannot be read votes for nothing. If the answer on the original input cannot be
|
|
245
|
+
read, the confidence is 0.
|
|
246
|
+
* **Not probabilities:** PCS scores measure agreement. Use `eval.recalibrate` if you need calibrated probabilities.
|
|
247
|
+
* **Weak models:** when a model performs near chance, no consistency signal, including PCS, is informative.
|
|
248
|
+
* **C and C++:** the program rewrites keep behaviour in both languages: the tests compile C programs with gcc and
|
|
249
|
+
C++ programs with g++ before and after every rewrite. In C++, comparison reversal (M9) and explicit conditions
|
|
250
|
+
(M10) are skipped by default, because the operators may be overloaded; set `assume_builtin_types=True` if your
|
|
251
|
+
code compares only built-in types. Code that does not parse, often because of unexpanded macros, is left unchanged.
|
|
252
|
+
* **Upgrading from 0.x:** version 2 replaces the 0.x interface `PCS(prompt=..., dataset_path=..., annotators=...)`.
|
|
253
|
+
See `CHANGELOG.md`.
|
|
254
|
+
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
"""The three tasks with real models through OpenRouter (costs money; set OPENROUTER_API_KEY first).
|
|
2
|
+
|
|
3
|
+
Settings as in the paper: temperature 1, reasoning off, one answer per version; Claude Haiku rejects a temperature
|
|
4
|
+
parameter (it runs at its default of 1.0) and needs a longer output limit because it often explains before the tag.
|
|
5
|
+
"""
|
|
6
|
+
from pcs_annotator import PCS
|
|
7
|
+
from pcs_annotator.backends import Budget, Cache, OpenAICompatible
|
|
8
|
+
from pcs_annotator.tasks import NEWS_PROMPT, BugLocalization, TextClassification, VulnClassification
|
|
9
|
+
|
|
10
|
+
cache, budget = Cache(".pcs_cache.sqlite"), Budget(cap=0.50) # replies are cached; stop before $0.50
|
|
11
|
+
off = {"reasoning": {"enabled": False}}
|
|
12
|
+
haiku = OpenAICompatible("anthropic/claude-haiku-5.5", temperature=None, max_tokens=160, extra=off, cache=cache,
|
|
13
|
+
budget=budget, name="haiku")
|
|
14
|
+
deepseek = OpenAICompatible("deepseek/deepseek-v4.1-flash", max_tokens=32, extra=off, cache=cache, budget=budget,
|
|
15
|
+
name="deepseek")
|
|
16
|
+
|
|
17
|
+
# 1. Text classification: M1-M3 written by GPT-6 Luna (no temperature, reasoning off, as in the paper)
|
|
18
|
+
rewriter = OpenAICompatible("openai/gpt-6-luna", temperature=None, max_tokens=1500, extra=off, cache=cache,
|
|
19
|
+
budget=budget, name="rewriter")
|
|
20
|
+
news = PCS(TextClassification(["Fake", "Real"], NEWS_PROMPT, rewriter=rewriter), haiku)
|
|
21
|
+
print(news.predict("Aliens landed in New York yesterday, officials confirmed."))
|
|
22
|
+
|
|
23
|
+
# 2. Vulnerability classification of a C function
|
|
24
|
+
vuln = PCS(VulnClassification(), deepseek)
|
|
25
|
+
print(vuln.predict(open("func.c").read()))
|
|
26
|
+
|
|
27
|
+
# 3. Bug localization, two models combined (equal weights; call .calibrate(xs, golds) to fit weights)
|
|
28
|
+
loc = PCS(BugLocalization(), [haiku, deepseek])
|
|
29
|
+
r = loc.predict(open("func.c").read())
|
|
30
|
+
print(r.prediction, r.confidence)
|
|
31
|
+
print(f"spent ${budget.spent:.4f}")
|