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 |