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)