File size: 38,572 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
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
"""
Initial Solution Generator

AZR ๊ธฐ๋ฐ˜ TestTime RLVR์„ ์œ„ํ•œ ์ดˆ๊ธฐ ์†”๋ฃจ์…˜ ์ƒ์„ฑ๊ธฐ
๊ธฐ์กด Test-Time-RLVR์˜ generate_initial_solution ํ•จ์ˆ˜๋ฅผ ํด๋ž˜์Šคํ™”ํ•˜์—ฌ ํ™•์žฅ
"""

import re
import torch
from typing import Dict, Any, Optional, Tuple, List
from transformers import AutoTokenizer, AutoModelForCausalLM

from .config import TestTimeConfig
from .logger import TestTimeLogger
from .prompts import get_prompt, get_temperature, get_diversity_instruction

# AZR์—์„œ ์‚ฌ์šฉํ•˜๋Š” ์ฝ”๋“œ ์ถ”์ถœ ํ•จ์ˆ˜ ์ง์ ‘ ์ž„ํฌํŠธ
from ..rewards.custom_evaluate import extract_code

# VLLM ์ตœ์ ํ™” ์ง€์›
try:
    from vllm import LLM, SamplingParams
    VLLM_AVAILABLE = True
except ImportError:
    VLLM_AVAILABLE = False


class InitialSolutionGenerator:
    """๋ฒค์น˜๋งˆํฌ ๋ฌธ์ œ์— ๋Œ€ํ•œ ์ดˆ๊ธฐ ์†”๋ฃจ์…˜ ์ƒ์„ฑ"""
    
    def __init__(self, model, tokenizer, config: TestTimeConfig, 
                 logger: Optional[TestTimeLogger] = None, use_vllm: bool = True):
        self.model = model
        self.tokenizer = tokenizer
        self.config = config
        self.logger = logger or TestTimeLogger()
        self.use_vllm = use_vllm and VLLM_AVAILABLE
        
        # VLLM ์‚ฌ์šฉ ๊ฐ€๋Šฅ ์—ฌ๋ถ€ ํ™•์ธ ๋ฐ ๋กœ๊น…
        if use_vllm and not VLLM_AVAILABLE:
            self.logger.log_info("โš ๏ธ  VLLM requested but not available, falling back to HuggingFace")
        elif self.use_vllm:
            self.logger.log_info("๐Ÿš€ Using VLLM for optimized inference")
        else:
            self.logger.log_info("๐Ÿ”ง Using HuggingFace Transformers for inference")
        
    def generate(self, problem: Dict[str, Any]) -> str:
        """๋ฌธ์ œ์— ๋Œ€ํ•œ ์ดˆ๊ธฐ ์†”๋ฃจ์…˜ ์ƒ์„ฑ (AZR ์ฝ”๋“œ ํ‰๊ฐ€ ํ”„๋กฌํ”„ํŠธ ์‚ฌ์šฉ)"""
        
        problem_prompt = problem['prompt']
        problem_id = problem.get('task_id', 'unknown')
        
        # AZR ์ฝ”๋“œ ํ‰๊ฐ€์—์„œ ์‚ฌ์šฉํ•˜๋Š” ํ”„๋กฌํ”„ํŠธ ํฌ๋งท ์ ์šฉ
        # prompt = f"Please provide a self-contained Python script that solves the following problem in a markdown code block:\n\n{problem_prompt}"
        
        # ์ค‘์•™ ํ”„๋กฌํ”„ํŠธ ์‹œ์Šคํ…œ ์‚ฌ์šฉ
        if 'HumanEval' in problem_id:
            # entry_point ํ•จ์ˆ˜๋ช… ์ฐพ๊ธฐ
            entry_point = problem.get('entry_point', 'unknown')
            
            # ํ”„๋กฌํ”„ํŠธ์—์„œ ํ•จ์ˆ˜๊ฐ€ ์—ฌ๋Ÿฌ ๊ฐœ ์žˆ๋Š”์ง€ ํ™•์ธ
            import re
            function_count = len(re.findall(r'^\s*def\s+\w+', problem_prompt, re.MULTILINE))
            
            if function_count > 1:
                # ๋‹ค์ค‘ ํ•จ์ˆ˜ ํ”„๋กฌํ”„ํŠธ ์‚ฌ์šฉ
                prompt = get_prompt("solution_humaneval_multi", 
                                  problem_prompt=problem_prompt, 
                                  entry_point=entry_point)
            else:
                # ๋‹จ์ผ ํ•จ์ˆ˜ ํ”„๋กฌํ”„ํŠธ ์‚ฌ์šฉ
                prompt = get_prompt("solution_humaneval_basic", 
                                  problem_prompt=problem_prompt)
        else:
            # MBPP ํ”„๋กฌํ”„ํŠธ ์‚ฌ์šฉ
            prompt = get_prompt("solution_mbpp_basic", 
                              problem_prompt=problem_prompt)
        
        self.logger.log_info(f"๐Ÿ” Generating initial solution for {problem_id}")
        self.logger.log_info(f"๐Ÿ“‹ Full prompt: {prompt}")
        
        # VLLM ๋˜๋Š” HuggingFace ๋ฐฑ์—”๋“œ ์„ ํƒ
        if self.use_vllm and isinstance(self.model, LLM):
            solution = self._generate_with_vllm(prompt)
        else:
            solution = self._generate_with_huggingface(prompt)
        
        # ๋งˆํฌ๋‹ค์šด ์ฝ”๋“œ ๋ธ”๋ก์—์„œ Python ์ฝ”๋“œ ์ถ”์ถœ (๊ฐœ์„ ๋œ ๋ฐฉ์‹)
        extracted_solution = self._extract_python_code(solution)
        
        # ์ฝ”๋“œ ์ถ”์ถœ ๊ฒฐ๊ณผ ๋กœ๊น…
        if extracted_solution and extracted_solution != solution:
            self.logger.log_info(f"๐Ÿ” Extracted Python code from markdown block")
            solution = extracted_solution
        elif not extracted_solution:
            self.logger.log_info(f"๐Ÿ” No markdown code block found, using original text")
        
        # HumanEval์˜ ๊ฒฝ์šฐ ํ”„๋กฌํ”„ํŠธ์—์„œ import ์ถ”์ถœํ•˜์—ฌ ์ถ”๊ฐ€ (EvalPlus ๋ฐฉ์‹)
        if 'HumanEval' in problem_id:
            solution = self._add_imports_from_prompt(solution, problem_prompt)
        
        # ํ•จ์ˆ˜ ์ •์˜ ๋ณต๊ตฌ (AZR ๋กœ์ง ๊ทธ๋Œ€๋กœ)
        solution = self._fix_function_definition(solution, prompt, problem_id)
        
        self.logger.log_info(f"โœ… Generated solution ({len(solution)} chars)")
        self.logger.log_info(f"๐Ÿ” Solution preview: {solution[:200]}...")
        
        # ๋””๋ฒ„๊น…: ์‹ค์ œ ์†”๋ฃจ์…˜ ๋‚ด์šฉ ๋กœ๊น…
        self.logger.log_info(f"๐Ÿ” Full solution for debugging:")
        self.logger.log_info(f"--- START SOLUTION ---")
        self.logger.log_info(solution)
        self.logger.log_info(f"--- END SOLUTION ---")
        
        return solution
    
    def generate_diverse(self, problem: Dict[str, Any], temperature: float = 0.7, variation_id: int = 0) -> str:
        """๋‹ค์–‘ํ•œ ์†”๋ฃจ์…˜ ์ƒ์„ฑ (๋†’์€ temperature ์‚ฌ์šฉ)"""
        
        problem_prompt = problem['prompt']
        problem_id = problem.get('task_id', 'unknown')
        
        # ์ค‘์•™ ๊ด€๋ฆฌ ๋‹ค์–‘์„ฑ ํ”„๋กฌํ”„ํŠธ ์‹œ์Šคํ…œ ์‚ฌ์šฉ
        diversity_instruction = get_diversity_instruction(variation_id)
        
        # HumanEval์— ๋Œ€ํ•ด์„œ๋Š” ํ•จ์ˆ˜ ์™„์„ฑ ์š”์ฒญ (๋‹ค์–‘์„ฑ ๋ฒ„์ „)
        if 'HumanEval' in problem_id:
            entry_point = problem.get('entry_point', 'unknown')
            
            import re
            function_count = len(re.findall(r'^\s*def\s+\w+', problem_prompt, re.MULTILINE))
            
            if function_count > 1:
                prompt = get_prompt("diverse_humaneval_multi",
                                  diversity_instruction=diversity_instruction,
                                  problem_prompt=problem_prompt,
                                  entry_point=entry_point)
            else:
                prompt = get_prompt("diverse_humaneval_basic",
                                  diversity_instruction=diversity_instruction,
                                  problem_prompt=problem_prompt)
        else:
            # MBPP ๋‹ค์–‘์„ฑ ํ”„๋กฌํ”„ํŠธ ์‚ฌ์šฉ
            prompt = get_prompt("diverse_mbpp_basic",
                              diversity_instruction=diversity_instruction,
                              problem_prompt=problem_prompt)
        
        self.logger.log_info(f"๐ŸŽจ Generating diverse solution #{variation_id+1} for {problem_id}")
        
        # ๋‹ค์–‘์„ฑ ์ƒ์„ฑ ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ
        try:
            from vllm import LLM
            if isinstance(self.model, LLM):
                solution = self._generate_with_vllm_diverse(prompt, temperature)
            else:
                solution = self._generate_with_huggingface_diverse(prompt, temperature)
        except ImportError:
            solution = self._generate_with_huggingface_diverse(prompt, temperature)
        
        # ์ฝ”๋“œ ์ถ”์ถœ ๋ฐ ํ›„์ฒ˜๋ฆฌ (๊ธฐ์กด๊ณผ ๋™์ผ)
        extracted_solution = self._extract_python_code(solution)
        if extracted_solution and extracted_solution != solution:
            self.logger.log_info(f"๐Ÿ” Extracted Python code from markdown block")
            solution = extracted_solution
        
        if 'HumanEval' in problem_id:
            solution = self._add_imports_from_prompt(solution, problem_prompt)
        
        solution = self._fix_function_definition(solution, prompt, problem_id)
        
        self.logger.log_info(f"โœ… Generated diverse solution #{variation_id+1} ({len(solution)} chars)")
        
        return solution
    
    def _generate_with_vllm(self, prompt: str) -> str:
        """VLLM ๋ฐฑ์—”๋“œ๋กœ ์ƒ์„ฑ (AZR ๋ฐฉ์‹)"""
        
        # AZR evaluation๊ณผ ๋™์ผํ•œ SamplingParams ์„ค์ •
        sampling_params = SamplingParams(
            temperature=0.05,       
            max_tokens=2048,       # AZR ํ‰๊ฐ€ ์„ค์ •
            top_p=1.0,             # greedy mode
            stop=["\n```\n"],      # ์ฝ”๋“œ ๋ธ”๋ก ์ข…๋ฃŒ ์‹œ ์ •์ง€
        )
        
        # VLLM ์ƒ์„ฑ
        outputs = self.model.generate([prompt], sampling_params, use_tqdm=False)
        solution = outputs[0].outputs[0].text.replace("\t", "    ")  # AZR ๋ฐฉ์‹ ํƒญ ์ฒ˜๋ฆฌ
        
        return solution.strip()
    
    def _generate_with_vllm_diverse(self, prompt: str, temperature: float = 0.7) -> str:
        """๋‹ค์–‘ํ•œ ์†”๋ฃจ์…˜ ์ƒ์„ฑ์šฉ VLLM ๋ฐฑ์—”๋“œ (๋†’์€ temperature)"""
        
        # ๋‹ค์–‘์„ฑ์„ ์œ„ํ•œ SamplingParams ์„ค์ •
        sampling_params = SamplingParams(
            temperature=temperature,   # ๋†’์€ temperature๋กœ ๋‹ค์–‘์„ฑ ํ™•๋ณด
            max_tokens=2048,
            top_p=0.95,               # ๋‹ค์–‘์„ฑ์„ ์œ„ํ•ด top_p ์‚ฌ์šฉ
            stop=["\n```\n"],         # ์ฝ”๋“œ ๋ธ”๋ก ์ข…๋ฃŒ ์‹œ ์ •์ง€
        )
        
        # VLLM ์ƒ์„ฑ
        outputs = self.model.generate([prompt], sampling_params, use_tqdm=False)
        solution = outputs[0].outputs[0].text.replace("\t", "    ")
        
        return solution.strip()
    
    def generate_batch(self, prompts: List[str], temperature: float = 0.7) -> List[str]:
        """๋ฐฐ์น˜๋กœ ์—ฌ๋Ÿฌ ํ”„๋กฌํ”„ํŠธ ๋™์‹œ ์ฒ˜๋ฆฌ"""
        
        # ์‹ค์ œ ๋ชจ๋ธ ํƒ€์ž… ํ™•์ธ (VLLM ๋กœ๋”ฉ ์‹คํŒจ ์‹œ HuggingFace ๋ชจ๋ธ์ด ๋กœ๋“œ๋จ)
        if self.use_vllm and isinstance(self.model, LLM):
            raw_solutions = self._generate_batch_with_vllm(prompts, temperature)
        else:
            # HuggingFace๋Š” ์ˆœ์ฐจ ์ฒ˜๋ฆฌ (fallback)
            raw_solutions = [self._generate_with_huggingface(prompt) for prompt in prompts]
        
        # ๊ฐ ์†”๋ฃจ์…˜์— ๋Œ€ํ•ด ํ›„์ฒ˜๋ฆฌ ์ˆ˜ํ–‰
        processed_solutions = []
        for i, (prompt, solution) in enumerate(zip(prompts, raw_solutions)):
            # 1. ๋งˆํฌ๋‹ค์šด์—์„œ Python ์ฝ”๋“œ ์ถ”์ถœ
            extracted = self._extract_python_code(solution)
            if extracted and extracted != solution:
                self.logger.log_info(f"๐Ÿ” Extracted Python code from markdown block for batch item {i+1}")
                solution = extracted
            
            # 2. HumanEval ๋ฌธ์ œ์ธ ๊ฒฝ์šฐ import ์ถ”๊ฐ€
            # ํ”„๋กฌํ”„ํŠธ์—์„œ problem ID ์ถ”์ถœ (ํ”„๋กฌํ”„ํŠธ์— ํฌํ•จ๋˜์–ด ์žˆ๋‹ค๊ณ  ๊ฐ€์ •)
            if 'HumanEval' in prompt:
                # ํ”„๋กฌํ”„ํŠธ์—์„œ ์›๋ณธ problem prompt ์ถ”์ถœ ์‹œ๋„
                # ํ”„๋กฌํ”„ํŠธ ๊ตฌ์กฐ์— ๋”ฐ๋ผ ์กฐ์ • ํ•„์š”
                solution = self._add_imports_from_prompt(solution, prompt)
            
            # 3. ํ•จ์ˆ˜ ์ •์˜ ์ˆ˜์ • (ํ•„์š”ํ•œ ๊ฒฝ์šฐ)
            # generate_diverse์™€ ๋™์ผํ•œ ์ฒ˜๋ฆฌ
            solution = self._fix_function_definition(solution, prompt)
            
            processed_solutions.append(solution)
        
        return processed_solutions
    
    def _generate_batch_with_vllm(self, prompts: List[str], temperature: float = 0.7) -> List[str]:
        """VLLM์œผ๋กœ ๋ฐฐ์น˜ ์ฒ˜๋ฆฌ"""
        
        # VLLM ์ƒ˜ํ”Œ๋ง ํŒŒ๋ผ๋ฏธํ„ฐ
        # seed๋ฅผ ์ œ๊ฑฐํ•˜์—ฌ ๋งค๋ฒˆ ๋‹ค๋ฅธ ์‘๋‹ต ์ƒ์„ฑ
        sampling_params = SamplingParams(
            temperature=temperature,
            top_p=0.85,
            max_tokens=1024,
            stop=[]  # stop ํ† ํฐ ๋ช…์‹œ์ ์œผ๋กœ ๋น„์›€
        )
        
        # VLLM ๋ฐฐ์น˜ ์ƒ์„ฑ
        outputs = self.model.generate(prompts, sampling_params, use_tqdm=False)
        
        # ๊ฒฐ๊ณผ ์ถ”์ถœ
        solutions = []
        for i, output in enumerate(outputs):
            solution = output.outputs[0].text.replace("\t", "    ")
            # ๋””๋ฒ„๊น…: finish_reason ํ™•์ธ
            finish_reason = output.outputs[0].finish_reason
            if finish_reason != "stop" and i < 3:  # ์ฒ˜์Œ 3๊ฐœ๋งŒ ๋กœ๊น…
                self.logger.log_warning(f"Output {i} finish_reason: {finish_reason}, length: {len(solution)}")
            solutions.append(solution.strip())
        
        return solutions
    
    def _generate_with_huggingface(self, prompt: str) -> str:
        """HuggingFace ๋ฐฑ์—”๋“œ๋กœ ์ƒ์„ฑ (attention mask ์ˆ˜์ •)"""
        
        # ํ† ํฌ๋‚˜์ด์ € ์ฒ˜๋ฆฌ (attention mask ๊ฒฝ๊ณ  ์ˆ˜์ •)
        inputs = self.tokenizer(prompt, return_tensors='pt', truncation=True, max_length=4096)
        
        # attention mask ๋ช…์‹œ์ ์œผ๋กœ ์„ค์ •
        if 'attention_mask' not in inputs:
            inputs['attention_mask'] = torch.ones_like(inputs['input_ids'])
        
        # ๋””๋ฐ”์ด์Šค ์ด๋™ (AZR ๋ฐฉ์‹ ๊ทธ๋Œ€๋กœ)
        device = getattr(self.model, 'device', 'cuda' if torch.cuda.is_available() else 'cpu')
        if isinstance(device, str):
            inputs = {k: v.to(device) for k, v in inputs.items()}
        else:
            # ๋ชจ๋ธ์ด ์ด๋ฏธ ํŠน์ • ๋””๋ฐ”์ด์Šค์— ์žˆ๋Š” ๊ฒฝ์šฐ
            inputs = {k: v.to(next(self.model.parameters()).device) for k, v in inputs.items()}
        
        with torch.no_grad():
            # ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ (AZR ๋ฐฉ์‹ ๊ทธ๋Œ€๋กœ)
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
                
            # AZR evaluation๊ณผ ๋™์ผํ•œ greedy ์„ค์ •
            outputs = self.model.generate(
                inputs['input_ids'],
                attention_mask=inputs['attention_mask'],  # attention mask ๋ช…์‹œ์ ์œผ๋กœ ์ „๋‹ฌ
                max_new_tokens=2048,  # ์›๋ž˜ AZR ํ‰๊ฐ€ ์„ค์ •
                do_sample=False,      # greedy mode (--greedy์™€ ๋™์ผ)
                pad_token_id=self.tokenizer.eos_token_id
            )
        
        # ์†”๋ฃจ์…˜ ์ถ”์ถœ (AZR ๋ฐฉ์‹ ๊ทธ๋Œ€๋กœ)
        solution = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
        solution = solution[len(prompt):].strip()
        
        return solution
    
    def _generate_with_huggingface_diverse(self, prompt: str, temperature: float = 0.7) -> str:
        """๋‹ค์–‘ํ•œ ์†”๋ฃจ์…˜ ์ƒ์„ฑ์šฉ HuggingFace ๋ฐฑ์—”๋“œ (๋†’์€ temperature)"""
        
        # ํ† ํฌ๋‚˜์ด์ € ์ฒ˜๋ฆฌ
        inputs = self.tokenizer(prompt, return_tensors='pt', truncation=True, max_length=4096)
        
        # attention mask ๋ช…์‹œ์ ์œผ๋กœ ์„ค์ •
        if 'attention_mask' not in inputs:
            inputs['attention_mask'] = torch.ones_like(inputs['input_ids'])
        
        # ๋””๋ฐ”์ด์Šค ์ด๋™
        device = getattr(self.model, 'device', 'cuda' if torch.cuda.is_available() else 'cpu')
        if isinstance(device, str):
            inputs = {k: v.to(device) for k, v in inputs.items()}
        else:
            # ๋ชจ๋ธ์ด ์ด๋ฏธ ํŠน์ • ๋””๋ฐ”์ด์Šค์— ์žˆ๋Š” ๊ฒฝ์šฐ
            inputs = {k: v.to(next(self.model.parameters()).device) for k, v in inputs.items()}
        
        with torch.no_grad():
            # ๋ฉ”๋ชจ๋ฆฌ ์ •๋ฆฌ
            if torch.cuda.is_available():
                torch.cuda.empty_cache()
                
            # ๋‹ค์–‘์„ฑ์„ ์œ„ํ•œ sampling ์„ค์ •
            outputs = self.model.generate(
                inputs['input_ids'],
                attention_mask=inputs['attention_mask'],
                max_new_tokens=2048,
                do_sample=True,          # sampling ํ™œ์„ฑํ™”
                temperature=temperature,  # ๋†’์€ temperature
                top_p=0.95,             # ๋‹ค์–‘์„ฑ์„ ์œ„ํ•ด top_p ์‚ฌ์šฉ
                pad_token_id=self.tokenizer.eos_token_id,
                eos_token_id=self.tokenizer.eos_token_id
            )
        
        # ์†”๋ฃจ์…˜ ์ถ”์ถœ
        solution = self.tokenizer.decode(outputs[0], skip_special_tokens=True)
        solution = solution[len(prompt):].strip()
        
        return solution
    
    def _extract_python_code(self, solution: str) -> str:
        """๊ฐœ์„ ๋œ Python ์ฝ”๋“œ ์ถ”์ถœ (AZR ๋ฐฉ์‹ + ์ถ”๊ฐ€ ํŒจํ„ด)"""
        
        # 1. AZR์˜ extract_code ํ•จ์ˆ˜ ๋จผ์ € ์‹œ๋„
        try:
            extracted = extract_code(solution, language="python")
            if extracted:
                return extracted
        except:
            pass
        
        # 2. ๋‹ค์–‘ํ•œ ๋งˆํฌ๋‹ค์šด ํŒจํ„ด ์‹œ๋„
        patterns = [
            r'```python\n(.*?)```',           # ```python ... ```
            r'```\n(.*?)```',                 # ``` ... ```
            r'```py\n(.*?)```',              # ```py ... ```
            r'```Python\n(.*?)```',          # ```Python ... ```
            r'Here is.*?:\n\n```python\n(.*?)```',  # ์„ค๋ช… ํ…์ŠคํŠธ ํฌํ•จ
            r'Here is.*?:\n\n```\n(.*?)```',        # ์„ค๋ช… ํ…์ŠคํŠธ ํฌํ•จ
        ]
        
        for pattern in patterns:
            matches = re.findall(pattern, solution, re.DOTALL | re.IGNORECASE)
            if matches:
                return matches[-1].strip()
        
        # 3. def๋กœ ์‹œ์ž‘ํ•˜๋Š” ํ•จ์ˆ˜ ์ฐพ๊ธฐ
        lines = solution.split('\n')
        code_lines = []
        in_function = False
        
        for line in lines:
            if line.strip().startswith('def '):
                in_function = True
                code_lines.append(line)
            elif in_function and (line.startswith('    ') or line.strip() == ''):
                code_lines.append(line)
            elif in_function and line.strip() and not line.startswith('    '):
                # ํ•จ์ˆ˜ ์ •์˜ ๋
                break
        
        if code_lines:
            return '\n'.join(code_lines)
        
        # 4. ์›๋ณธ ๋ฐ˜ํ™˜
        return solution
    
    def _add_imports_from_prompt(self, solution: str, prompt: str) -> str:
        """HumanEval ํ”„๋กฌํ”„ํŠธ์—์„œ import ๋ฌธ์„ ์ถ”์ถœํ•˜์—ฌ ์†”๋ฃจ์…˜์— ์ถ”๊ฐ€ (EvalPlus ๋ฐฉ์‹)"""
        
        # ์ด๋ฏธ import๊ฐ€ ์žˆ์œผ๋ฉด ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜
        if 'from typing import' in solution or 'import typing' in solution:
            return solution
        
        # ํ”„๋กฌํ”„ํŠธ์—์„œ import ๋ฌธ ์ถ”์ถœ
        import_lines = []
        prompt_lines = prompt.split('\n')
        
        for line in prompt_lines:
            stripped = line.strip()
            # import ๋ฌธ ์ฐพ๊ธฐ
            if (stripped.startswith('from ') and 'import' in stripped) or stripped.startswith('import '):
                import_lines.append(line)
            # ํ•จ์ˆ˜ ์ •์˜๊ฐ€ ์‹œ์ž‘๋˜๋ฉด ์ค‘๋‹จ
            elif stripped.startswith('def '):
                break
        
        # import๊ฐ€ ์—†์œผ๋ฉด ์›๋ณธ ๋ฐ˜ํ™˜
        if not import_lines:
            return solution
        
        # import ์ถ”๊ฐ€
        self.logger.log_info(f"๐Ÿ”ง Adding imports from prompt: {import_lines}")
        
        # ์†”๋ฃจ์…˜์ด ์ด๋ฏธ import๋กœ ์‹œ์ž‘ํ•˜๋Š”์ง€ ํ™•์ธ
        solution_lines = solution.split('\n')
        first_non_empty_line = None
        for i, line in enumerate(solution_lines):
            if line.strip():
                first_non_empty_line = i
                break
        
        # import๋ฅผ ๋งจ ์•ž์— ์ถ”๊ฐ€
        if first_non_empty_line is not None:
            # ๊ธฐ์กด import ๋’ค์— ์ถ”๊ฐ€ํ•˜๊ฑฐ๋‚˜ ๋งจ ์•ž์— ์ถ”๊ฐ€
            imports_text = '\n'.join(import_lines) + '\n\n'
            
            # ์ฒซ ๋ฒˆ์งธ ๋น„์–ด์žˆ์ง€ ์•Š์€ ์ค„์ด import์ธ ๊ฒฝ์šฐ
            if solution_lines[first_non_empty_line].strip().startswith(('import ', 'from ')):
                # ๋งˆ์ง€๋ง‰ import ์ฐพ๊ธฐ
                last_import_idx = first_non_empty_line
                for i in range(first_non_empty_line, len(solution_lines)):
                    if solution_lines[i].strip() and not solution_lines[i].strip().startswith(('import ', 'from ')):
                        break
                    if solution_lines[i].strip().startswith(('import ', 'from ')):
                        last_import_idx = i
                
                # ๋งˆ์ง€๋ง‰ import ๋‹ค์Œ์— ์ถ”๊ฐ€
                solution_lines.insert(last_import_idx + 1, '')
                solution_lines.insert(last_import_idx + 1, '\n'.join(import_lines))
                return '\n'.join(solution_lines)
            else:
                # ๋งจ ์•ž์— ์ถ”๊ฐ€
                return imports_text + solution
        
        return imports_text + solution
    
    def _fix_function_definition(self, solution: str, prompt: str, problem_id: str = "") -> str:
        """ํ•จ์ˆ˜ ์ •์˜๊ฐ€ ๋ˆ„๋ฝ๋œ ๊ฒฝ์šฐ ๋ณต๊ตฌ + lpw ์Šคํƒ€์ผ ์ค‘๋ณต ์ฒ˜๋ฆฌ"""
        
        # lpw ์Šคํƒ€์ผ: ํ”„๋กฌํ”„ํŠธ์—์„œ ํ•จ์ˆ˜ ์ด๋ฆ„ ์ถ”์ถœ
        func_def_match = re.search(r'def\s+(\w+)\([^)]*\)(?:\s*->\s*[^:]+)?:', prompt)
        if not func_def_match:
            return solution
            
        entry_point = func_def_match.group(1)
        func_def_line = func_def_match.group(0)
        
        # HumanEval์˜ ๊ฒฝ์šฐ ์ „์ฒด ์ฝ”๋“œ๋ฅผ ๋ฐ˜ํ™˜ํ•˜๋ฏ€๋กœ ์ค‘๋ณต ์ฒ˜๋ฆฌ ๋ถˆํ•„์š”
        if 'HumanEval' in problem_id:
            # ์ด๋ฏธ ์ „์ฒด ์ฝ”๋“œ๊ฐ€ ์žˆ์œผ๋ฏ€๋กœ ๊ทธ๋Œ€๋กœ ๋ฐ˜ํ™˜
            return solution
        
        # MBPP์˜ ๊ฒฝ์šฐ ๊ธฐ์กด ๋กœ์ง ์œ ์ง€
        # Case 1: LLM์ด ์ „์ฒด ํ•จ์ˆ˜๋ฅผ ์ƒ์„ฑํ•œ ๊ฒฝ์šฐ (lpw ์Šคํƒ€์ผ ์ฒดํฌ)
        if (prompt in solution) or (f'def {entry_point}(' in solution):
            # ํ•จ์ˆ˜๊ฐ€ ์ด๋ฏธ ํฌํ•จ๋˜์–ด ์žˆ์Œ
            self.logger.log_info(f"โœ… Function definition already present for {entry_point}")
            return solution
        
        # Case 2: ํ•จ์ˆ˜ ๋ณธ๋ฌธ๋งŒ ์ƒ์„ฑํ•œ ๊ฒฝ์šฐ - ํ•จ์ˆ˜ ์ •์˜ ์ถ”๊ฐ€
        if solution and not solution.startswith('def '):
            # ํ•จ์ˆ˜ ์ •์˜์™€ ํ•จ์ˆ˜ ๋‚ด์šฉ์„ ๊ฒฐํ•ฉ
            lines = solution.split('\n')
            fixed_lines = [func_def_line]
            
            for line in lines:
                if line.strip():  # ๋นˆ ์ค„์ด ์•„๋‹Œ ๊ฒฝ์šฐ
                    # if __name__ == "__main__": ๋ถ€๋ถ„์€ ํ•จ์ˆ˜ ๋ฐ–์— ์žˆ์–ด์•ผ ํ•จ
                    if line.strip().startswith('if __name__'):
                        # ํ•จ์ˆ˜ ์ •์˜ ๋๋‚ด๊ณ  ๋ฉ”์ธ ๋ถ€๋ถ„ ์‹œ์ž‘
                        fixed_lines.append('')  # ๋นˆ ์ค„ ์ถ”๊ฐ€
                        fixed_lines.append(line.strip())
                    else:
                        # ํ•จ์ˆ˜ ๋‚ด์šฉ์€ 4์นธ ์ธ๋ดํ…Œ์ด์…˜
                        if not line.startswith('    ') and line.strip():
                            line = '    ' + line.lstrip()
                        fixed_lines.append(line)
                else:
                    fixed_lines.append(line)
            
            solution = '\n'.join(fixed_lines)
            self.logger.log_info(f"๐Ÿ”ง Fixed function definition for {entry_point}")
        
        return solution
    
    def generate_fallback_solution(self, problem: Dict[str, Any]) -> str:
        """๋ฌธ์ œ ์ƒ์„ฑ ์‹คํŒจ ์‹œ ๋Œ€์ฒด ์†”๋ฃจ์…˜ ์ƒ์„ฑ"""
        
        entry_point = problem.get('entry_point', 'solution')
        problem_description = problem.get('prompt', '')
        
        # ๋ฌธ์ œ ์œ ํ˜•๋ณ„ ๊ธฐ๋ณธ ํ…œํ”Œ๋ฆฟ (๊ธฐ์กด ๋ฐฉ์‹)
        if 'similar_elements' in problem_description:
            # similar_elements ๋ฌธ์ œ (Mbpp/2)
            solution = f"""def {entry_point}(test_tup1, test_tup2):
    return tuple(set(test_tup1) & set(test_tup2))"""
        elif 'kth_element' in problem_description:
            # kth_element ๋ฌธ์ œ
            solution = f"""def {entry_point}(arr, k):
    return sorted(arr)[k-1]"""
        else:
            # ์ผ๋ฐ˜ ํ…œํ”Œ๋ฆฟ
            solution = f"""def {entry_point}(*args):
    # TODO: Implement this function
    return None"""
        
        self.logger.log_info(f"๐Ÿ”„ Generated fallback solution for {entry_point}")
        return solution
    
    def validate_syntax(self, solution: str) -> Tuple[bool, Optional[str]]:
        """์†”๋ฃจ์…˜ ๊ตฌ๋ฌธ ๊ฒ€์ฆ"""
        try:
            compile(solution, '<string>', 'exec')
            return True, None
        except SyntaxError as e:
            return False, str(e)
        except Exception as e:
            return False, str(e)
    
    def extract_function_signature(self, prompt: str) -> Optional[Dict[str, str]]:
        """ํ”„๋กฌํ”„ํŠธ์—์„œ ํ•จ์ˆ˜ ์‹œ๊ทธ๋‹ˆ์ฒ˜ ์ถ”์ถœ"""
        
        # def function_name(args) -> return_type: ํŒจํ„ด ๋งค์นญ
        pattern = r'def\s+(\w+)\(([^)]*)\)(?:\s*->\s*([^:]+))?:'
        match = re.search(pattern, prompt)
        
        if match:
            func_name = match.group(1)
            args = match.group(2)
            return_type = match.group(3)
            
            return {
                'name': func_name,
                'args': args.strip(),
                'return_type': return_type.strip() if return_type else None,
                'full_signature': match.group(0)
            }
        
        return None
    
    def format_solution(self, raw_solution: str, problem: Dict[str, Any]) -> str:
        """์†”๋ฃจ์…˜ ํ˜•์‹ ์ •๋ฆฌ"""
        
        # ๊ธฐ๋ณธ ์ •๋ฆฌ
        solution = raw_solution.strip()
        
        # ํ•จ์ˆ˜ ์ •์˜ ํ™•์ธ ๋ฐ ์ˆ˜์ •
        if not solution.startswith('def '):
            signature = self.extract_function_signature(problem.get('prompt', ''))
            if signature:
                # ํ•จ์ˆ˜ ์ •์˜ ์ถ”๊ฐ€
                lines = solution.split('\n')
                indented_lines = ['    ' + line if line.strip() else line for line in lines]
                solution = signature['full_signature'] + '\n' + '\n'.join(indented_lines)
        
        # ๋ถˆํ•„์š”ํ•œ ์„ค๋ช… ํ…์ŠคํŠธ ์ œ๊ฑฐ
        lines = solution.split('\n')
        code_lines = []
        in_function = False
        
        for line in lines:
            if line.strip().startswith('def '):
                in_function = True
                code_lines.append(line)
            elif in_function:
                code_lines.append(line)
            elif line.strip() and not any(keyword in line.lower() for keyword in 
                                        ['explanation', 'here', 'this function', 'the solution']):
                code_lines.append(line)
        
        return '\n'.join(code_lines).strip()
    
    @staticmethod
    def extract_docstring_from_function(code: str) -> str:
        """ํ•จ์ˆ˜ ์ฝ”๋“œ์—์„œ docstring์„ ์ถ”์ถœ"""
        import re
        
        # ํ•จ์ˆ˜ ์ •์˜ ๋‹ค์Œ์— ์˜ค๋Š” docstring ํŒจํ„ด ๋งค์นญ
        # """...""" ๋˜๋Š” '''...''' ํ˜•ํƒœ
        docstring_patterns = [
            r'def\s+\w+\([^)]*\):\s*\n\s*"""(.*?)"""',  # """..."""
            r'def\s+\w+\([^)]*\):\s*\n\s*\'\'\'(.*?)\'\'\'',  # '''...'''
        ]
        
        for pattern in docstring_patterns:
            match = re.search(pattern, code, re.DOTALL)
            if match:
                docstring = match.group(1).strip()
                # ์—ฌ๋Ÿฌ ์ค„์ธ ๊ฒฝ์šฐ ๊น”๋”ํ•˜๊ฒŒ ์ •๋ฆฌ
                lines = docstring.split('\n')
                cleaned_lines = []
                for line in lines:
                    cleaned_line = line.strip()
                    if cleaned_line:
                        cleaned_lines.append(cleaned_line)
                
                return ' '.join(cleaned_lines)
        
        # docstring์ด ์—†๋Š” ๊ฒฝ์šฐ ๊ธฐ๋ณธ ๋ฉ”์‹œ์ง€ ๋ฐ˜ํ™˜
        return "Find the function that produces these outputs from these inputs."

    def _extract_function_code(self, code: str) -> str:
        """์ฝ”๋“œ์—์„œ ํ•จ์ˆ˜ ์ •์˜์™€ ํ•„์š”ํ•œ import ์ถ”์ถœ"""
        import re
        
        lines = code.strip().split('\n')
        import_lines = []
        func_lines = []
        in_function = False
        indent_level = 0
        
        # 1. import ๋ฌธ ์ˆ˜์ง‘
        for line in lines:
            stripped = line.strip()
            if (stripped.startswith('import ') or stripped.startswith('from ')) and not stripped.startswith('#'):
                import_lines.append(line)
        
        # 2. ํ•จ์ˆ˜ ์ •์˜ ์ฐพ๊ธฐ
        for line in lines:
            if line.strip().startswith('def '):
                in_function = True
                func_lines = [line]
                # ์ฒซ ์ค„์˜ ๋“ค์—ฌ์“ฐ๊ธฐ ๋ ˆ๋ฒจ ์ €์žฅ
                indent_level = len(line) - len(line.lstrip())
            elif in_function:
                # ๋นˆ ์ค„์ด๊ฑฐ๋‚˜ ๊ฐ™์€/๋” ๊นŠ์€ ๋“ค์—ฌ์“ฐ๊ธฐ๋ฉด ํ•จ์ˆ˜์˜ ์ผ๋ถ€
                if not line.strip() or (line.strip() and len(line) - len(line.lstrip()) > indent_level):
                    func_lines.append(line)
                else:
                    # ํ•จ์ˆ˜ ๋
                    break
        
        # 3. import + function ๊ฒฐํ•ฉ
        if func_lines:
            result_lines = import_lines + [''] + func_lines if import_lines else func_lines
            return '\n'.join(result_lines)
        else:
            return code
    
    def evaluate_solution(self, problem: Dict[str, Any], solution: str) -> Dict[str, Any]:
        """LLM ์†”๋ฃจ์…˜์„ ๋ฒค์น˜๋งˆํฌ ํ…Œ์ŠคํŠธ๋กœ ํ‰๊ฐ€ (EvalPlus ํ•„์ˆ˜)"""
        try:
            # EvalPlus ํ•จ์ˆ˜๋“ค ์ž„ํฌํŠธ (pip์œผ๋กœ ์„ค์น˜๋œ ๋ฒ„์ „ ์‚ฌ์šฉ)
            self.logger.log_info("๐Ÿ”„ Attempting to import EvalPlus...")
            from evalplus.evaluate import check_correctness
            from evalplus.gen.util import trusted_exec
            from evalplus.eval._special_oracle import MBPP_OUTPUT_NOT_NONE_TASKS
            from evalplus.eval import PASS
            self.logger.log_info("โœ… Using EvalPlus for evaluation")
        except ImportError as e:
            # EvalPlus๊ฐ€ ์—†์œผ๋ฉด ์˜ค๋ฅ˜๋กœ ์ฒ˜๋ฆฌ (fallback ์ œ๊ฑฐ)
            self.logger.log_error(f"โŒ EvalPlus is required but not available: {e}")
            import traceback
            self.logger.log_error(f"๐Ÿ“‹ Import traceback: {traceback.format_exc()}")
            return {
                'correct': False,
                'passed_tests': 0,
                'total_tests': 0,
                'error': f"EvalPlus import failed: {e}. Please install EvalPlus properly.",
                'execution_results': [],
                'base_passed': 0,
                'plus_passed': 0,
                'base_total': 0,
                'plus_total': 0
            }
        except Exception as e:
            self.logger.log_error(f"โŒ EvalPlus import failed with unexpected error: {e}")
            return {
                'correct': False,
                'passed_tests': 0,
                'total_tests': 0,
                'error': f"EvalPlus import error: {e}",
                'execution_results': [],
                'base_passed': 0,
                'plus_passed': 0,
                'base_total': 0,
                'plus_total': 0
            }
        
        result = {
            'correct': False,
            'passed_tests': 0,
            'total_tests': 0,
            'error': None,
            'execution_results': [],
            'base_passed': 0,
            'plus_passed': 0,
            'base_total': 0,
            'plus_total': 0
        }
        
        try:
            # 1. ํ•จ์ˆ˜ ์ •์˜ ์ถ”์ถœ
            extracted_code = self._extract_function_code(solution)
            if not extracted_code:
                result['error'] = "No function definition found"
                return result
            
            # 2. ๋ฐ์ดํ„ฐ์…‹ ํƒ€์ž… ๊ฒฐ์ •
            task_id = problem.get('task_id', '')
            if task_id.startswith('Mbpp'):
                dataset = 'mbpp'
            elif task_id.startswith('HumanEval'):
                dataset = 'humaneval'
            else:
                # ๊ธฐ๋ณธ๊ฐ’
                dataset = 'mbpp'
            
            # 3. expected outputs ์ƒ์„ฑ (canonical solution ์‚ฌ์šฉ)
            entry_point = problem.get('entry_point', '')
            canonical_solution = problem.get('canonical_solution', '')
            
            if not canonical_solution:
                result['error'] = "No canonical_solution found"
                return result
            
            # Expected outputs ๊ณ„์‚ฐ
            expected_output = {}
            
            # Base tests
            base_inputs = problem.get('base_input', [])
            if base_inputs:
                expected_output['base'], expected_output['base_time'] = trusted_exec(
                    problem.get('prompt', '') + canonical_solution,
                    base_inputs,
                    entry_point,
                    record_time=True,
                    output_not_none=entry_point in MBPP_OUTPUT_NOT_NONE_TASKS
                )
            
            # Plus tests  
            plus_inputs = problem.get('plus_input', [])
            if plus_inputs:
                expected_output['plus'], expected_output['plus_time'] = trusted_exec(
                    problem.get('prompt', '') + canonical_solution,
                    plus_inputs,
                    entry_point,
                    record_time=True,
                    output_not_none=entry_point in MBPP_OUTPUT_NOT_NONE_TASKS
                )
            
            # 4. EvalPlus check_correctness ํ˜ธ์ถœ
            evalplus_result = check_correctness(
                dataset=dataset,
                completion_id=0,
                problem=problem,
                solution=extracted_code,
                expected_output=expected_output,
                base_only=False,  # Plus tests๋„ ์‹คํ–‰
                fast_check=False,  # ๋ชจ๋“  ํ…Œ์ŠคํŠธ ์‹คํ–‰
                identifier=task_id
            )
            
            # 5. ๊ฒฐ๊ณผ ํŒŒ์‹ฑ
            if 'base' in evalplus_result:
                base_stat, base_details = evalplus_result['base']
                result['base_total'] = len(base_inputs)
                if base_stat == PASS:
                    result['base_passed'] = result['base_total']
                else:
                    result['base_passed'] = sum(1 for d in base_details if d) if base_details else 0
                
                result['passed_tests'] += result['base_passed']
                result['total_tests'] += result['base_total']
            
            if 'plus' in evalplus_result:
                plus_stat, plus_details = evalplus_result['plus']
                result['plus_total'] = len(plus_inputs)
                if plus_stat == PASS:
                    result['plus_passed'] = result['plus_total']
                else:
                    result['plus_passed'] = sum(1 for d in plus_details if d) if plus_details else 0
                
                result['passed_tests'] += result['plus_passed']
                result['total_tests'] += result['plus_total']
            
            # EvalPlus ๊ธฐ์ค€: ๋ชจ๋“  ํ…Œ์ŠคํŠธ ํ†ต๊ณผํ•ด์•ผ correct
            result['correct'] = (result['passed_tests'] == result['total_tests']) and result['total_tests'] > 0
            
            # ์—๋Ÿฌ ๋ฉ”์‹œ์ง€ ์„ค์ •
            if not result['correct']:
                if base_stat != PASS:
                    result['error'] = f"Base tests failed: {base_stat}"
                elif 'plus' in evalplus_result and plus_stat != PASS:
                    result['error'] = f"Plus tests failed: {plus_stat}"
            
            # ๋กœ๊น…
            self.logger.log_info(f"EvalPlus evaluation for {task_id}:")
            self.logger.log_info(f"  Base: {result['base_passed']}/{result['base_total']}")
            self.logger.log_info(f"  Plus: {result['plus_passed']}/{result['plus_total']}")
            self.logger.log_info(f"  Total: {result['passed_tests']}/{result['total_tests']}")
            self.logger.log_info(f"  Correct: {result['correct']}")
            
        except Exception as e:
            result['error'] = f"Evaluation failed: {str(e)}"
            import traceback
            self.logger.log_info(f"Evaluation traceback: {traceback.format_exc()}")
        
        return result
    

    @staticmethod
    def load_model_with_optimizations(model_name: str, device: str, 
                                    config: TestTimeConfig, use_vllm: bool = True, tensor_parallel_size: int = 1) -> Tuple[Any, Any]:
        """๋ชจ๋ธ๊ณผ ํ† ํฌ๋‚˜์ด์ € ๋กœ๋“œ (AZR ์Šคํƒ€์ผ ์ตœ์ ํ™”, VLLM ์ง€์›)"""
        
        # ํ† ํฌ๋‚˜์ด์ € ๋กœ๋“œ
        tokenizer = AutoTokenizer.from_pretrained(model_name, trust_remote_code=True)
        if tokenizer.pad_token is None:
            tokenizer.pad_token = tokenizer.eos_token
        
        # VLLM ์‚ฌ์šฉ ๊ฐ€๋Šฅ ์—ฌ๋ถ€ ํ™•์ธ ๋ฐ ๋ชจ๋ธ ๋กœ๋“œ
        if use_vllm and VLLM_AVAILABLE and device.startswith('cuda'):
            try:
                # GPU ๋””๋ฐ”์ด์Šค ์„ค์ • (์ด๋ฏธ ์„ค์ •๋œ CUDA_VISIBLE_DEVICES ์šฐ์„  ์‚ฌ์šฉ)
                import os
                if 'CUDA_VISIBLE_DEVICES' not in os.environ:
                    gpu_id = device.split(':')[1] if ':' in device else '0'
                    os.environ['CUDA_VISIBLE_DEVICES'] = gpu_id
                else:
                    # ์ด๋ฏธ ์„ค์ •๋œ CUDA_VISIBLE_DEVICES ์‚ฌ์šฉ
                    gpu_id = os.environ['CUDA_VISIBLE_DEVICES']
                    print(f"๐ŸŽฏ Using existing CUDA_VISIBLE_DEVICES: {gpu_id}")
                
                # VLLM ๋ชจ๋ธ ๋กœ๋“œ (Ray Actor ํ™˜๊ฒฝ์—์„œ ๋ฉ”๋ชจ๋ฆฌ ์ตœ์ ํ™”)
                model = LLM(
                    model=model_name,
                    dtype=str(config.torch_dtype).split('.')[-1],  # torch.float16 -> float16
                    trust_remote_code=True,
                    gpu_memory_utilization=config.gpu_memory_utilization,
                    max_model_len=getattr(config, 'max_model_len', 2048),  # ์ถฉ๋ถ„ํ•œ ๊ธธ์ด๋กœ ์ฆ๊ฐ€
                    tensor_parallel_size=tensor_parallel_size,  # GPU ๊ฐœ์ˆ˜์— ๋งž์ถค
                )
                print(f"โœ… VLLM model loaded successfully on GPU {gpu_id} (tensor_parallel_size={tensor_parallel_size})")
                return model, tokenizer
            except Exception as e:
                import traceback
                print(f"โš ๏ธ  VLLM loading failed: {e}")
                print(f"๐Ÿ” Full traceback: {traceback.format_exc()}")
                print(f"๐Ÿ”„ Falling back to HuggingFace")
        
        # HuggingFace ๋ชจ๋ธ ๋กœ๋“œ (๊ธฐ์กด ๋ฐฉ์‹)
        model = AutoModelForCausalLM.from_pretrained(
            model_name,
            torch_dtype=config.torch_dtype,
            device_map=device if device.startswith('cuda') else None,
            trust_remote_code=True,
            attn_implementation="flash_attention_2" if config.use_flash_attention and device.startswith('cuda') else None,
            use_cache=False,  # ํ•™์Šต์šฉ์œผ๋กœ ์บ์‹œ ๋น„ํ™œ์„ฑํ™”
        )
        
        # Gradient checkpointing ํ™œ์„ฑํ™”
        # Gradient checkpointing ๋น„ํ™œ์„ฑํ™” - ์ถ”๋ก  ์‹œ์—๋Š” ๋ถˆํ•„์š”ํ•˜๊ณ  ๊ฒฝ๊ณ ๋งŒ ๋ฐœ์ƒ
        # ํ•™์Šต์ด ํ•„์š”ํ•œ ๊ฒฝ์šฐ ๋ณ„๋„๋กœ ํ™œ์„ฑํ™”ํ•ด์•ผ ํ•จ
        if hasattr(model, 'gradient_checkpointing_disable'):
            model.gradient_checkpointing_disable()
        
        print(f"โœ… HuggingFace model loaded successfully")
        return model, tokenizer