Skip to content

Commit 990b5f9

Browse files
flyingdoubleGcodelion
authored andcommitted
fix(deepconf): Vote and calibrate as in the DeepConf reference implementation
- Score each answer by the sum of its traces' confidences, DeepConf's confidence-weighted majority vote. The 0.7 * mean confidence + 0.3 * frequency mix let one trace outvote many agreeing ones, since token confidences are several units while the frequency term is at most 1. - Leave early-terminated traces out of the vote, and let warmup traces vote only if they pass the threshold. - Treat a trace shorter than the window as one group of all its tokens, instead of reporting 0 for its lowest and bottom-10% group confidence. - Default confidence_metric to lowest_group, the trace confidence the online threshold is calibrated on.
1 parent c0dc4f0 commit 990b5f9

4 files changed

Lines changed: 104 additions & 21 deletions

File tree

‎optillm/deepconf/README.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,7 @@ print(response.choices[0].message.content)
7070
| `top_k` | `5` | Number of top tokens for confidence calculation |
7171
| `min_trace_length` | `100` | Minimum tokens before allowing early termination |
7272
| `max_tokens_per_trace` | `4096` | Maximum tokens per individual trace |
73-
| `confidence_metric` | `"average_confidence"` | Metric used for threshold calculation |
73+
| `confidence_metric` | `"lowest_group"` | Trace confidence used for the threshold and as voting weight (`"lowest_group"`, `"bottom_10_percent"` or `"average_confidence"`) |
7474
| `include_stats` | `false` | Include processing statistics in response |
7575

7676
### Advanced Usage

‎optillm/deepconf/confidence.py‎

Lines changed: 22 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -133,18 +133,34 @@ def get_average_trace_confidence(self) -> float:
133133
return 0.0
134134
return np.mean(self.token_confidences)
135135

136+
def _trace_group_confidences(self) -> List[float]:
137+
"""
138+
Group confidences of the whole trace. A trace shorter than the window
139+
forms a single group of all its tokens, as in the DeepConf reference
140+
implementation, rather than having no groups at all.
141+
142+
Returns:
143+
List of group confidences (empty only for an empty trace)
144+
"""
145+
if self.group_confidences:
146+
return self.group_confidences
147+
if self.token_confidences:
148+
return [float(np.mean(self.token_confidences))]
149+
return []
150+
136151
def get_bottom_10_percent_confidence(self) -> float:
137152
"""
138153
Calculate average confidence of bottom 10% groups.
139154
140155
Returns:
141156
Bottom 10% group confidence
142157
"""
143-
if not self.group_confidences:
158+
group_confidences = self._trace_group_confidences()
159+
if not group_confidences:
144160
return 0.0
145161

146-
num_bottom = max(1, len(self.group_confidences) // 10)
147-
sorted_confidences = sorted(self.group_confidences)
162+
num_bottom = max(1, len(group_confidences) // 10)
163+
sorted_confidences = sorted(group_confidences)
148164
bottom_confidences = sorted_confidences[:num_bottom]
149165

150166
return np.mean(bottom_confidences)
@@ -156,9 +172,10 @@ def get_lowest_group_confidence(self) -> float:
156172
Returns:
157173
Lowest group confidence
158174
"""
159-
if not self.group_confidences:
175+
group_confidences = self._trace_group_confidences()
176+
if not group_confidences:
160177
return 0.0
161-
return min(self.group_confidences)
178+
return min(group_confidences)
162179

163180
def get_trace_statistics(self) -> Dict[str, float]:
164181
"""

‎optillm/deepconf/processor.py‎

Lines changed: 22 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -31,7 +31,7 @@
3131
"min_trace_length": 100, # Minimum tokens before termination allowed
3232
"max_tokens_per_trace": 4096, # Maximum tokens per individual trace
3333
"temperature": 0.7, # Generation temperature
34-
"confidence_metric": "average_confidence", # Metric for threshold calculation
34+
"confidence_metric": "lowest_group", # Metric for threshold and voting weights
3535
"include_stats": False, # Include debugging statistics in response
3636
}
3737

@@ -242,6 +242,9 @@ def weighted_majority_vote(self, traces: List[TraceResult]) -> Tuple[str, Dict[s
242242
if not traces:
243243
return "", {}
244244

245+
# Early-terminated traces were cut off mid-reasoning, so they don't vote
246+
traces = [trace for trace in traces if not trace.terminated_early] or traces
247+
245248
# Group traces by answer and calculate weighted scores
246249
answer_groups = defaultdict(list)
247250
for trace in traces:
@@ -251,17 +254,14 @@ def weighted_majority_vote(self, traces: List[TraceResult]) -> Tuple[str, Dict[s
251254
answer = trace.text.strip()[-50:].strip()
252255
answer_groups[answer].append(trace)
253256

254-
# Calculate weighted scores for each answer
255-
answer_scores = {}
256-
for answer, group_traces in answer_groups.items():
257-
# Weight by average confidence
258-
confidences = [trace.confidence_stats['average_confidence'] for trace in group_traces]
259-
weighted_score = sum(confidences) / len(confidences) # Average confidence
260-
count_weight = len(group_traces) / len(traces) # Frequency weight
261-
262-
# Combine confidence and frequency
263-
final_score = weighted_score * 0.7 + count_weight * 0.3
264-
answer_scores[answer] = final_score
257+
# Each answer scores the sum of its traces' confidences (DeepConf's
258+
# confidence-weighted majority vote), so agreement and confidence
259+
# both count
260+
metric = self.config["confidence_metric"]
261+
answer_scores = {
262+
answer: sum(trace.confidence_stats[metric] for trace in group_traces)
263+
for answer, group_traces in answer_groups.items()
264+
}
265265

266266
# Select best answer
267267
best_answer = max(answer_scores.keys(), key=lambda x: answer_scores[x])
@@ -315,8 +315,16 @@ def process_online(self, messages: List[Dict[str, str]]) -> Tuple[str, Dict[str,
315315
f"(ratio: {consensus_ratio:.3f})")
316316
break
317317

318-
# Phase 3: Final answer selection
319-
final_answer, voting_stats = self.weighted_majority_vote(all_traces)
318+
# Phase 3: Final answer selection. As in the DeepConf reference
319+
# implementation, warmup traces vote only if they pass the threshold.
320+
metric = self.config["confidence_metric"]
321+
voting_traces = [
322+
trace for trace in self.warmup_traces
323+
if trace.confidence_stats[metric] >= self.confidence_threshold
324+
] + self.online_traces
325+
final_answer, voting_stats = self.weighted_majority_vote(
326+
voting_traces or all_traces
327+
)
320328

321329
# Compile processing statistics
322330
processing_stats = {

‎tests/test_deepconf.py‎

Lines changed: 59 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -161,6 +161,61 @@ def test_info_function():
161161
logger.error(f"✗ Info function test failed: {e}")
162162
return False
163163

164+
def _trace(text, confidence, terminated_early=False):
165+
from optillm.deepconf.processor import TraceResult
166+
167+
stats = {
168+
"average_confidence": confidence,
169+
"bottom_10_percent": confidence,
170+
"lowest_group": confidence,
171+
}
172+
trace = TraceResult([], text, stats)
173+
trace.terminated_early = terminated_early
174+
return trace
175+
176+
def _processor():
177+
from unittest.mock import Mock
178+
from optillm.deepconf.processor import DeepConfProcessor
179+
180+
return DeepConfProcessor(Mock(), Mock())
181+
182+
def test_short_trace_group_confidence():
183+
"""A trace shorter than the window is one group of all its tokens."""
184+
import torch
185+
from optillm.deepconf.confidence import ConfidenceCalculator
186+
187+
calculator = ConfidenceCalculator(window_size=2048, top_k=5)
188+
for _ in range(50):
189+
calculator.add_token_confidence(torch.randn(1000))
190+
stats = calculator.get_trace_statistics()
191+
192+
assert stats["num_groups"] == 0
193+
assert stats["lowest_group"] == stats["average_confidence"] > 0
194+
assert stats["bottom_10_percent"] == stats["average_confidence"]
195+
return True
196+
197+
def test_weighted_vote_sums_confidences():
198+
"""Each answer scores the sum of its traces' confidences, so many agreeing
199+
traces outvote one slightly more confident trace."""
200+
traces = [_trace("The answer is 42", 9.0) for _ in range(15)]
201+
traces.append(_trace("The answer is 7", 9.5))
202+
203+
answer, stats = _processor().weighted_majority_vote(traces)
204+
205+
assert answer == "The answer is 42"
206+
assert abs(stats["best_score"] - 15 * 9.0) < 1e-9
207+
return True
208+
209+
def test_weighted_vote_skips_early_terminated_traces():
210+
"""Traces cut off by early termination are unfinished and don't vote."""
211+
traces = [_trace("The answer is 42", 9.0) for _ in range(3)]
212+
traces += [_trace("The answer is 7 because", 9.0, True) for _ in range(4)]
213+
214+
answer, _ = _processor().weighted_majority_vote(traces)
215+
216+
assert answer == "The answer is 42"
217+
return True
218+
164219
def main():
165220
"""Run all tests."""
166221
logger.info("Starting DeepConf test suite...")
@@ -170,7 +225,10 @@ def main():
170225
test_confidence_calculator,
171226
test_threshold_calibrator,
172227
test_config_validation,
173-
test_info_function
228+
test_info_function,
229+
test_short_trace_group_confidence,
230+
test_weighted_vote_sums_confidences,
231+
test_weighted_vote_skips_early_terminated_traces,
174232
]
175233

176234
passed = 0

0 commit comments

Comments
 (0)