File size: 26,279 Bytes
f50dc54 |
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 |
#!/usr/bin/env python3
"""
TTRLVR + AZR ํตํฉ ํ์ต ๋ฉ์ธ ์คํฌ๋ฆฝํธ (Unified Version)
UnifiedTTRLVRTrainer๋ฅผ ์ฌ์ฉํ์ฌ ํ๋์ VeRL ์ธ์
์์ ์ ์ฒด ํ์ต ์งํ:
1. VeRL worker ํ ๋ฒ๋ง ์ด๊ธฐํ
2. ๊ฐ ๋ผ์ด๋๋ง๋ค ๊ฐ์ vLLM์ผ๋ก Phase 1-4 ์คํ
3. ๊ฐ์ vLLM์ผ๋ก Phase 5 PPO ํ์ต
4. ๋๊ธฐํ ๋ฌธ์ ์์ ํด๊ฒฐ (dummy_dtensor ์ฌ์ฉ ๊ฐ๋ฅ)
์ฌ์ฉ ์์:
# ์ผ๋ฐ ํ์ต
python train_ttrlvr_azr_unified.py --benchmark mbpp --problems 10 --rounds 30
python train_ttrlvr_azr_unified.py --benchmark humaneval --problems 5 --rounds 10
python train_ttrlvr_azr_unified.py --benchmark mbpp --problem-id Mbpp/2 --rounds 5
# GPU ์ง์
python train_ttrlvr_azr_unified.py --benchmark mbpp --problems 10 --rounds 30 --gpu 0,1,2,3
"""
import os
import sys
import argparse
import json
from datetime import datetime
from pathlib import Path
from typing import List
import warnings
import ray
import torch
# Gradient checkpointing ๊ด๋ จ ๊ฒฝ๊ณ ํํฐ๋ง
warnings.filterwarnings("ignore", message=".*Caching is incompatible with gradient checkpointing.*")
# ๊ฒฝ๋ก ์ค์ - ์๋ ๊ฒฝ๋ก ์ฌ์ฉ
project_root = Path(__file__).parent.parent # TestTime-RLVR-v2 ๋๋ ํ ๋ฆฌ
sys.path.append(str(project_root))
# verl๊ณผ Absolute-Zero-Reasoner๋ ์์ ๋๋ ํ ๋ฆฌ์์ ์ฐพ๊ธฐ
parent_dir = project_root.parent
for lib_name in ['verl', 'Absolute-Zero-Reasoner']:
lib_path = parent_dir / lib_name
if lib_path.exists():
sys.path.append(str(lib_path))
# pip๋ก ์ค์น๋ ๊ฒฝ์ฐ๋ ์๋์ผ๋ก import ๋จ
# AZR/VeRL ๋ชจ๋ ์ํฌํธ (main_azr_ppo.py์ ๋์ผํ ๊ตฌ์กฐ)
from verl import DataProto
from omegaconf import OmegaConf
import ray
from verl.utils import hf_tokenizer
from verl.trainer.ppo.ray_trainer import ResourcePoolManager, Role
from verl.single_controller.ray import RayWorkerGroup
from verl.workers.fsdp_workers import ActorRolloutRefWorker, AsyncActorRolloutRefWorker, CriticWorker
from absolute_zero_reasoner.utils.logging_utils.stdout import PrettyPrinter
# TTRLVR ๋ชจ๋ ์ํฌํธ
from absolute_zero_reasoner.testtime.config import TestTimeConfig, BenchmarkConfig
from absolute_zero_reasoner.testtime.logger import TestTimeLogger
# Ray ์ ๋ฆฌ ๋ณ์
_trainer_instance = None
_logger_instance = None
def cleanup_ray():
"""Ray ํด๋ฌ์คํฐ ์ ๋ฆฌ ํจ์"""
global _trainer_instance, _logger_instance
try:
if _logger_instance:
_logger_instance.log_info("๐ ๊ฐ์ ์ข
๋ฃ ๊ฐ์ง: Ray ํด๋ฌ์คํฐ ์ ๋ฆฌ ์ค...")
except:
print("๐ ๊ฐ์ ์ข
๋ฃ ๊ฐ์ง: Ray ํด๋ฌ์คํฐ ์ ๋ฆฌ ์ค...")
try:
# IterativeTrainer ์ ๋ฆฌ
if _trainer_instance:
_trainer_instance.cleanup_ray()
except Exception as e:
try:
if _logger_instance:
_logger_instance.log_error(f"IterativeTrainer ์ ๋ฆฌ ์คํจ: {e}")
except:
print(f"IterativeTrainer ์ ๋ฆฌ ์คํจ: {e}")
try:
# ํ์ฌ ํ๋ก๊ทธ๋จ์ Ray๋ง ์ข
๋ฃ (์์ ํ ๋ฐฉ๋ฒ)
import ray
if ray.is_initialized():
ray.shutdown()
except Exception as e:
try:
if _logger_instance:
_logger_instance.log_error(f"Ray ์ข
๋ฃ ์คํจ: {e}")
except:
print(f"Ray ์ข
๋ฃ ์คํจ: {e}")
try:
if _logger_instance:
_logger_instance.log_info("โ
Ray ์ ๋ฆฌ ์๋ฃ")
except:
print("โ
Ray ์ ๋ฆฌ ์๋ฃ")
def signal_handler(signum, frame):
"""์๊ทธ๋ ํธ๋ค๋ฌ (Ctrl+C, ๊ฐ์ ์ข
๋ฃ ๋ฑ)"""
try:
if _logger_instance:
_logger_instance.log_info(f"๐ ์๊ทธ๋ {signum} ์์ : ํ๋ก๊ทธ๋จ ์ข
๋ฃ ์ค...")
except:
print(f"๐ ์๊ทธ๋ {signum} ์์ : ํ๋ก๊ทธ๋จ ์ข
๋ฃ ์ค...")
cleanup_ray()
sys.exit(1)
def parse_arguments():
"""๋ช
๋ นํ ์ธ์ ํ์ฑ"""
parser = argparse.ArgumentParser(
description='TTRLVR + AZR ํตํฉ ๋ฐ๋ณต ํ์ต',
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
์์:
# MBPP 10๋ฌธ์ ๋ก 30๋ผ์ด๋ ํ์ต
python train_ttrlvr_azr.py --benchmark mbpp --problems 10 --rounds 30
# HumanEval 5๋ฌธ์ ๋ก 10๋ผ์ด๋ ํ์ต
python train_ttrlvr_azr.py --benchmark humaneval --problems 5 --rounds 10
# 15๋ผ์ด๋๋ถํฐ ์ฌ๊ฐ
python train_ttrlvr_azr.py --benchmark mbpp --problems 10 --rounds 30 --resume 15
# ํน์ GPU ์ฌ์ฉ
python train_ttrlvr_azr.py --benchmark mbpp --problems 10 --rounds 30 --gpu 4
"""
)
parser.add_argument(
'--benchmark',
choices=['mbpp', 'humaneval'],
default='mbpp',
help='๋ฒค์น๋งํฌ ์ ํ (๊ธฐ๋ณธ๊ฐ: mbpp)'
)
parser.add_argument(
'--problems',
type=int,
default=10,
help='๋ฌธ์ ์ (๊ธฐ๋ณธ๊ฐ: 10)'
)
parser.add_argument(
'--problem-id',
type=str,
help='ํน์ ๋ฌธ์ ID (์: HumanEval/1, Mbpp/10)'
)
parser.add_argument(
'--rounds',
type=int,
default=30,
help='์ด ๋ผ์ด๋ ์ (๊ธฐ๋ณธ๊ฐ: 30)'
)
parser.add_argument(
'--resume',
type=int,
default=1,
help='์ฌ๊ฐํ ๋ผ์ด๋ ๋ฒํธ (๊ธฐ๋ณธ๊ฐ: 1)'
)
parser.add_argument(
'--gpu',
type=str,
default='5',
help='์ฌ์ฉํ GPU ๋ฒํธ (๋จ์ผ: 5, ๋ค์ค: 1,2,3,5)'
)
parser.add_argument(
'--output-dir',
type=str,
default='./results/ttrlvr_azr',
help='๊ฒฐ๊ณผ ์ ์ฅ ๋๋ ํ ๋ฆฌ (๊ธฐ๋ณธ๊ฐ: ./results/ttrlvr_azr)'
)
parser.add_argument(
'--config',
type=str,
help='์ค์ ํ์ผ ๊ฒฝ๋ก (์ ํ์ฌํญ)'
)
parser.add_argument(
'--model',
type=str,
default='Qwen/Qwen2.5-7B',
help='์ฌ์ฉํ ๋ชจ๋ธ (๊ธฐ๋ณธ๊ฐ: Qwen/Qwen2.5-7B)'
)
parser.add_argument(
'--debug',
action='store_true',
help='๋๋ฒ๊ทธ ๋ชจ๋ ํ์ฑํ'
)
parser.add_argument(
'--batch-size',
type=int,
default=24,
help='ํ์ต ๋ฐฐ์น ํฌ๊ธฐ (๊ธฐ๋ณธ๊ฐ: 24, OOM ์ ์ค์ด๊ธฐ)'
)
parser.add_argument(
'--batch-epochs',
type=int,
default=1,
help='๋ฐฐ์น๋น ์ํญ ์ (๊ธฐ๋ณธ๊ฐ: 1, ๋ ๋ง์ ํ์ต์ ์ํด ์ฆ๊ฐ ๊ฐ๋ฅ)'
)
parser.add_argument(
'--num-programs',
type=int,
default=4,
help='์์ฑํ ๋ค์ํ ํ๋ก๊ทธ๋จ ์ (๊ธฐ๋ณธ๊ฐ: 4, ๋ ๋ค์ํ ๋ฐ์ดํฐ๋ฅผ ์ํด ์ฆ๊ฐ ๊ฐ๋ฅ)'
)
parser.add_argument(
'--input-generation-rounds',
type=int,
default=3,
help='๋ค์ํ ์
๋ ฅ ์์ฑ ๋ผ์ด๋ ์ (๊ธฐ๋ณธ๊ฐ: 3, ๋ผ์ด๋๋น 5๊ฐ์ฉ ์์ฑ)'
)
parser.add_argument(
'--parallel-batch-size',
type=int,
default=4,
help='๋์ ์ฒ๋ฆฌํ ํ๋กฌํํธ ์ (๊ธฐ๋ณธ๊ฐ: 4, GPU ๋ฉ๋ชจ๋ฆฌ์ ๋ฐ๋ผ ์กฐ์ )'
)
parser.add_argument(
'--eval-rounds',
type=int,
default=5,
help='๋งค ๋ผ์ด๋ ์ ํ๋ ์ธก์ ํ์ (๊ธฐ๋ณธ๊ฐ: 5, ๋ ์ ํํ ํ๊ฐ๋ฅผ ์ํด ์ฆ๊ฐ ๊ฐ๋ฅ)'
)
parser.add_argument(
'--skip-task-eval',
action='store_true',
help='Task evaluation(4๋จ๊ณ) ์คํตํ์ฌ ๋น ๋ฅธ ํ
์คํธ (๋ฐ์ดํฐ ์์ฑ ํ ๋ฐ๋ก VeRL ํ์ต)'
)
parser.add_argument(
'--save-every-round',
action='store_true',
help='๋งค ๋ผ์ด๋๋ง๋ค ์ฒดํฌํฌ์ธํธ ์ ์ฅ (๊ธฐ๋ณธ๊ฐ: False)'
)
parser.add_argument(
'--save-round-interval',
type=int,
default=5,
help='์ฒดํฌํฌ์ธํธ ์ ์ฅ ๊ฐ๊ฒฉ (์: 5 = 5๋ผ์ด๋๋ง๋ค ์ ์ฅ, ๊ธฐ๋ณธ๊ฐ: 5)'
)
return parser.parse_args()
def setup_environment(gpu_id: str, batch_size: int = None):
"""ํ๊ฒฝ ๋ณ์ ์ค์ - run_ttrlvr_azr_training.sh์ ๋์ผํ๊ฒ"""
# GPU ์ค์ - ๋ช
๋ นํ ์ธ์๋ฅผ ์ฐ์ ์ฌ์ฉํ๊ณ , ์์ผ๋ฉด ๊ธฐ์กด ํ๊ฒฝ๋ณ์ ์ฌ์ฉ
if gpu_id:
os.environ['CUDA_VISIBLE_DEVICES'] = gpu_id
print(f"๐ฏ Using command line GPU setting: {gpu_id}")
elif 'CUDA_VISIBLE_DEVICES' in os.environ and os.environ['CUDA_VISIBLE_DEVICES']:
print(f"๐ฏ Using existing CUDA_VISIBLE_DEVICES: {os.environ['CUDA_VISIBLE_DEVICES']}")
else:
os.environ['CUDA_VISIBLE_DEVICES'] = '5' # ๊ธฐ๋ณธ๊ฐ
print(f"๐ฏ Using default GPU: 5")
# VLLM ์ค์ (run_ttrlvr_azr_training.sh์ ๋์ผ)
os.environ['VLLM_ATTENTION_BACKEND'] = 'FLASH_ATTN'
# Ray ์ค์ (run_ttrlvr_azr_training.sh์ ๋์ผ)
os.environ['RAY_memory_monitor_refresh_ms'] = '0'
os.environ['RAY_LOGGING_LEVEL'] = 'DEBUG'
# Hydra ์ค์
os.environ['HYDRA_FULL_ERROR'] = '1'
# Python ๊ฒฝ๋ก ์ค์ (verl ๊ฒฝ๋ก ์ถ๊ฐ) - ์๋ ๊ฒฝ๋ก ์ฌ์ฉ
pythonpath = os.environ.get('PYTHONPATH', '')
project_root = Path(__file__).parent.parent # TestTime-RLVR-v2 directory
# ํ๋ก์ ํธ ๊ฒฝ๋ก๋ค ์ค์
paths_to_add = [str(project_root)]
parent_dir = project_root.parent
# verl๊ณผ Absolute-Zero-Reasoner ๊ฒฝ๋ก ์ถ๊ฐ (์กด์ฌํ๋ ๊ฒฝ์ฐ)
if (parent_dir / 'verl').exists():
paths_to_add.append(str(parent_dir / 'verl'))
if (parent_dir / 'Absolute-Zero-Reasoner').exists():
paths_to_add.append(str(parent_dir / 'Absolute-Zero-Reasoner'))
# PYTHONPATH ์
๋ฐ์ดํธ
for path in paths_to_add:
if path not in pythonpath:
pythonpath = f"{path}:{pythonpath}" if pythonpath else path
os.environ['PYTHONPATH'] = pythonpath
# batch size ์ค์
if batch_size is not None:
os.environ['TRAIN_BATCH_SIZE'] = str(batch_size)
# ์ถ๊ฐ ํ๊ฒฝ ๋ณ์ ์ค์ (์์์ ์ค์ ํ์ง ์์ ๊ฒ๋ค๋ง)
# ๊ธฐ๋ณธ๊ฐ์ผ๋ก ํ ๋๋ ํ ๋ฆฌ ์ฌ์ฉ, ํ๊ฒฝ๋ณ์๋ก ์ค๋ฒ๋ผ์ด๋ ๊ฐ๋ฅ
os.environ.setdefault('HF_HOME', os.path.expanduser('~/.cache/huggingface'))
os.environ.setdefault('TRANSFORMERS_CACHE', os.path.expanduser('~/.cache/huggingface'))
os.environ['TOKENIZERS_PARALLELISM'] = 'false'
# PYTHONPATH ์ค์ - ์๋ ๊ฒฝ๋ก ์ฌ์ฉ
current_pythonpath = os.environ.get('PYTHONPATH', '')
project_root = Path(__file__).parent.parent # TestTime-RLVR-v2 directory
new_paths = [
str(project_root)
# site-packages๋ ์๋์ผ๋ก ํฌํจ๋๋ฏ๋ก ์ ๊ฑฐ
]
for path in new_paths:
if path not in current_pythonpath:
current_pythonpath = f"{path}:{current_pythonpath}" if current_pythonpath else path
os.environ['PYTHONPATH'] = current_pythonpath
def load_benchmark_problems(benchmark_config: BenchmarkConfig) -> List[str]:
"""๋ฒค์น๋งํฌ์์ ๋ฌธ์ ID ๋ชฉ๋ก ๋ก๋ (๊ธฐ์กด TTRLVR ๋ฐฉ์ ์ฌ์ฉ)"""
problems = []
if benchmark_config.name == 'mbpp':
# MBPP+ EvalPlus ํ์ค ๋ฐ์ดํฐ ๋ก๋ฉ
try:
from evalplus.data.mbpp import get_mbpp_plus
mbpp_problems = get_mbpp_plus() # ์๋์ผ๋ก mbpp_deserialize_inputs ์ ์ฉ๋จ
problems = list(mbpp_problems.keys())
print(f"โ
MBPP+ ๋ฐ์ดํฐ ๋ก๋ ์ฑ๊ณต: {len(problems)}๊ฐ ๋ฌธ์ (EvalPlus ํ์ค ๋ฐฉ์)")
except Exception as e:
print(f"โ MBPP+ EvalPlus ๋ก๋ฉ ์คํจ, ๊ธฐ์กด ๋ฐฉ์ ์ฌ์ฉ: {e}")
# Fallback to original method
data_path = benchmark_config.data_path
if os.path.exists(data_path):
with open(data_path, 'r') as f:
for line in f:
problem = json.loads(line.strip())
problems.append(problem['task_id'])
elif benchmark_config.name == 'humaneval':
# HumanEval+ EvalPlus ํ์ค ๋ฐ์ดํฐ ๋ก๋ฉ
try:
from evalplus.data.humaneval import get_human_eval_plus
humaneval_problems = get_human_eval_plus()
problems = list(humaneval_problems.keys())
print(f"โ
HumanEval+ ๋ฐ์ดํฐ ๋ก๋ ์ฑ๊ณต: {len(problems)}๊ฐ ๋ฌธ์ (EvalPlus ํ์ค ๋ฐฉ์)")
except Exception as e:
print(f"โ HumanEval+ EvalPlus ๋ก๋ฉ ์คํจ, ๊ธฐ์กด ๋ฐฉ์ ์ฌ์ฉ: {e}")
# Fallback to original method
data_path = benchmark_config.data_path
if os.path.exists(data_path):
with open(data_path, 'r') as f:
for line in f:
problem = json.loads(line.strip())
problems.append(problem['task_id'])
return problems
def create_problem_list(benchmark: str, num_problems: int, specific_problem_id: str = None) -> list:
"""๋ฒค์น๋งํฌ๋ณ ๋ฌธ์ ID ๋ฆฌ์คํธ ์์ฑ (๊ธฐ์กด TTRLVR ๋ฐฉ์ ์ฌ์ฉ)"""
# BenchmarkConfig ์์ฑ
benchmark_config = create_benchmark_config(benchmark)
# ์ ์ฒด ๋ฌธ์ ๋ชฉ๋ก ๋ก๋
all_problems = load_benchmark_problems(benchmark_config)
if not all_problems:
raise ValueError(f"No problems found for benchmark: {benchmark}")
# ํน์ ๋ฌธ์ ID๊ฐ ์ง์ ๋ ๊ฒฝ์ฐ
if specific_problem_id:
if specific_problem_id in all_problems:
return [specific_problem_id]
else:
raise ValueError(f"Problem ID '{specific_problem_id}' not found in {benchmark} benchmark")
# ์์ฒญ๋ ์๋งํผ ๋ฌธ์ ์ ํ
if num_problems <= 0 or num_problems > len(all_problems):
return all_problems
else:
return all_problems[:num_problems]
def create_config(args) -> TestTimeConfig:
"""TestTimeConfig ์์ฑ"""
config = TestTimeConfig()
# ๊ธฐ๋ณธ ์ค์
config.model_name = args.model # ์ธ์๋ก ๋ฐ์ ๋ชจ๋ธ ์ฌ์ฉ
config.max_new_tokens = 512
config.temperature = 0.05
config.baseline_evaluation_rounds = args.eval_rounds # ํ๊ฐ ํ์
# ํ๋ก๊ทธ๋จ ์์ฑ ์ค์
config.num_program_variations = args.num_programs # ๋ค์ํ ํ๋ก๊ทธ๋จ ๊ฐ์
config.input_generation_rounds = args.input_generation_rounds # ์
๋ ฅ ์์ฑ ๋ผ์ด๋ ์
config.parallel_batch_size = args.parallel_batch_size # ๋์ ์ฒ๋ฆฌ ํ๋กฌํํธ ์
# Task evaluation ์คํต ์ค์
config.skip_task_evaluation = args.skip_task_eval # Task evaluation ์คํต ์ฌ๋ถ
# ๋๋ฒ๊ทธ ๋ชจ๋
if args.debug:
config.debug = True
config.verbose = True
return config
def create_benchmark_config(benchmark: str) -> BenchmarkConfig:
"""BenchmarkConfig ์์ฑ (๊ธฐ์กด TTRLVR ๋ฐฉ์ ์ฌ์ฉ)"""
# ๊ธฐ์กด TTRLVR ์์คํ
๊ณผ ๋์ผํ ๋ฐฉ์์ผ๋ก BenchmarkConfig ์์ฑ
# TestTime-RLVR-v2 ๋๋ ํ ๋ฆฌ๋ฅผ base๋ก ์ฌ์ฉ
base_dir = Path(__file__).parent.parent # TestTime-RLVR-v2 directory
if benchmark == 'mbpp':
benchmark_config = BenchmarkConfig.get_mbpp_config()
benchmark_config.data_path = str(base_dir / 'evaluation/code_eval/data/MbppPlus.jsonl')
return benchmark_config
elif benchmark == 'humaneval':
benchmark_config = BenchmarkConfig.get_humaneval_config()
benchmark_config.data_path = str(base_dir / 'evaluation/code_eval/data/HumanEvalPlus.jsonl')
return benchmark_config
else:
raise ValueError(f"Unknown benchmark: {benchmark}")
def run_step5_only_mode(args):
"""Step 5 ์ ์ฉ ๋ชจ๋ ์คํ"""
from pathlib import Path
print(f"๐ Running Step 5 (VeRL training) only mode")
print(f"๐ Data path: {args.data_path}")
# ๋ฐ์ดํฐ ๊ฒฝ๋ก ๊ฒ์ฆ
data_path = Path(args.data_path)
if not data_path.exists():
print(f"โ Error: Data path does not exist: {data_path}")
return 1
# ํ์ ํ์ผ๋ค ํ์ธ
required_files = ['induction.parquet', 'deduction.parquet', 'abduction.parquet']
missing_files = []
for file_name in required_files:
if not (data_path / file_name).exists():
missing_files.append(file_name)
if missing_files:
print(f"โ Error: Missing required files: {missing_files}")
return 1
print(f"โ
Found all required training data files in: {data_path}")
# ํ์ผ ํฌ๊ธฐ ์ ๋ณด ์ถ๋ ฅ
for file_name in required_files:
file_path = data_path / file_name
file_size = file_path.stat().st_size
print(f" ๐ {file_name}: {file_size:,} bytes")
# ํ๊ฒฝ ์ค์
setup_environment(args.gpu, args.batch_size)
# ์ค์ ํ์ผ ๊ฒฝ๋ก ๊ฒฐ์
config_path = args.config
if not config_path:
# GPU ๊ฐ์์ ๋ฐ๋ผ ๊ธฐ๋ณธ ์ค์ ํ์ผ ์ ํ
gpu_count = len(args.gpu.split(',')) if args.gpu else 1
if gpu_count >= 4:
config_path = str(Path(__file__).parent / 'configs/ttrlvr_azr_ppo_4gpu.yaml')
else:
config_path = str(Path(__file__).parent / 'configs/ttrlvr_azr_ppo_1gpu.yaml')
print(f"๐ Initializing trainer with config: {config_path}")
# TestTimeConfig ์์ฑ (๊ธฐ์กด create_config ํจ์ ์ฌ์ฉ)
config = create_config(args)
# ๋ก๊ฑฐ ์ด๊ธฐํ
logger = TestTimeLogger()
# IterativeTrainer ์ด๊ธฐํ
global _trainer_instance
_trainer_instance = IterativeTrainer(
config=config,
logger=logger,
verl_config_path=config_path
)
# Step 5 ์ ์ฉ VeRL ํ์ต ์คํ
try:
result = _trainer_instance.run_verl_training_only(
training_data_path=str(data_path),
round_num=args.resume, # resume์ round number๋ก ์ฌ์ฉ
experiment_name=f"step5_only_{args.benchmark}"
)
if result.get('success', False):
print(f"โ
VeRL training completed successfully!")
print(f"โฑ๏ธ Duration: {result.get('duration', 'N/A')} seconds")
if 'model_path' in result:
print(f"๐ค Updated model: {result['model_path']}")
return 0
else:
print(f"โ VeRL training failed: {result.get('error', 'Unknown error')}")
return 1
except Exception as e:
print(f"๐ฅ Training failed with exception: {e}")
import traceback
traceback.print_exc()
return 1
def main():
"""๋ฉ์ธ ์คํ ํจ์ - UnifiedTTRLVRTrainer ์ฌ์ฉ"""
# ์ธ์ ํ์ฑ
args = parse_arguments()
# ํ๊ฒฝ ์ค์
setup_environment(args.gpu)
# ์ถ๋ ฅ ๋๋ ํ ๋ฆฌ ์์ฑ
timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
output_dir = os.path.join(
args.output_dir,
f'ttrlvr_unified_{args.benchmark}_{args.rounds}rounds_{timestamp}'
)
os.makedirs(output_dir, exist_ok=True)
PrettyPrinter.section_header("๐ TTRLVR Unified Training")
PrettyPrinter.status("Config", f"Benchmark: {args.benchmark}", "info")
PrettyPrinter.status("Config", f"Rounds: {args.rounds}", "info")
PrettyPrinter.status("Config", f"Output: {output_dir}", "info")
# ๋ฌธ์ ๋ฆฌ์คํธ ์์ฑ
problem_ids = create_problem_list(args.benchmark, args.problems, args.problem_id)
PrettyPrinter.status("Problems", f"Selected {len(problem_ids)} problems", "info")
# TTRLVR ์ค์
ttrlvr_config = {
'num_programs': args.num_programs,
'input_generation_rounds': args.input_generation_rounds,
'parallel_batch_size': args.parallel_batch_size,
}
# VeRL config ํ์ผ ๊ฒฝ๋ก
if args.config:
config_path = os.path.abspath(args.config)
else:
# ํ์ฌ๋ 4GPU config๋ง ์ฌ์ฉ (์ถํ 1GPU config ์ถ๊ฐ ์ ์์ )
config_path = str(Path(__file__).parent / 'configs/ttrlvr_azr_unified_4gpu.yaml')
PrettyPrinter.status("Config", f"Using VeRL config: {config_path}", "info")
try:
# ============================================
# VeRL์ ํตํด UnifiedTTRLVRTrainer ์คํ
# ============================================
# VeRL ์คํ์ ์ํ ํ๊ฒฝ ๋ณ์ ์ค์
os.environ['TTRLVR_PROBLEM_IDS'] = json.dumps(problem_ids)
os.environ['TTRLVR_TOTAL_ROUNDS'] = str(args.rounds)
os.environ['TTRLVR_OUTPUT_DIR'] = output_dir
os.environ['TTRLVR_CONFIG'] = json.dumps(ttrlvr_config)
# ============================================
# AZR ํ์์ผ๋ก ์ด๊ธฐํ, TTRLVR ๋ฐฉ์์ผ๋ก ์คํ
# (main_azr_ppo.py์ ๊ตฌ์กฐ๋ฅผ ๋ฐ๋ฅด๋ UnifiedTTRLVRTrainer ์ฌ์ฉ)
# ============================================
PrettyPrinter.section_header("๐ฏ Starting UnifiedTTRLVRTrainer (AZR-style initialization)")
# 1. Config ๋ก๋ (main_azr_ppo.py์ ๋์ผ)
PrettyPrinter.status("Config", f"Loading {config_path}", "info")
verl_config = OmegaConf.load(config_path)
# Config ์
๋ฐ์ดํธ
verl_config.trainer.project_name = f'ttrlvr_unified_{args.benchmark}'
verl_config.trainer.experiment_name = f'round_{args.rounds}_{timestamp}'
verl_config.trainer.total_epochs = args.rounds
# 2. Ray ์ด๊ธฐํ (main_azr_ppo.py์ ๋์ผ)
if not ray.is_initialized():
cuda_visible_devices = args.gpu or "0,1,2,3"
PrettyPrinter.status("Ray", f"Initializing Ray cluster (GPUs: {cuda_visible_devices})", "info")
ray.init(
runtime_env={"env_vars": {
"TOKENIZERS_PARALLELISM": "true",
"NCCL_DEBUG": "WARN",
"VLLM_LOGGING_LEVEL": "WARN",
"VLLM_ALLOW_RUNTIME_LORA_UPDATING": "true",
"CUDA_VISIBLE_DEVICES": cuda_visible_devices
}},
num_cpus=verl_config.ray_init.num_cpus,
# num_gpus ์ง์ ํ์ง ์์ - Ray๊ฐ ์๋์ผ๋ก GPU ๊ฐ์ง (AZR ์๋ณธ๊ณผ ๋์ผ)
)
# 3. Tokenizer ๋ก๋ (main_azr_ppo.py์ ๋์ผ)
model_path = verl_config.actor_rollout_ref.model.path
PrettyPrinter.status("Model", f"Loading tokenizer from {model_path}", "info")
tokenizer = hf_tokenizer(model_path)
# 4. Worker ๋งคํ ์ค์ (main_azr_ppo.py์ ๋์ผ)
role_worker_mapping = {}
# Actor/Rollout Worker ์ ํ
if verl_config.actor_rollout_ref.rollout.name == 'vllm':
if verl_config.actor_rollout_ref.rollout.mode == 'async':
actor_rollout_cls = AsyncActorRolloutRefWorker
else:
actor_rollout_cls = ActorRolloutRefWorker
# AZR ์๋ณธ๊ณผ ๋์ผํ๊ฒ ray.remote() ์ฌ์ฉ
role_worker_mapping[Role.ActorRollout] = ray.remote(actor_rollout_cls)
PrettyPrinter.status("Workers", f"Using {actor_rollout_cls.__name__} for ActorRollout", "info")
# Critic Worker (REINFORCE++๋ ์ฌ์ฉ ์ํจ)
if verl_config.critic.include_critic:
# AZR ์๋ณธ๊ณผ ๋์ผํ๊ฒ ray.remote() ์ฌ์ฉ
role_worker_mapping[Role.Critic] = ray.remote(CriticWorker)
PrettyPrinter.status("Workers", "Including Critic worker", "info")
else:
PrettyPrinter.status("Workers", "No Critic (using REINFORCE++)", "info")
# 5. ResourcePoolManager ์์ฑ (main_azr_ppo.py์ ๋์ผ)
# AZR ์คํ์ผ๋ก resource_pool_spec ์ง์ ์์ฑ
global_pool_id = "global_pool"
n_gpus_per_node = verl_config.trainer.n_gpus_per_node
nnodes = verl_config.trainer.nnodes
resource_pool_spec = {
global_pool_id: [n_gpus_per_node] * nnodes,
}
mapping = {
Role.ActorRollout: global_pool_id,
}
if verl_config.critic.include_critic:
mapping[Role.Critic] = global_pool_id
resource_pool_manager = ResourcePoolManager(resource_pool_spec=resource_pool_spec, mapping=mapping)
PrettyPrinter.status("Resources", f"Created ResourcePoolManager with {len(resource_pool_spec)} pools", "info")
# 6. UnifiedTTRLVRTrainer ์์ฑ (CodeIORayPPOTrainer ๋์ )
from trainer.unified_ttrlvr_trainer import UnifiedTTRLVRTrainer
PrettyPrinter.status("Trainer", "Creating UnifiedTTRLVRTrainer", "info")
trainer = UnifiedTTRLVRTrainer(
past_epoch_window=verl_config.azr.past_epoch_window, # AZR ํ์ ํ๋ผ๋ฏธํฐ (TTRLVR์ ๋งค ๋ผ์ด๋ ์ ๋ฐ์ดํฐ)
config=verl_config,
tokenizer=tokenizer,
processor=None, # TTRLVR์ ํ
์คํธ ์ ์ฉ์ด๋ฏ๋ก ๋ถํ์
role_worker_mapping=role_worker_mapping,
resource_pool_manager=resource_pool_manager,
ray_worker_group_cls=RayWorkerGroup,
reward_fn=None, # TTRLVR์ ์์ฒด ๋ณด์ ๊ณ์ฐ ์ฌ์ฉ (use_ttrlvr_rewards=True)
val_reward_fn=None, # TTRLVR์ ๊ฒ์ฆ ์์
# TTRLVR ํนํ ํ๋ผ๋ฏธํฐ
ttrlvr_config=ttrlvr_config,
problem_ids=problem_ids,
total_rounds=args.rounds,
output_dir=output_dir
)
# 7. ํ์ต ์คํ (main_azr_ppo.py์ ๋์ผ)
PrettyPrinter.section_header("๐ Starting Training")
PrettyPrinter.status("Training", f"Running {args.rounds} rounds with {len(problem_ids)} problems", "info")
trainer.fit() # ๋ด๋ถ์์ TTRLVR Phase 1-5 ์คํ
PrettyPrinter.section_header("โ
Training Complete")
return 0
except KeyboardInterrupt:
PrettyPrinter.status("Interrupt", "Training interrupted by user", "warning")
return 130
except Exception as e:
PrettyPrinter.status("Error", f"Training failed: {e}", "error")
import traceback
traceback.print_exc()
return 1
finally:
# Ray cleanup
if ray.is_initialized():
ray.shutdown()
PrettyPrinter.status("Cleanup", "Resources cleaned up", "success")
if __name__ == '__main__':
exit_code = main()
sys.exit(exit_code) |