File size: 15,752 Bytes
c1cd11a |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 |
"""
Example usage of Online mode with warmup
This demonstrates:
1. Warmup phase (generate N sequences to calibrate threshold)
2. Threshold computation (DeepConf-low or DeepConf-high)
3. Final generation with calibrated early stopping
"""
from typing import Optional
import numpy as np
import torch
from transformers import AutoModelForCausalLM, AutoTokenizer, GenerationConfig
def extract_answer(text: str) -> Optional[str]:
"""
Extract boxed answer from LaTeX text
Looks for \\boxed{answer} pattern in generated text.
"""
if "boxed" in text:
ans = text.split("boxed")[-1]
if len(ans) == 0:
return ""
elif ans[0] == "{":
stack = 1
a = ""
for c in ans[1:]:
if c == "{":
stack += 1
a += c
elif c == "}":
stack -= 1
if stack == 0:
break
a += c
else:
a += c
else:
a = ans.split("$")[0].strip()
return a.strip()
return None
def compute_least_grouped(confs: list, group_size: int) -> list:
"""
Compute sliding window mean confidence
Args:
confs: List of per-token confidence values
group_size: Size of sliding window
Returns:
List of mean confidences for each window position
"""
if len(confs) < group_size:
return [sum(confs) / len(confs)] if confs else [0]
sliding_means = []
for i in range(len(confs) - group_size + 1):
window = confs[i : i + group_size]
sliding_means.append(round(sum(window) / len(window), 3))
return sliding_means
def process_single_output(
sequence, confidences, tokenizer, window_size: int, threshold: Optional[float] = None
) -> dict:
"""
Process a single generated sequence
Args:
sequence: Generated token IDs
confidences: Per-token confidence values (list or tensor)
tokenizer: Tokenizer for decoding
window_size: Size of sliding window for confidence
threshold: Optional threshold for early stopping detection
Returns:
Dictionary with trace data
"""
# Convert to list if tensor
if hasattr(confidences, "tolist"):
confs = confidences.tolist()
else:
confs = list(confidences)
# Decode text
text = tokenizer.decode(sequence, skip_special_tokens=True)
# Compute sliding window statistics
sliding_window = compute_least_grouped(confs, window_size)
min_conf = min(sliding_window) if sliding_window else 0
# Determine if early stopping would have triggered
stopped_early = False
stop_position = None
if threshold is not None:
for pos, window_mean in enumerate(sliding_window):
if window_mean < threshold:
stopped_early = True
stop_position = pos + window_size # Position in original sequence
break
# Extract answer if present
extracted_answer = extract_answer(text)
return {
"text": text,
"confs": confs,
"group_confs": sliding_window,
"min_conf": min_conf,
"stopped_early": stopped_early,
"stop_position": stop_position,
"extracted_answer": extracted_answer,
"num_tokens": len(confs),
"token_ids": sequence.tolist() if hasattr(sequence, "tolist") else list(sequence),
}
def process_batch_results(outputs, tokenizer, window_size: int = 2048, threshold: Optional[float] = None) -> dict:
"""
Process batch generation outputs
This function provides post-processing capabilities for batch-generated
sequences, allowing analysis of confidence patterns and early stopping
behavior after generation is complete.
Args:
outputs: GenerateDecoderOnlyOutput from model.generate()
tokenizer: Tokenizer for decoding sequences
window_size: Size of sliding window for confidence computation
threshold: Optional threshold for detecting where early stopping would occur
Returns:
Dictionary containing:
- traces: List of processed trace dictionaries
- min_confs: List of minimum confidences per trace
- total_tokens: Total tokens across all traces
- num_traces: Number of traces processed
"""
if not hasattr(outputs, "sequences"):
raise ValueError("outputs must have 'sequences' attribute")
if not hasattr(outputs, "confidences") or outputs.confidences is None:
raise ValueError("outputs must have 'confidences' attribute. Set output_confidences=True in generation_config")
sequences = outputs.sequences
confidences = outputs.confidences
# Process each sequence
traces = []
min_confs = []
total_tokens = 0
for i in range(sequences.shape[0]):
trace_data = process_single_output(sequences[i], confidences[i], tokenizer, window_size, threshold)
traces.append(trace_data)
min_confs.append(trace_data["min_conf"])
total_tokens += trace_data["num_tokens"]
return {"traces": traces, "min_confs": min_confs, "total_tokens": total_tokens, "num_traces": len(traces)}
def compute_warmup_threshold(min_confs: list, variant: str = "low", eta: Optional[float] = None) -> float:
"""
Compute threshold from warmup confidences
Args:
min_confs: List of minimum confidences from warmup sequences
variant: "low" (aggressive) or "high" (permissive)
eta: Optional manual eta value (overrides variant default)
Returns:
Computed threshold value
"""
if eta is None:
eta = 0.1 if variant == "low" else 0.9 if variant == "high" else 0.5
confs = np.asarray(min_confs, dtype=np.float32)
pct = max(0.0, min(100.0, 100.0 - (eta * 100.0)))
threshold = float(np.percentile(confs, pct))
return threshold
# ============================================================================
# Example Functions
# ============================================================================
def prepare_prompt(question: str, tokenizer):
"""Prepare prompt using chat template"""
messages = [{"role": "user", "content": question}]
prompt = tokenizer.apply_chat_template(messages, tokenize=False, add_generation_prompt=True)
return prompt
def run_online_mode_example(
question: str,
ground_truth: Optional[str] = None,
warmup_traces: int = 8,
confidence_variant: str = "low", # "low" or "high"
window_size: int = 10,
max_tokens: int = 128,
temperature: float = 0.7,
top_p: float = 0.95,
):
"""
Run DeepConf in online mode
Args:
question: Question to answer
ground_truth: Optional ground truth answer for evaluation
warmup_traces: Number of warmup sequences (default: 8)
confidence_variant: "low" (aggressive) or "high" (permissive)
window_size: Sliding window size for confidence
max_tokens: Max tokens per generation
temperature: Sampling temperature
top_p: Top-p sampling
"""
# Load model (use local cache to avoid HF Hub timeouts)
model_name = "Qwen/Qwen2.5-0.5B-Instruct"
print(f"Loading model: {model_name}")
model = AutoModelForCausalLM.from_pretrained(
model_name,
torch_dtype=torch.float16,
device_map="auto",
local_files_only=True, # Use cached model
)
tokenizer = AutoTokenizer.from_pretrained(model_name, local_files_only=True)
# Prepare prompt
prompt = prepare_prompt(question, tokenizer)
inputs = tokenizer(prompt, return_tensors="pt").to(model.device)
print("\n" + "=" * 80)
print("DEEPCONF ONLINE MODE - FOLLOWING OFFICIAL PATTERN")
print("=" * 80)
print(f"\nQuestion: {question}")
if ground_truth:
print(f"Ground truth: {ground_truth}")
print("\nConfiguration:")
print(f" - Warmup traces: {warmup_traces}")
print(f" - Variant: DeepConf-{confidence_variant}")
print(f" - Window size: {window_size}")
print(f" - Max tokens: {max_tokens}")
print(f" - Temperature: {temperature}")
print(f" - Top-p: {top_p}")
# ============================================================
# PHASE 1: WARMUP - Generate multiple sequences to calibrate
# ============================================================
print("\n" + "=" * 80)
print(f"PHASE 1: WARMUP (Generating {warmup_traces} sequences for calibration)")
print("=" * 80)
warmup_config = GenerationConfig(
do_sample=True,
temperature=temperature,
top_p=top_p,
max_new_tokens=max_tokens,
enable_conf=True,
enable_early_stopping=False, # No stopping during warmup
output_confidences=True,
return_dict_in_generate=True,
pad_token_id=tokenizer.eos_token_id,
)
# Expand inputs for batch generation
expanded_ids = inputs.input_ids.repeat(warmup_traces, 1)
if "attention_mask" in inputs and inputs.attention_mask is not None:
expanded_mask = inputs.attention_mask.repeat(warmup_traces, 1)
else:
expanded_mask = None
print(f"Generating {warmup_traces} warmup sequences...")
warmup_outputs = model.generate(
input_ids=expanded_ids,
attention_mask=expanded_mask,
generation_config=warmup_config,
custom_generate="kashif/DeepConf",
trust_remote_code=True,
)
# Process warmup results
warmup_results = process_batch_results(warmup_outputs, tokenizer, window_size=window_size)
print("\nWarmup complete!")
print(f" - Total tokens: {warmup_results['total_tokens']}")
print(f" - Min confidences: {[round(c, 3) for c in warmup_results['min_confs']]}")
# Show warmup traces
print("\nWarmup Traces:")
print("-" * 80)
for i, trace in enumerate(warmup_results["traces"]):
text = trace["text"][len(prompt) :].strip()
answer = extract_answer(text)
print(f"\nTrace {i + 1}:")
print(f" Tokens: {trace['num_tokens']}, Min conf: {trace['min_conf']:.3f}")
print(f" Text: {text[:80]}..." if len(text) > 80 else f" Text: {text}")
if answer:
print(f" Answer: {answer}")
if ground_truth:
correct = answer.strip() == ground_truth.strip()
print(f" Correct: {'β' if correct else 'β'}")
# ============================================================
# PHASE 2: THRESHOLD COMPUTATION
# ============================================================
print("\n" + "=" * 80)
print("PHASE 2: THRESHOLD COMPUTATION")
print("=" * 80)
threshold = compute_warmup_threshold(warmup_results["min_confs"], variant=confidence_variant)
eta = 0.1 if confidence_variant == "low" else 0.9
percentile = (1.0 - eta) * 100
print("\nComputed threshold from warmup:")
print(f" - Variant: DeepConf-{confidence_variant} (eta={eta})")
print(f" - Percentile: {percentile:.0f}th")
print(f" - Threshold: {threshold:.3f}")
print("\nInterpretation:")
if confidence_variant == "low":
print(" DeepConf-low is AGGRESSIVE - stops early to save tokens")
else:
print(" DeepConf-high is PERMISSIVE - allows longer generation")
# ============================================================
# PHASE 3: FINAL GENERATION with calibrated threshold
# ============================================================
print("\n" + "=" * 80)
print("PHASE 3: FINAL GENERATION (With calibrated early stopping)")
print("=" * 80)
final_config = GenerationConfig(
do_sample=True,
temperature=temperature,
top_p=top_p,
max_new_tokens=max_tokens,
enable_conf=True,
enable_early_stopping=True, # Online stopping with calibrated threshold
threshold=threshold,
window_size=window_size,
output_confidences=True,
return_dict_in_generate=True,
pad_token_id=tokenizer.eos_token_id,
)
print(f"Generating with DeepConf-{confidence_variant} (threshold={threshold:.3f})...")
final_output = model.generate(
**inputs,
generation_config=final_config,
custom_generate="kashif/DeepConf",
trust_remote_code=True,
)
final_text = tokenizer.decode(final_output.sequences[0], skip_special_tokens=True)
final_tokens = final_output.sequences.shape[1] - inputs.input_ids.shape[1]
final_answer = extract_answer(final_text)
# Calculate min confidence if available
if hasattr(final_output, "confidences") and final_output.confidences is not None:
min_conf = final_output.confidences.min().item()
mean_conf = final_output.confidences.mean().item()
else:
min_conf = None
mean_conf = None
print("\nFinal generation complete!")
print(f" - Tokens generated: {final_tokens}")
if min_conf is not None:
print(f" - Min confidence: {min_conf:.3f}")
print(f" - Mean confidence: {mean_conf:.3f}")
print("\nGenerated text:")
print("-" * 80)
print(final_text)
print("-" * 80)
if final_answer:
print(f"\nExtracted answer: {final_answer}")
if ground_truth:
correct = final_answer.strip() == ground_truth.strip()
print(f"Correct: {'β' if correct else 'β'}")
# ============================================================
# SUMMARY
# ============================================================
print("\n" + "=" * 80)
print("SUMMARY")
print("=" * 80)
total_warmup_tokens = warmup_results["total_tokens"]
total_tokens = total_warmup_tokens + final_tokens
print(f"Total tokens: {total_tokens}")
print(f" - Warmup: {total_warmup_tokens} ({warmup_traces} sequences)")
print(f" - Final: {final_tokens}")
# Check if we would have used more tokens without early stopping
avg_warmup_tokens = total_warmup_tokens / warmup_traces
potential_savings = avg_warmup_tokens - final_tokens
if potential_savings > 0:
print("\nToken savings from early stopping:")
print(f" - Average warmup length: {avg_warmup_tokens:.1f} tokens")
print(f" - Final length: {final_tokens} tokens")
print(f" - Saved: {potential_savings:.1f} tokens ({potential_savings / avg_warmup_tokens * 100:.1f}%)")
print("\n" + "=" * 80)
print("Example complete!")
print("=" * 80)
if __name__ == "__main__":
# Example 1: Simple math problem
print("\n\n" + "β" * 80)
print("EXAMPLE 1: Simple Math Problem")
print("β" * 80)
run_online_mode_example(
question="What is 15 * 8? Show your work step by step.",
ground_truth="120",
warmup_traces=4,
confidence_variant="low",
window_size=5,
max_tokens=64,
)
# Example 2: Square root problem
print("\n\n" + "β" * 80)
print("EXAMPLE 2: Square Root Problem")
print("β" * 80)
run_online_mode_example(
question="What is the square root of 144? Express your answer in the form \\boxed{answer}.",
ground_truth="12",
warmup_traces=4,
confidence_variant="high",
window_size=5,
max_tokens=64,
)
# Example 3: Word problem
print("\n\n" + "β" * 80)
print("EXAMPLE 3: Word Problem")
print("β" * 80)
run_online_mode_example(
question="If a train travels 60 miles per hour for 2.5 hours, how far does it travel?",
ground_truth="150",
warmup_traces=4,
confidence_variant="low",
window_size=5,
max_tokens=96,
)
|