File size: 29,309 Bytes
24c2665 |
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 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 |
#!/usr/bin/env python3
"""
Complete TestTime RLVR Pipeline Test Script
AZR κΈ°λ° TestTime RLVR νμ΄νλΌμΈμ μ€μ λ²€μΉλ§ν¬ λ¬Έμ λ‘ ν
μ€νΈ
LLM μ루μ
μμ± β IPO μΆμΆ β νμ€ν¬ μμ± β LLM νκ° β Reward κ³μ° μ 체 νλ‘μ° κ²μ¦
"""
import os
import sys
import torch
import argparse
import json
from pathlib import Path
from datetime import datetime
# TestTime RLVR λͺ¨λ μν¬νΈ
sys.path.append('/home/ubuntu/RLVR/TestTime-RLVR-v2')
from absolute_zero_reasoner.testtime.complete_pipeline import CompleteTestTimePipeline
from absolute_zero_reasoner.testtime.config import TestTimeConfig, BenchmarkConfig
from absolute_zero_reasoner.testtime.logger import TestTimeLogger
from absolute_zero_reasoner.testtime.solution_generator import InitialSolutionGenerator
def load_test_problem():
"""κ°λ¨ν ν
μ€νΈ λ¬Έμ μμ± (HumanEval μ€νμΌ)"""
return {
'task_id': 'test/simple_sum',
'prompt': '''def add_two_numbers(a, b):
"""
Add two numbers and return the result.
Args:
a (int): First number
b (int): Second number
Returns:
int: Sum of a and b
Examples:
>>> add_two_numbers(2, 3)
5
>>> add_two_numbers(-1, 1)
0
>>> add_two_numbers(0, 0)
0
"""''',
'entry_point': 'add_two_numbers',
'canonical_solution': 'def add_two_numbers(a, b):\n return a + b',
'test': '''def check(candidate):
assert candidate(2, 3) == 5
assert candidate(-1, 1) == 0
assert candidate(0, 0) == 0
assert candidate(10, -5) == 5'''
}
def save_detailed_results(result, args, output_dir):
"""μμΈν κ²°κ³Όλ₯Ό κ°λ³ νμΌλ‘ μ μ₯"""
# λ²€μΉλ§ν¬μ λ¬Έμ IDμ λ°λ₯Έ λλ ν 리 ꡬ쑰 μμ±
benchmark = result.get('benchmark', 'unknown')
problem_id = result['problem_id'] # '/' μ μ§
problem_id_safe = problem_id.replace('/', '_') # νμΌλͺ
μ©
# {output_dir}/{benchmark}/{task_id} κ΅¬μ‘°λ‘ λλ ν 리 μμ±
base_dir = os.path.join(output_dir, benchmark, problem_id_safe)
os.makedirs(base_dir, exist_ok=True)
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
# 1. μ΄κΈ° LLM μ루μ
μ μ₯ (λ²€μΉλ§ν¬ λ¬Έμ ν΄κ²°)
if 'llm_generation' in result['steps']:
llm_step = result['steps']['llm_generation']
initial_solution_dir = os.path.join(base_dir, 'initial_solution')
os.makedirs(initial_solution_dir, exist_ok=True)
# λ²€μΉλ§ν¬ λ¬Έμ μλ³Έ μ μ₯
if 'problem_loading' in result['steps']:
problem_data = result['steps']['problem_loading'].get('problem', {})
problem_file = os.path.join(initial_solution_dir, f"{problem_id_safe}_original_problem.txt")
with open(problem_file, 'w', encoding='utf-8') as f:
f.write(f"Problem ID: {result['problem_id']}\n")
f.write(f"Benchmark: {result['benchmark']}\n")
f.write(f"Generated: {timestamp}\n")
f.write("="*80 + "\n")
f.write("ORIGINAL BENCHMARK PROBLEM:\n")
f.write("="*80 + "\n")
f.write(problem_data.get('prompt', 'No prompt available'))
f.write("\n" + "="*80 + "\n")
f.write("ENTRY POINT:\n")
f.write("="*80 + "\n")
f.write(problem_data.get('entry_point', 'No entry point'))
f.write("\n" + "="*80 + "\n")
f.write("CANONICAL SOLUTION:\n")
f.write("="*80 + "\n")
f.write(problem_data.get('canonical_solution', 'No canonical solution'))
if 'test' in problem_data:
f.write("\n" + "="*80 + "\n")
f.write("TEST CASES:\n")
f.write("="*80 + "\n")
f.write(str(problem_data['test']))
# LLM μμ± μ루μ
μ μ₯
llm_solution_file = os.path.join(initial_solution_dir, f"{problem_id_safe}_llm_solution.txt")
with open(llm_solution_file, 'w', encoding='utf-8') as f:
f.write(f"Problem ID: {result['problem_id']}\n")
f.write(f"Benchmark: {result['benchmark']}\n")
f.write(f"Generated: {timestamp}\n")
f.write("="*80 + "\n")
f.write("LLM GENERATED SOLUTION:\n")
f.write("="*80 + "\n")
f.write(llm_step.get('solution', 'No solution generated'))
f.write("\n" + "="*80 + "\n")
f.write("SYNTAX VALIDATION:\n")
f.write("="*80 + "\n")
syntax_valid = llm_step.get('syntax_valid', False)
f.write(f"Valid: {'β
YES' if syntax_valid else 'β NO'}")
if llm_step.get('syntax_error'):
f.write(f"\nError: {llm_step['syntax_error']}")
# μ΄κΈ° μ루μ
μ νμ± νκ° κ²°κ³Ό μΆκ°
f.write("\n" + "="*80 + "\n")
f.write("SOLUTION CORRECTNESS EVALUATION:\n")
f.write("="*80 + "\n")
solution_eval = llm_step.get('solution_evaluation')
if solution_eval:
if solution_eval['correct']:
f.write(f"Result: β
CORRECT ({solution_eval['passed_tests']}/{solution_eval['total_tests']} tests passed)\n")
else:
f.write(f"Result: β INCORRECT ({solution_eval['passed_tests']}/{solution_eval['total_tests']} tests passed)\n")
if solution_eval.get('error'):
f.write(f"Error: {solution_eval['error']}\n")
# μ€ν κ²°κ³Ό μμΈ μ 보
if solution_eval.get('execution_results'):
f.write("\nExecution Details:\n")
for i, exec_result in enumerate(solution_eval['execution_results']):
f.write(f" Test {i+1}:\n")
f.write(f" Status: {exec_result.get('status', 'N/A')}\n")
if 'result' in exec_result:
f.write(f" Result: {exec_result['result'][:100]}...\n")
else:
f.write("No evaluation performed (syntax error or no test cases)\n")
# IPO μΆμΆμ μν΄ μ¬μ©λ νλ‘κ·Έλ¨ μ μ₯
if 'ipo_extraction' in result['steps']:
ipo_step = result['steps']['ipo_extraction']
if 'extracted_program' in ipo_step:
extracted_program_file = os.path.join(initial_solution_dir, f"{problem_id_safe}_extracted_program.py")
with open(extracted_program_file, 'w', encoding='utf-8') as f:
f.write(f"# Problem ID: {result['problem_id']}\n")
f.write(f"# Benchmark: {result['benchmark']}\n")
f.write(f"# Generated: {timestamp}\n")
f.write(f"# Extracted from LLM solution for IPO generation\n\n")
f.write(ipo_step['extracted_program'])
print(f"π μ΄κΈ° μ루μ
μ μ₯: {initial_solution_dir}/")
# 2. IPO νΈλ¦¬ν μ μ₯
if 'ipo_extraction' in result['steps']:
ipo_step = result['steps']['ipo_extraction']
triples = ipo_step.get('triples', [])
ipo_dir = os.path.join(base_dir, 'ipo_triples')
os.makedirs(ipo_dir, exist_ok=True)
for i, triple in enumerate(triples):
triple_file = os.path.join(ipo_dir, f"{problem_id_safe}_triple_{i+1}.json")
with open(triple_file, 'w', encoding='utf-8') as f:
json.dump(triple, f, indent=2, ensure_ascii=False)
print(f"π IPO νΈλ¦¬ν μ μ₯: {ipo_dir}/ ({len(triples)}κ° νμΌ)")
# 3. μμ±λ νμ€ν¬ ν둬ννΈ μ μ₯
if 'task_generation' in result['steps']:
task_step = result['steps']['task_generation']
all_tasks = task_step.get('all_tasks', {})
task_dir = os.path.join(base_dir, 'task_prompts')
os.makedirs(task_dir, exist_ok=True)
task_count = 0
for task_type, tasks in all_tasks.items():
for i, task in enumerate(tasks):
task_file = os.path.join(task_dir, f"{problem_id_safe}_{task_type}_{i+1}.txt")
with open(task_file, 'w', encoding='utf-8') as f:
f.write(f"Task Type: {task_type}\n")
f.write(f"Task ID: {task.get('task_id', 'N/A')}\n")
f.write(f"Generated: {timestamp}\n")
f.write("="*80 + "\n")
f.write("TASK PROMPT:\n")
f.write("="*80 + "\n")
f.write(task.get('prompt', 'No prompt available'))
f.write("\n" + "="*80 + "\n")
f.write("EXPECTED SOLUTION:\n")
f.write("="*80 + "\n")
f.write(task.get('expected_solution', 'No expected solution'))
f.write("\n" + "="*80 + "\n")
f.write("EVALUATION DATA:\n")
f.write("="*80 + "\n")
f.write(str(task.get('evaluation_data', 'No evaluation data')))
task_count += 1
print(f"π νμ€ν¬ ν둬ννΈ μ μ₯: {task_dir}/ ({task_count}κ° νμΌ)")
# 4. LLM νμ€ν¬ μλ΅ μ μ₯
if 'task_evaluation' in result['steps']:
eval_step = result['steps']['task_evaluation']
evaluations = eval_step.get('evaluations', {})
response_dir = os.path.join(base_dir, 'llm_responses')
os.makedirs(response_dir, exist_ok=True)
response_count = 0
for task_type, task_evals in evaluations.items():
for i, evaluation in enumerate(task_evals):
response_file = os.path.join(response_dir, f"{problem_id_safe}_{task_type}_{i+1}_response.txt")
with open(response_file, 'w', encoding='utf-8') as f:
f.write(f"Task Type: {task_type}\n")
f.write(f"Task ID: {evaluation.get('task_id', 'N/A')}\n")
f.write(f"Generated: {timestamp}\n")
f.write("="*80 + "\n")
f.write("ORIGINAL PROMPT:\n")
f.write("="*80 + "\n")
f.write(evaluation.get('prompt', 'No prompt available'))
f.write("\n" + "="*80 + "\n")
f.write("LLM RESPONSE:\n")
f.write("="*80 + "\n")
f.write(evaluation.get('llm_response', 'No response'))
f.write("\n" + "="*80 + "\n")
f.write("EXPECTED SOLUTION:\n")
f.write("="*80 + "\n")
f.write(evaluation.get('expected_solution', 'No expected solution'))
# μΆμΆλ μ λ΅ μ 보 μΆκ° (보μ κ³μ° κ²°κ³Όμμ κ°μ Έμ€κΈ°)
if 'reward_computation' in result['steps']:
reward_step = result['steps']['reward_computation']
rewards = reward_step.get('rewards', {})
rewards_by_type = rewards.get('rewards_by_type', {})
# νμ¬ νμ€ν¬μ 보μ μ 보 μ°ΎκΈ°
current_task_rewards = rewards_by_type.get(task_type, [])
current_reward = None
for reward in current_task_rewards:
if reward.get('task_id') == evaluation.get('task_id'):
current_reward = reward
break
if current_reward and 'extracted_answer' in current_reward:
f.write("\n" + "="*80 + "\n")
f.write("EXTRACTED ANSWER:\n")
f.write("="*80 + "\n")
f.write(current_reward['extracted_answer'])
f.write("\n" + "="*80 + "\n")
f.write("MATCH RESULT:\n")
f.write("="*80 + "\n")
match_result = "β
CORRECT" if current_reward.get('basic_accuracy', 0) > 0 else "β INCORRECT"
f.write(f"{match_result} (Score: {current_reward.get('basic_accuracy', 0):.3f})")
response_count += 1
print(f"π LLM μλ΅ μ μ₯: {response_dir}/ ({response_count}κ° νμΌ)")
# 4-1. μΆμΆλ μ λ΅ λ³λ μ μ₯
if 'reward_computation' in result['steps']:
reward_step = result['steps']['reward_computation']
rewards = reward_step.get('rewards', {})
rewards_by_type = rewards.get('rewards_by_type', {})
extracted_dir = os.path.join(base_dir, 'extracted_answers')
os.makedirs(extracted_dir, exist_ok=True)
extracted_count = 0
for task_type, task_rewards in rewards_by_type.items():
for reward in task_rewards:
if 'extracted_answer' in reward:
task_id = reward.get('task_id', 'unknown')
extracted_file = os.path.join(extracted_dir, f"{problem_id_safe}_{task_type}_{task_id}_extracted.txt")
with open(extracted_file, 'w', encoding='utf-8') as f:
f.write(f"Task Type: {task_type}\n")
f.write(f"Task ID: {task_id}\n")
f.write(f"Generated: {timestamp}\n")
f.write("="*80 + "\n")
f.write("EXTRACTED ANSWER:\n")
f.write("="*80 + "\n")
f.write(reward['extracted_answer'])
f.write("\n" + "="*80 + "\n")
f.write("EXPECTED SOLUTION:\n")
f.write("="*80 + "\n")
f.write(reward['expected_solution'])
f.write("\n" + "="*80 + "\n")
f.write("MATCH RESULT:\n")
f.write("="*80 + "\n")
match_result = "β
CORRECT" if reward.get('basic_accuracy', 0) > 0 else "β INCORRECT"
f.write(f"{match_result} (Score: {reward.get('basic_accuracy', 0):.3f})")
extracted_count += 1
print(f"π μΆμΆλ μ λ΅ μ μ₯: {extracted_dir}/ ({extracted_count}κ° νμΌ)")
# 5. μ λ΅ λΉκ΅ λ° λ³΄μ κ²°κ³Ό μ μ₯
if 'reward_computation' in result['steps']:
reward_step = result['steps']['reward_computation']
rewards = reward_step.get('rewards', {})
reward_file = os.path.join(base_dir, f"{problem_id_safe}_reward_analysis.json")
with open(reward_file, 'w', encoding='utf-8') as f:
json.dump(rewards, f, indent=2, ensure_ascii=False)
# μ¬λμ΄ μ½κΈ° μ¬μ΄ 보μ μμ½ μ μ₯
summary_file = os.path.join(base_dir, f"{problem_id_safe}_reward_summary.txt")
with open(summary_file, 'w', encoding='utf-8') as f:
f.write(f"REWARD ANALYSIS SUMMARY\n")
f.write(f"Problem: {result['problem_id']}\n")
f.write(f"Benchmark: {result['benchmark']}\n")
f.write(f"Generated: {timestamp}\n")
f.write("="*80 + "\n")
f.write(f"OVERALL STATISTICS:\n")
f.write(f"- Total Tasks: {rewards.get('total_tasks', 0)}\n")
f.write(f"- Average Reward: {rewards.get('average_reward', 0.0):.3f}\n")
f.write("\n")
f.write(f"REWARD BY TASK TYPE:\n")
for task_type, avg_reward in rewards.get('reward_distribution', {}).items():
f.write(f"- {task_type.title()}: {avg_reward:.3f}\n")
f.write("\n")
f.write(f"DETAILED TASK REWARDS:\n")
for task_type, task_rewards in rewards.get('rewards_by_type', {}).items():
f.write(f"\n{task_type.upper()} TASKS:\n")
for reward in task_rewards:
f.write(f" Task {reward['task_id']}: ")
f.write(f"Accuracy={reward['basic_accuracy']:.3f}, ")
f.write(f"Final={reward['final_reward']:.3f}\n")
print(f"π 보μ λΆμ μ μ₯: {reward_file}")
print(f"π 보μ μμ½ μ μ₯: {summary_file}")
# 6. μ 체 κ²°κ³Ό μμ½ μ μ₯ (JSON μ§λ ¬ν κ°λ₯νκ² μμ )
summary_file = os.path.join(base_dir, f"{problem_id_safe}_pipeline_summary.json")
# JSON μ§λ ¬ν κ°λ₯νλλ‘ κ²°κ³Ό μ 리
serializable_result = result.copy()
# BenchmarkConfig κ°μ²΄ μ κ±° λλ μ§λ ¬ν κ°λ₯ν ννλ‘ λ³ν
if 'steps' in serializable_result and 'problem_loading' in serializable_result['steps']:
problem_data = serializable_result['steps']['problem_loading'].get('problem', {})
if 'benchmark_config' in problem_data:
# BenchmarkConfig κ°μ²΄λ₯Ό λμ
λλ¦¬λ‘ λ³ν
config_obj = problem_data['benchmark_config']
problem_data['benchmark_config'] = {
'name': config_obj.name,
'data_path': config_obj.data_path,
'problem_prefix': config_obj.problem_prefix,
'max_problems': config_obj.max_problems,
'test_timeout': config_obj.test_timeout
}
with open(summary_file, 'w', encoding='utf-8') as f:
json.dump(serializable_result, f, indent=2, ensure_ascii=False)
print(f"π μ 체 κ²°κ³Ό μμ½ μ μ₯: {summary_file}")
print(f"\nπ λͺ¨λ κ²°κ³Ό νμΌ μ μ₯ μλ£: {output_dir}")
def main():
parser = argparse.ArgumentParser(description='Test Complete TestTime RLVR Pipeline')
parser.add_argument('--model', type=str, default='Qwen/Qwen2.5-7B',
help='Model name to test with')
parser.add_argument('--gpu', type=int, default=0, help='GPU ID to use')
parser.add_argument('--max_tokens', type=int, default=512, help='Max tokens for generation')
parser.add_argument('--benchmark', type=str, default='test',
choices=['test', 'humaneval', 'mbpp'],
help='Benchmark to use (test=example data, humaneval=HumanEval+, mbpp=MBPP+)')
parser.add_argument('--problem_id', type=str, default='test/simple_sum',
help='Problem ID to test (e.g., HumanEval/0, Mbpp/2)')
parser.add_argument('--output_dir', type=str, default='../tmp',
help='Output directory for detailed results')
parser.add_argument('--verbose', action='store_true', help='Verbose logging')
args = parser.parse_args()
# GPU μ€μ
device = f'cuda:{args.gpu}' if torch.cuda.is_available() else 'cpu'
print(f"π― Using device: {device}")
# TestTime μ€μ
config = TestTimeConfig(
model_name=args.model,
max_adaptation_steps=3,
learning_rate=1e-5,
task_distribution={'induction': 0.4, 'deduction': 0.3, 'abduction': 0.3},
adaptation_batch_size=1,
max_tasks_per_type=3,
use_flash_attention=False, # μμ λͺ¨λΈμμλ λΉνμ±ν
torch_dtype=torch.float16,
enable_gradient_checkpointing=False
)
# λ²€μΉλ§ν¬ μ€μ (μ λ κ²½λ‘λ‘ κ³μ°)
base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
if args.benchmark == 'humaneval':
benchmark_config = BenchmarkConfig.get_humaneval_config()
benchmark_config.data_path = os.path.join(base_dir, 'evaluation/code_eval/data/HumanEvalPlus.jsonl')
elif args.benchmark == 'mbpp':
benchmark_config = BenchmarkConfig.get_mbpp_config()
benchmark_config.data_path = os.path.join(base_dir, 'evaluation/code_eval/data/MbppPlus.jsonl')
else: # test
benchmark_config = BenchmarkConfig(
name='test_humaneval',
data_path='test_data',
problem_prefix='TestEval',
max_problems=1,
test_timeout=30
)
# λ‘κ±° μ€μ
logger = TestTimeLogger(log_level='DEBUG' if args.verbose else 'INFO')
logger.log_info("π Starting Complete TestTime RLVR Pipeline Test")
logger.log_info(f"π Model: {args.model}")
logger.log_info(f"π― Device: {device}")
try:
# λͺ¨λΈ λ° ν ν¬λμ΄μ λ‘λ (VLLM μ΅μ ν μ μ©)
logger.log_info("π¦ Loading model and tokenizer with VLLM optimization...")
model, tokenizer = InitialSolutionGenerator.load_model_with_optimizations(
args.model, device, config, use_vllm=True # VLLM μ΅μ ν νμ±ν
)
logger.log_info("β
Model loaded successfully")
# νμ΄νλΌμΈ μ΄κΈ°ν
logger.log_info("π§ Initializing pipeline...")
pipeline = CompleteTestTimePipeline(model, tokenizer, config, logger)
logger.log_info("β
Pipeline initialized")
# λ¬Έμ ID μ€μ
problem_id = args.problem_id
logger.log_info(f"π Testing with {args.benchmark} benchmark")
logger.log_info(f"π Problem ID: {problem_id}")
# ν
μ€νΈ λͺ¨λμΈ κ²½μ° μμ λ°μ΄ν° μ¬μ©
if args.benchmark == 'test':
test_problem = load_test_problem()
logger.log_info(f"π Problem preview: {test_problem['prompt'][:100]}...")
# μμλ‘ λ¬Έμ λ₯Ό pipelineμ benchmark_loaderμ μ§μ μ 곡
pipeline.benchmark_loader.load_problem = lambda cfg, pid: test_problem
else:
# μ€μ λ²€μΉλ§ν¬ μ¬μ© μ ν둬ννΈ λ―Έλ¦¬λ³΄κΈ°
temp_problem = pipeline.benchmark_loader.load_problem(benchmark_config, problem_id)
# AZR μ½λ νκ° ν둬ννΈ ν¬λ§· μ μ©
azr_prompt = f"Please provide a self-contained Python script that solves the following problem in a markdown code block:\n\n{temp_problem.get('prompt', 'No prompt available')}"
print(f"\nπ **ORIGINAL PROBLEM:**")
print("="*80)
print(temp_problem.get('prompt', 'No prompt available'))
print("="*80)
print(f"\nπ **AZR CODE EVALUATION PROMPT (μ€μ μ¬μ©λλ ν둬ννΈ):**")
print("="*80)
print(azr_prompt)
print("="*80)
print(f"π Entry Point: {temp_problem.get('entry_point', 'N/A')}")
print(f"π Task ID: {temp_problem.get('task_id', 'N/A')}")
if 'test' in temp_problem:
print(f"π Test Preview: {str(temp_problem['test'])[:200]}...")
print("="*80)
# μ 체 νμ΄νλΌμΈ μ€ν
logger.log_info("πββοΈ Running complete pipeline...")
print("\n" + "="*60)
print("π COMPLETE TESTTIME RLVR PIPELINE EXECUTION")
print(f"π Benchmark: {args.benchmark}")
print(f"π Problem: {problem_id}")
print("="*60)
result = pipeline.run_complete_pipeline(benchmark_config, problem_id)
print("\n" + "="*60)
print("π PIPELINE EXECUTION RESULTS")
print("="*60)
# κ²°κ³Ό μΆλ ₯
print(f"β
Success: {result['success']}")
if result['error']:
print(f"β Error: {result['error']}")
print(f"π Problem: {result['problem_id']}")
print(f"π·οΈ Benchmark: {result['benchmark']}")
# λ¨κ³λ³ κ²°κ³Ό μΆλ ₯
for step_name, step_result in result['steps'].items():
print(f"\nπ Step: {step_name.replace('_', ' ').title()}")
print(f" Success: {'β
' if step_result['success'] else 'β'}")
if step_name == 'llm_generation':
solution = step_result.get('solution', '')
print(f" Solution preview: {solution[:100]}...")
print(f" Syntax valid: {'β
' if step_result.get('syntax_valid') else 'β'}")
# μ΄κΈ° μ루μ
μ νμ± νκ° κ²°κ³Ό νμ
eval_result = step_result.get('solution_evaluation')
if eval_result:
if eval_result['correct']:
print(f" β
Solution CORRECT ({eval_result['passed_tests']}/{eval_result['total_tests']} tests passed)")
else:
print(f" β Solution INCORRECT ({eval_result['passed_tests']}/{eval_result['total_tests']} tests passed)")
if eval_result.get('error'):
print(f" Error: {eval_result['error'][:80]}...")
elif step_name == 'ipo_extraction':
print(f" IPO triples extracted: {step_result.get('num_triples', 0)}")
elif step_name == 'task_generation':
print(f" Total tasks generated: {step_result.get('total_tasks', 0)}")
for task_type, count in step_result.get('tasks_by_type', {}).items():
print(f" {task_type}: {count}")
elif step_name == 'task_evaluation':
evaluations = step_result.get('evaluations', {})
total_evaluated = sum(len(evals) for evals in evaluations.values())
print(f" Tasks evaluated: {total_evaluated}")
elif step_name == 'reward_computation':
rewards = step_result.get('rewards', {})
print(f" Average reward: {rewards.get('average_reward', 0.0):.3f}")
print(f" Total tasks scored: {rewards.get('total_tasks', 0)}")
# μ λ΅ μΆμΆ μμΈ μ 보 νμ
for task_type, type_rewards in rewards.get('rewards_by_type', {}).items():
print(f" {task_type.title()} Tasks:")
for reward in type_rewards[:2]: # μ²μ 2κ°λ§ νμ
print(f" Task {reward['task_id']}: Expected='{reward['expected_solution'][:50]}...' | Extracted='{reward['extracted_answer'][:50]}...' | Match={'β
' if reward['basic_accuracy'] > 0 else 'β'}")
# μμΈ κ²°κ³Ό νμ (verbose λͺ¨λ)
if args.verbose and result['success']:
print("\n" + "="*60)
print("π DETAILED RESULTS (VERBOSE MODE)")
print("="*60)
# IPO μΆμΆ μμΈ
if 'ipo_extraction' in result['steps']:
ipo_step = result['steps']['ipo_extraction']
triples = ipo_step.get('triples', [])
print(f"\nπ IPO Triples ({len(triples)}):")
for i, triple in enumerate(triples[:3]): # μ²μ 3κ°λ§ νμ
print(f" [{i+1}] Input: {str(triple.get('input', 'N/A'))[:50]}...")
print(f" Output: {str(triple.get('output', 'N/A'))[:50]}...")
# νμ€ν¬ μμ± μμΈ
if 'task_generation' in result['steps']:
task_step = result['steps']['task_generation']
all_tasks = task_step.get('all_tasks', {})
print(f"\nπ― Generated Tasks:")
for task_type, tasks in all_tasks.items():
print(f" {task_type.title()} Tasks ({len(tasks)}):")
for i, task in enumerate(tasks[:2]): # μ²μ 2κ°λ§ νμ
prompt = task.get('prompt', '')
print(f" [{i+1}] {prompt[:80]}...")
# 보μ λΆν¬ μμΈ
if 'reward_computation' in result['steps']:
reward_step = result['steps']['reward_computation']
rewards = reward_step.get('rewards', {})
distribution = rewards.get('reward_distribution', {})
print(f"\nπ Reward Distribution:")
for task_type, avg_reward in distribution.items():
print(f" {task_type.title()}: {avg_reward:.3f}")
print("\n" + "="*60)
print("π PIPELINE TEST COMPLETED SUCCESSFULLY")
print("="*60)
# μμΈ κ²°κ³Ό νμΌ μ μ₯
if result['success']:
print(f"\nπ μμΈ κ²°κ³Ό νμΌ μ μ₯ μ€...")
save_detailed_results(result, args, args.output_dir)
return result['success']
except Exception as e:
logger.log_error(f"π₯ Pipeline test failed: {e}")
import traceback
traceback.print_exc()
return False
finally:
# GPU λ©λͺ¨λ¦¬ μ 리
if torch.cuda.is_available():
torch.cuda.empty_cache()
logger.log_info("π§Ή Cleaned up resources")
if __name__ == '__main__':
success = main()
exit_code = 0 if success else 1
print(f"\nπͺ Exiting with code {exit_code}")
sys.exit(exit_code) |