File size: 94,350 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 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 |
#!/usr/bin/env python3
"""
TTRLVR + AZR ๋ฐ๋ณต ํ์ต ํธ๋ ์ด๋
30๋ผ์ด๋ ๋ฐ๋ณต ํ์ต์ ๊ด๋ฆฌํ๋ฉฐ, ๊ฐ ๋ผ์ด๋๋ง๋ค:
1. TTRLVR ํ์ดํ๋ผ์ธ์ผ๋ก (i,p,o) โ tasks ์์ฑ
2. ํด๋น ๋ผ์ด๋ ๋ฐ์ดํฐ๋ก ์ค์ AZR์ CodeIORayPPOTrainer ํ์ต
3. ๊ฐ์ ๋ ๋ชจ๋ธ๋ก ๋ค์ ๋ผ์ด๋ ์งํ
"""
import os
import sys
import json
import pandas as pd
import ray
from pathlib import Path
from datetime import datetime
from typing import Dict, List, Any, Optional
# TTRLVR ๋ชจ๋ ์ํฌํธ
sys.path.append('/home/ubuntu/RLVR/TestTime-RLVR-v2')
from absolute_zero_reasoner.testtime.complete_pipeline import CompleteTestTimePipeline
from absolute_zero_reasoner.testtime.config import TestTimeConfig, BenchmarkConfig
from absolute_zero_reasoner.testtime.logger import TestTimeLogger
# VeRL ๊ธฐ๋ฐ AZR ์คํ์ ์ํ ์ํฌํธ
from utils.checkpoint_manager import CheckpointManager
from absolute_zero_reasoner.trainer.ppo.azr_ray_trainer import CodeIORayPPOTrainer
from utils.custom_ray_trainer import CustomCodeIORayPPOTrainer
import hydra
from hydra.core.global_hydra import GlobalHydra
class IterativeTrainer:
"""TTRLVR + AZR ๋ฐ๋ณต ํ์ต ๊ด๋ฆฌ์"""
def __init__(self, config: TestTimeConfig, logger: Optional[TestTimeLogger] = None, batch_epochs: int = 1, verl_config_path: str = None, save_every_round: bool = False, save_round_interval: int = 5):
self.config = config
self.logger = logger or TestTimeLogger()
self.batch_epochs = batch_epochs # ๋ฐฐ์น๋น ์ํญ ์ ์ ์ฅ
self.verl_config_path = verl_config_path # VeRL config ํ์ผ ๊ฒฝ๋ก
self.save_every_round = save_every_round # ๋งค ๋ผ์ด๋ ์ ์ฅ ์ฌ๋ถ
self.save_round_interval = save_round_interval # ์ ์ฅ ๊ฐ๊ฒฉ
# GPU ๊ฐ์ ๊ฐ์ง ๋ฐ ์คํ ๋ชจ๋ ๊ฒฐ์
self.available_gpus = self._detect_available_gpus()
self.execution_mode = self._determine_execution_mode()
self.logger.log_info(f"๐ฏ Detected {len(self.available_gpus)} GPUs: {self.available_gpus}")
self.logger.log_info(f"๐ฏ Execution mode: {self.execution_mode}")
# ์์ ํ ํ์ดํ๋ผ์ธ ์ธ์คํด์ค (lazy initialization)
self.complete_pipeline = None
# ์ฒดํฌํฌ์ธํธ ๋งค๋์ ์ด๊ธฐํ
self.checkpoint_manager = CheckpointManager(logger=self.logger)
# ํ์ต ์ํ ์ถ์
self.original_model_name = config.model_name # ์๋ณธ ๋ชจ๋ธ ์ด๋ฆ ์ ์ฅ (tokenizer ๋ก๋์ฉ)
self.current_model_path = config.model_name # config์์ ๋ชจ๋ธ ์ด๋ฆ ๊ฐ์ ธ์ค๊ธฐ
self.current_model = None # ํ์ฌ ๋ชจ๋ธ ์ธ์คํด์ค ์ ์ฅ (VeRL๊ณผ ๊ณต์ ์ฉ)
self.round_results = {}
self.checkpoint_dir = "/data/RLVR/checkpoints/ttrlvr_azr"
# Ray Actor๋ก ํ์ดํ๋ผ์ธ ๊ด๋ฆฌ (VeRL ํจํด)
self.remote_pipeline = None
# VeRL trainer ์ธ์คํด์ค (ํ ๋ฒ๋ง ์ด๊ธฐํ, ๋ฉ๋ชจ๋ฆฌ์์ ๊ณ์ ์ฌ์ฉ)
self.verl_trainer = None
self.verl_config = None
self.ray_initialized = False
# ํ์ต ์คํ ์๊ฐ ๊ธฐ๋ก
self.start_time = None
self.round_times = {}
def cleanup(self):
"""Ray ํด๋ฌ์คํฐ ๋ฐ ๊ด๋ จ ๋ฆฌ์์ค ์ ๋ฆฌ"""
try:
self.logger.log_info("๐งน Starting cleanup process...")
# VeRL trainer ์ ๋ฆฌ
if hasattr(self, 'verl_trainer') and self.verl_trainer is not None:
try:
self.logger.log_info(" - Cleaning up VeRL trainer...")
# VeRL trainer์ Ray actors ์ ๋ฆฌ
if hasattr(self.verl_trainer, 'shutdown'):
self.verl_trainer.shutdown()
self.verl_trainer = None
except Exception as e:
self.logger.log_warning(f" - VeRL trainer cleanup warning: {e}")
# Remote pipeline actor ์ข
๋ฃ
if self.remote_pipeline is not None:
try:
self.logger.log_info(" - Killing remote pipeline actor...")
ray.kill(self.remote_pipeline)
except:
pass
self.remote_pipeline = None
# Ray ํด๋ฌ์คํฐ ์ข
๋ฃ
if self.ray_initialized and ray.is_initialized():
self.logger.log_info(" - Shutting down Ray cluster...")
# ๋ชจ๋ Ray actors ๊ฐ์ ์ข
๋ฃ
try:
# ํ์ฌ ์คํ ์ค์ธ ๋ชจ๋ actors ๊ฐ์ ธ์ค๊ธฐ
actors = ray.util.list_named_actors()
if actors:
self.logger.log_info(f" - Found {len(actors)} named actors to kill")
for actor in actors:
try:
ray.kill(ray.get_actor(actor['name']))
except:
pass
except:
pass
# Ray shutdown with force
ray.shutdown()
self.ray_initialized = False
# Ray ํ๋ก์ธ์ค๊ฐ ์์ ํ ์ข
๋ฃ๋ ๋๊น์ง ์ ์ ๋๊ธฐ
import time
time.sleep(2)
self.logger.log_info("โ
Ray cluster shutdown complete")
# GPU ๋ฉ๋ชจ๋ฆฌ ์ ๋ฆฌ
try:
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
self.logger.log_info(" - GPU memory cleared")
except:
pass
except Exception as e:
self.logger.log_error(f"Error during cleanup: {e}")
# ๊ทธ๋๋ Ray๋ ๊ฐ์ ์ข
๋ฃ ์๋
try:
ray.shutdown()
except:
pass
def run_iterative_training(self, benchmark_config: BenchmarkConfig,
problem_ids: List[str],
total_rounds: int = 30,
resume_from_round: int = 1) -> Dict[str, Any]:
"""30๋ผ์ด๋ ๋ฐ๋ณต ํ์ต ๋ฉ์ธ ๋ฃจํ"""
self.start_time = datetime.now()
# ์ธ์
์ ์ฒด์์ ์ฌ์ฉํ timestamp ์์ฑ (ํ ๋ฒ๋ง)
self.session_timestamp = self.start_time.strftime('%Y%m%d_%H%M%S')
self.logger.log_info(f"๐ Starting TTRLVR + AZR iterative training")
self.logger.log_info(f"๐ Configuration: {len(problem_ids)} problems, {total_rounds} rounds")
self.logger.log_info(f"๐ฏ Problems: {problem_ids}")
self.logger.log_info(f"๐ Session timestamp: {self.session_timestamp}")
# ์ฒดํฌํฌ์ธํธ์์ ์ฌ๊ฐํ๋ ๊ฒฝ์ฐ
if resume_from_round > 1:
self.logger.log_info(f"๐ Resuming from round {resume_from_round}")
checkpoint_model = self._load_checkpoint(resume_from_round - 1)
if checkpoint_model:
self.current_model_path = checkpoint_model
training_results = {
'start_time': self.start_time.isoformat(),
'session_timestamp': self.session_timestamp,
'benchmark': benchmark_config.name,
'problem_ids': problem_ids,
'total_rounds': total_rounds,
'resume_from_round': resume_from_round,
'rounds': {},
'success': False,
'error': None
}
try:
# ๋ฉ์ธ ๋ฐ๋ณต ํ์ต ๋ฃจํ
for round_num in range(resume_from_round, total_rounds + 1):
round_start_time = datetime.now()
self.logger.log_info(f"" + "="*80)
self.logger.log_info(f"๐ ROUND {round_num}/{total_rounds} - Starting")
self.logger.log_info(f"๐ค Current model: {self.current_model_path}")
self.logger.log_info(f"" + "="*80)
# ๋จ์ผ ๋ผ์ด๋ ์คํ
round_result = self._run_single_round(
benchmark_config, problem_ids, round_num
)
# ๋ผ์ด๋ ๊ฒฐ๊ณผ ์ ์ฅ
round_end_time = datetime.now()
round_duration = (round_end_time - round_start_time).total_seconds()
self.round_times[round_num] = round_duration
round_result['duration_seconds'] = round_duration
round_result['model_before'] = self.current_model_path
training_results['rounds'][round_num] = round_result
if not round_result['success']:
self.logger.log_error(f"โ Round {round_num} failed: {round_result.get('error', 'Unknown error')}")
continue
# AZR ํ์ต ์คํ
if round_result['training_data_files']:
self.logger.log_info(f"๐ Starting AZR training for round {round_num}")
new_model_path = self._train_azr_with_round_data(
round_result['training_data_files'], round_num
)
if new_model_path:
self.current_model_path = new_model_path
round_result['model_after'] = new_model_path
self.logger.log_info(f"โ
Round {round_num} completed successfully")
self.logger.log_info(f"๐ฏ New model: {new_model_path}")
# โญ VLLM Ray Actor์ ๊ฐ์ค์น๋ ์
๋ฐ์ดํธ (์ง์ ํ ๋ชจ๋ธ ๊ณต์ )
if hasattr(self, 'remote_pipeline') and self.remote_pipeline is not None:
self.logger.log_info("๐ Updating VLLM Ray Actor weights with trained model")
import ray
update_success = ray.get(self.remote_pipeline.update_model_weights.remote(new_model_path))
if update_success:
self.logger.log_info("โ
VLLM weights updated successfully for next round")
else:
self.logger.log_warning("โ ๏ธ Failed to update VLLM weights, using old model")
else:
self.logger.log_error(f"โ AZR training failed for round {round_num}")
round_result['training_error'] = "AZR training failed"
# ์ฒดํฌํฌ์ธํธ ์ ์ฅ (5๋ผ์ด๋๋ง๋ค)
if round_num % 5 == 0:
self._save_checkpoint(round_num, self.current_model_path, training_results)
self.logger.log_info(f"๐พ Checkpoint saved for round {round_num}")
# ๋ผ์ด๋ ์์ฝ ๋ก๊ทธ
self._log_round_summary(round_num, round_result, round_duration)
# ์ ์ฒด ํ์ต ์๋ฃ
training_results['success'] = True
training_results['end_time'] = datetime.now().isoformat()
training_results['total_duration_seconds'] = (datetime.now() - self.start_time).total_seconds()
training_results['final_model'] = self.current_model_path
self.logger.log_info(f"๐ TTRLVR + AZR iterative training completed successfully!")
# VeRL Trainer ์ ๋ฆฌ
if hasattr(self, 'verl_trainer') and self.verl_trainer is not None:
self.logger.log_info("๐งน Cleaning up VeRL Trainer...")
try:
# VeRL trainer cleanup (Ray ๋ฑ)
if hasattr(self.verl_trainer, 'cleanup'):
self.verl_trainer.cleanup()
self.verl_trainer = None
except Exception as cleanup_error:
self.logger.log_warning(f"Cleanup warning: {cleanup_error}")
self._log_final_summary(training_results)
return training_results
except Exception as e:
self.logger.log_error(f"๐ฅ Iterative training failed: {e}")
import traceback
traceback.print_exc()
return {
'success': False,
'error': str(e),
'rounds': self.round_results
}
def run_verl_training_only(self, training_data_path: str, round_num: int = 1,
experiment_name: Optional[str] = None) -> Dict[str, Any]:
"""
VeRL training(5๋จ๊ณ)๋ง ๋ณ๋๋ก ์คํ
1-4๋จ๊ณ์์ ์์ฑ๋ ๋ฐ์ดํฐ๋ก VeRL PPO ํ์ต๋ง ์ํ
Args:
training_data_path: TTRLVR์์ ์์ฑ๋ ํ์ต ๋ฐ์ดํฐ ๊ฒฝ๋ก (parquet ํ์ผ๋ค)
round_num: ๋ผ์ด๋ ๋ฒํธ (๋ก๊ทธ์ฉ)
experiment_name: ์คํ ์ด๋ฆ (์ ํ์ฌํญ)
Returns:
ํ์ต ๊ฒฐ๊ณผ ๋์
๋๋ฆฌ
"""
try:
self.logger.log_info("๐ Starting VeRL training ONLY (Step 5)")
self.logger.log_info("="*80)
self.logger.log_info(f"๐ Training data path: {training_data_path}")
self.logger.log_info(f"๐ Round: {round_num}")
# VeRL config ๋ก๋ (ํ์์)
if not hasattr(self, 'verl_config') or self.verl_config is None:
self.logger.log_info("๐ง Loading VeRL config for standalone training")
self._load_verl_config()
# ํ์ต ๋ฐ์ดํฐ ๊ฒฝ๋ก ์
๋ฐ์ดํธ
if not os.path.exists(training_data_path):
raise FileNotFoundError(f"Training data path not found: {training_data_path}")
# parquet ํ์ผ๋ค ์ฐพ๊ธฐ
parquet_files = list(Path(training_data_path).glob("*.parquet"))
if not parquet_files:
raise FileNotFoundError(f"No parquet files found in: {training_data_path}")
# VeRL config ์
๋ฐ์ดํธ
self.verl_config.data.train_files = [str(f) for f in parquet_files]
self.verl_config.data.val_files = [str(f) for f in parquet_files[:1]] # ์ฒซ ๋ฒ์งธ ํ์ผ์ validation์ผ๋ก
self.logger.log_info(f"๐ Found {len(parquet_files)} training files")
for i, f in enumerate(parquet_files):
self.logger.log_info(f" {i+1}. {f.name}")
# โญ VeRL trainer ์ด๊ธฐํ (์ค์ ๋ฐ์ดํฐ๋ก)
if not hasattr(self, 'verl_trainer') or self.verl_trainer is None:
self.logger.log_info("๐ Initializing VeRL trainer with actual training data")
# GPU ๋ฉ๋ชจ๋ฆฌ ์ ๋ฆฌ (FSDP ๋ก๋ ์ )
import torch
torch.cuda.empty_cache()
# VeRL trainer ์ด๊ธฐํ
self._initialize_verl_trainer(training_data_path)
self.logger.log_info(f"โ
FSDP model loaded on GPU {self.available_gpus}")
self.logger.log_info("โ
GPU sharing enabled: VLLM + FSDP on same GPUs")
else:
# ๊ธฐ์กด VeRL trainer๊ฐ ์๋ค๋ฉด ๋ฐ์ดํฐ ๊ฒฝ๋ก ์
๋ฐ์ดํธ
self.logger.log_info("๐ Updating existing VeRL trainer with new data files")
# Trainer์ config ์
๋ฐ์ดํธ
self.verl_trainer.config.data.train_files = self.verl_config.data.train_files
self.verl_trainer.config.data.val_files = self.verl_config.data.val_files
# init_workers๊ฐ ๋ฐ์ดํฐ๋ก๋๋ฅผ ์์ฑํ๋ฏ๋ก ๋ค์ ํธ์ถ
self.logger.log_info("๐ง Re-initializing VeRL workers with new data...")
self.verl_trainer.init_workers()
self.logger.log_info("โ
VeRL workers re-initialized with actual training data")
# ์คํ๋ช
์ค์
if experiment_name:
self.verl_config.experiment.name = experiment_name
else:
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
self.verl_config.experiment.name = f"verl_only_round_{round_num}_{timestamp}"
self.logger.log_info(f"๐ท๏ธ Experiment: {self.verl_config.experiment.name}")
# 5๋จ๊ณ: VeRL PPO ํ์ต ์คํ
self.logger.log_info("๐ Starting VeRL PPO training...")
start_time = datetime.now()
# VeRL trainer๋ก ์ง์ ํ์ต ์คํ
try:
if hasattr(self, 'verl_trainer') and self.verl_trainer is not None:
# ํ์ต ์ค ์์ฑ๋ ์๋ต์ ์ ์ฅํ ๋๋ ํ ๋ฆฌ ์ค์ (๊ธฐ์กด ๊ฒฝ๋ก ๊ตฌ์กฐ์ ์ถ๊ฐ)
llm_responses_dir = os.path.join(os.path.dirname(training_data_path), "llm_responses")
os.makedirs(llm_responses_dir, exist_ok=True)
self.logger.log_info(f"๐ LLM responses will be saved to: {llm_responses_dir}")
# VeRL config์ rollout ๋ฐ์ดํฐ ์ ์ฅ ๊ฒฝ๋ก ์ค์
self.verl_trainer.config.trainer.rollout_data_dir = llm_responses_dir
# ์ปค์คํ
๋ก๊น
์ ์ํ ์ฝ๋ฐฑ ์ค์
self.llm_responses_dir = llm_responses_dir
self.response_counter = 0
self.logger.log_info("๐ฏ Running VeRL PPO training...")
self.verl_trainer.fit()
training_result = {'success': True, 'model_path': self.current_model_path}
self.logger.log_info("โ
VeRL training completed successfully")
# JSONL ํ์ผ๋ค์ TTRLVR ํ์์ผ๋ก ๋ณํ
if hasattr(self, 'llm_responses_dir') and os.path.exists(self.llm_responses_dir):
self.logger.log_info("๐ Converting VeRL outputs to TTRLVR format...")
jsonl_files = list(Path(self.llm_responses_dir).glob("*.jsonl"))
for jsonl_file in jsonl_files:
self._convert_jsonl_to_ttrlvr_format(str(jsonl_file), self.llm_responses_dir)
self.logger.log_info(f"โ
Converted {len(jsonl_files)} JSONL files to TTRLVR format")
else:
raise ValueError("VeRL trainer not initialized")
except Exception as e:
self.logger.log_error(f"VeRL training failed: {e}")
training_result = {'success': False, 'error': str(e)}
end_time = datetime.now()
duration = (end_time - start_time).total_seconds()
self.logger.log_info(f"โฑ๏ธ VeRL training completed in {duration:.1f} seconds")
# ๊ฒฐ๊ณผ ๊ตฌ์ฑ
result = {
'success': training_result.get('success', False),
'round': round_num,
'experiment_name': self.verl_config.experiment.name,
'training_data_path': training_data_path,
'duration_seconds': duration,
'start_time': start_time.isoformat(),
'end_time': end_time.isoformat(),
'training_files': len(parquet_files),
'model_path': getattr(training_result, 'model_path', self.current_model_path),
'details': training_result
}
if result['success']:
self.logger.log_info("๐ VeRL training completed successfully!")
if 'model_path' in training_result:
self.current_model_path = training_result['model_path']
self.logger.log_info(f"๐ค Updated model path: {self.current_model_path}")
else:
self.logger.log_error("โ VeRL training failed")
self.logger.log_error(f"Error: {training_result.get('error', 'Unknown error')}")
return result
except Exception as e:
self.logger.log_error(f"๐ฅ VeRL-only training failed: {e}")
import traceback
traceback.print_exc()
return {
'success': False,
'error': str(e),
'round': round_num,
'training_data_path': training_data_path
}
def _process_single_round(self, benchmark_config: BenchmarkConfig,
problem_ids: List[str], round_num: int) -> Dict[str, Any]:
"""๋จ์ผ ๋ผ์ด๋ ์ฒ๋ฆฌ"""
round_start_time = datetime.now()
self.logger.log_info(f"๐ ROUND {round_num} - Starting")
try:
# ๋ผ์ด๋ ์คํ ๋ก์ง์ _run_single_round๋ก ์์
return self._run_single_round(benchmark_config, problem_ids, round_num)
except Exception as e:
self.logger.log_error(f"Round {round_num} failed: {e}")
return {
'success': False,
'error': str(e),
'round': round_num,
'duration_seconds': (datetime.now() - round_start_time).total_seconds()
}
def _run_single_round(self, benchmark_config: BenchmarkConfig,
problem_ids: List[str], round_num: int) -> Dict[str, Any]:
"""๋จ์ผ ๋ผ์ด๋ ์คํ - Ray๋ฅผ ํ์ฉํ ๋ณ๋ ฌ TTRLVR ํ์ดํ๋ผ์ธ ์คํ"""
round_result = {
'round_num': round_num,
'problems': {},
'training_data_files': [],
'success': False,
'error': None,
'stats': {
'total_problems': len(problem_ids),
'successful_problems': 0,
'failed_problems': 0,
'total_tasks': 0,
'tasks_by_type': {'induction': 0, 'deduction': 0, 'abduction': 0}
}
}
try:
# VeRL config ๋ก๋ (Ray ์ค์ ํ์ธ์ฉ)
if not hasattr(self, 'verl_config') or self.verl_config is None:
self.logger.log_info("๐ง Loading VeRL config for Ray settings")
self._load_verl_config()
# Ray ํด๋ฌ์คํฐ๊ฐ ์ด๊ธฐํ๋์๋์ง ํ์ธ
if not self.ray_initialized:
self.logger.log_info("๐ Initializing Ray for data generation")
self._initialize_ray_cluster()
# โญ VeRL trainer๋ 5๋จ๊ณ์์ ์ค์ ๋ฐ์ดํฐ๋ก ์ด๊ธฐํ
# GPU ๊ณต์ ์ค์ ๋ง ๋ฏธ๋ฆฌ ํ์ธ
if round_num == 1:
self.logger.log_info("๐ VeRL trainer will be initialized in Step 5 with actual data")
self.logger.log_info("๐ง GPU sharing plan: VLLM (GPU 1,2) + FSDP (GPU 0,1,2,3)")
# ํ์ฌ ๋ชจ๋ธ๋ก ํ์ดํ๋ผ์ธ ์
๋ฐ์ดํธ
self._update_pipeline_model(self.current_model_path)
successful_problems = 0
# ํญ์ ์์ฐจ ์ฒ๋ฆฌ ์ฌ์ฉ (๋ฌธ์ ๊ฐ ๋ณ๋ ฌ ์ฒ๋ฆฌ ์ ๊ฑฐ)
# ๋จ์ผ ๋ฌธ์ ๋ด์์๋ง VLLM ๋ฐฐ์น ๋ณ๋ ฌ ์ฒ๋ฆฌ ์ฌ์ฉ
self.logger.log_info(f"๐ Using sequential processing for {len(problem_ids)} problems")
self.logger.log_info(" - Multi-problem parallelization disabled")
self.logger.log_info(" - Single-problem VLLM batch processing enabled")
results = self._process_problems_sequential(benchmark_config, problem_ids, round_num)
# ๊ฒฐ๊ณผ ํตํฉ
for problem_id, pipeline_result in results.items():
round_result['problems'][problem_id] = pipeline_result
if pipeline_result['success']:
successful_problems += 1
# AZR ํ์ต ๋ฐ์ดํฐ ํ์ผ ์์ง
if 'azr_training_data' in pipeline_result:
round_result['training_data_files'].append({
'problem_id': problem_id,
'files': pipeline_result['azr_training_data']
})
# ํต๊ณ ์
๋ฐ์ดํธ
if 'azr_data_saving' in pipeline_result['steps']:
total_tasks = pipeline_result['steps']['azr_data_saving']['total_tasks']
round_result['stats']['total_tasks'] += total_tasks
self.logger.log_info(f"โ
{problem_id} completed successfully")
else:
self.logger.log_error(f"โ {problem_id} failed: {pipeline_result.get('error', 'Unknown error')}")
# ๋ผ์ด๋ ํต๊ณ ์
๋ฐ์ดํธ
round_result['stats']['successful_problems'] = successful_problems
round_result['stats']['failed_problems'] = len(problem_ids) - successful_problems
round_result['success'] = successful_problems > 0
if successful_problems == 0:
round_result['error'] = "No problems completed successfully"
return round_result
except Exception as e:
round_result['error'] = str(e)
return round_result
def _initialize_pipeline(self):
"""Ray Actor๋ก ํ์ดํ๋ผ์ธ ์ด๊ธฐํ (VeRL ํจํด)"""
if self.remote_pipeline is None:
try:
# TTRLVR ํ์ดํ๋ผ์ธ์ฉ config ์
๋ฐ์ดํธ
ttrlvr_config = self.config
# ์คํ ๋ชจ๋์ ๋ฐ๋ฅธ ์์ง ์ ํ
# VeRL config์์ rollout name ํ์ธ
if hasattr(self, 'verl_config') and self.verl_config and hasattr(self.verl_config, 'actor_rollout_ref'):
rollout_name = self.verl_config.actor_rollout_ref.rollout.name
# HuggingFace rollout์ด๋ฉด HuggingFace ์ฌ์ฉ
use_vllm = (rollout_name == "vllm")
else:
# ๊ธฐ๋ณธ๊ฐ: distributed๋ฉด vllm, single_gpu๋ฉด huggingface
use_vllm = (self.execution_mode == "distributed")
ttrlvr_config.use_vllm_for_data_generation = use_vllm
engine_name = "vllm" if use_vllm else "huggingface"
self.logger.log_info(f"๐ง TTRLVR data generation using: {engine_name} (execution_mode: {self.execution_mode})")
# Config ๋๋ฒ๊น
๋ก๊ทธ ์ถ๊ฐ
self.logger.log_info(f"๐ Config debug: num_program_variations = {ttrlvr_config.num_program_variations}")
self.logger.log_info(f"๐ Config debug: skip_task_evaluation = {getattr(ttrlvr_config, 'skip_task_evaluation', False)}")
# Ray Actor๋ก ํ์ดํ๋ผ์ธ ์์ฑ (GPU ๊ฐ์์ ๋ง์ถฐ ๋์ ์์ฑ)
from absolute_zero_reasoner.testtime.complete_pipeline import RemoteTestTimePipeline
gpu_count = len(self.available_gpus)
self.logger.log_info(f"๐ Creating RemoteTestTimePipeline with {gpu_count} GPUs, model: {self.current_model_path}")
# ๋ก๊ทธ ํ์ผ ๊ฒฝ๋ก๋ฅผ ํ๊ฒฝ ๋ณ์๋ก ์ค์
import os
if hasattr(self.logger, 'log_file_path') and self.logger.log_file_path:
runtime_env = {
"env_vars": {
"TTRLVR_LOG_FILE": self.logger.log_file_path,
"CUDA_VISIBLE_DEVICES": os.environ.get("CUDA_VISIBLE_DEVICES", "0")
}
}
self.logger.log_info(f"๐ง Setting TTRLVR_LOG_FILE for Ray worker: {self.logger.log_file_path}")
else:
runtime_env = {
"env_vars": {
"CUDA_VISIBLE_DEVICES": os.environ.get("CUDA_VISIBLE_DEVICES", "0")
}
}
self.logger.log_warning("โ ๏ธ Logger does not have log_file_path attribute, Ray worker will create its own log file")
# GPU ๊ฐ์์ ๋ฐ๋ฅธ Ray Actor ์์ฑ
# โญ GPU๋ฅผ ๋
์ ํ์ง ์๋๋ก num_gpus=0์ผ๋ก ์ค์
# VLLM์ ๋ด๋ถ์ ์ผ๋ก CUDA_VISIBLE_DEVICES๋ก ์ฒซ 2๊ฐ GPU๋ง ์ฌ์ฉ
gpu_count = len(self.available_gpus)
# ์ฌ์ฉ ๊ฐ๋ฅํ GPU ์ค ์ฒซ 2๊ฐ๋ฅผ VLLM์ฉ์ผ๋ก ํ ๋น
if gpu_count >= 2:
# ์ค์ GPU ์ธ๋ฑ์ค ๊ฐ์ ธ์ค๊ธฐ
cuda_devices = os.environ.get("CUDA_VISIBLE_DEVICES", "0,1,2,3").split(',')
vllm_gpus = f"{cuda_devices[0]},{cuda_devices[1]}" # ์ฒซ 2๊ฐ GPU
else:
vllm_gpus = os.environ.get("CUDA_VISIBLE_DEVICES", "0")
# Runtime ํ๊ฒฝ์ VLLM GPU ์ ํ ์ถ๊ฐ
# Ray runtime_env์์ ์ผํ๊ฐ ์๋ ํ๊ฒฝ๋ณ์๋ฅผ ์ ๋๋ก ์ฒ๋ฆฌํ๋๋ก ๋ช
์์ ์ผ๋ก ๋ฌธ์์ด๋ก ์ค์
runtime_env["env_vars"]["CUDA_VISIBLE_DEVICES"] = str(vllm_gpus)
runtime_env["env_vars"]["VLLM_USE_SPECIFIC_GPUS"] = str(vllm_gpus)
self.logger.log_info(f"๐ฏ Creating Ray Actor without exclusive GPU allocation")
self.logger.log_info(f" - VLLM will use GPUs: {vllm_gpus} (via CUDA_VISIBLE_DEVICES)")
self.logger.log_info(f" - FSDP can use all GPUs: {os.environ.get('CUDA_VISIBLE_DEVICES', '0,1,2,3')}")
# AZR ๋ฐฉ์: GPU ํ ๋น ์์ด Ray Actor ์์ฑ
# GPU๋ CUDA_VISIBLE_DEVICES๋ก๋ง ์ ์ด
RemoteTestTimePipelineWithGPUs = RemoteTestTimePipeline.options(
num_cpus=4, # VLLM ์ฒ๋ฆฌ๋ฅผ ์ํ ์ถฉ๋ถํ CPU ํ ๋น
# num_gpus ์ค์ ํ์ง ์์ - GPU๋ CUDA_VISIBLE_DEVICES๋ก ์ ์ด
runtime_env=runtime_env
)
self.remote_pipeline = RemoteTestTimePipelineWithGPUs.remote(
config=ttrlvr_config,
model_path=self.current_model_path
)
self.logger.log_info(f"๐ RemoteTestTimePipeline initialized in {self.execution_mode} mode")
if self.execution_mode == "distributed":
self.logger.log_info(f" - Using VLLM distributed inference on GPU 0,1")
self.logger.log_info(f" - FSDP can use all GPUs: 0,1,2,3 with sharing")
self.logger.log_info(f" - Model loading handled inside Ray worker")
else:
self.logger.log_info(f" - Using HuggingFace single GPU inference inside Ray worker")
except Exception as e:
self.logger.log_error(f"Failed to initialize pipeline: {e}")
raise
def _update_pipeline_model(self, model_path: str):
"""ํ์ดํ๋ผ์ธ์ ๋ชจ๋ธ ๋ ํผ๋ฐ์ค ์
๋ฐ์ดํธ (๋ฉ๋ชจ๋ฆฌ ๋ด ๋์ผ ๋ชจ๋ธ ์ ์ง)"""
try:
# Ray Actor ํ์ดํ๋ผ์ธ์ด ์์ผ๋ฉด ์ด๊ธฐํ
if self.remote_pipeline is None:
self._initialize_pipeline()
# ๋ชจ๋ธ ๊ฒฝ๋ก ์
๋ฐ์ดํธ (Ray worker๋ ์๋ก์ด ๋ชจ๋ธ ๊ฒฝ๋ก๋ก ์ฌ์์ฑ)
self.current_model_path = model_path
self.logger.log_info(f"๐ Pipeline model path updated to: {model_path}")
# ์๋ก์ด ๋ชจ๋ธ์ด๋ฉด Ray Actor ์ฌ์์ฑ
if hasattr(self, '_last_model_path') and self._last_model_path != model_path:
self.logger.log_info("๐ Model path changed, recreating Ray Actor")
self.remote_pipeline = None
self._initialize_pipeline()
self._last_model_path = model_path
except Exception as e:
self.logger.log_warning(f"Failed to update pipeline model: {e}")
def _train_azr_with_round_data(self, training_data_files: List[Dict[str, Any]],
round_num: int) -> Optional[str]:
"""ํด๋น ๋ผ์ด๋ ๋ฐ์ดํฐ๋ก ๋ฉ๋ชจ๋ฆฌ ๋ด ๋ชจ๋ธ ์
๋ฐ์ดํธ"""
try:
# 1. ๋ผ์ด๋๋ณ ํตํฉ ๋ฐ์ดํฐ ์์ฑ
combined_data_path = self._combine_round_data(training_data_files, round_num)
if not combined_data_path:
self.logger.log_error(f"Failed to combine training data for round {round_num}")
return None
self.logger.log_info(f"๐ Combined training data: {combined_data_path}")
# 2. ๋ฉ๋ชจ๋ฆฌ ๋ด์์ ์ง์ ๋ชจ๋ธ ์
๋ฐ์ดํธ (๋์คํฌ ์ ์ฅ/๋ก๋ ์์)
updated_model = self._update_model_in_memory(combined_data_path, round_num)
if updated_model:
# ๋ฉ๋ชจ๋ฆฌ ๋ด ๋ชจ๋ธ ์ธ์คํด์ค ์
๋ฐ์ดํธ
self.current_model = updated_model
# ํ์ดํ๋ผ์ธ ์ปดํฌ๋ํธ๋ค๋ ์
๋ฐ์ดํธ๋ ๋ชจ๋ธ ์ฌ์ฉ
if self.complete_pipeline:
self.complete_pipeline.model = self.current_model
if hasattr(self.complete_pipeline, 'solution_generator') and self.complete_pipeline.solution_generator:
self.complete_pipeline.solution_generator.model = self.current_model
if hasattr(self.complete_pipeline, 'ipo_extractor') and self.complete_pipeline.ipo_extractor:
self.complete_pipeline.ipo_extractor.model = self.current_model
# ์ฐธ์กฐ์ฉ ๊ฒฝ๋ก ์
๋ฐ์ดํธ
virtual_model_path = f"memory://round_{round_num}_model"
self.logger.log_info(f"โ
Model updated in memory for round {round_num}")
self.logger.log_info(f"๐ฏ Virtual model path: {virtual_model_path}")
return virtual_model_path
else:
self.logger.log_error(f"โ Model update failed for round {round_num}")
return None
except Exception as e:
self.logger.log_error(f"๐ฅ Model update execution failed: {e}")
return None
def _update_model_in_memory(self, training_data_path: str, round_num: int) -> Optional[Any]:
"""๋ฉ๋ชจ๋ฆฌ ๋ด์์ VeRL์ ์ฌ์ฉํ์ฌ ๋ชจ๋ธ์ ์ง์ ์
๋ฐ์ดํธ (AZR REINFORCE++ ํ์ต)"""
try:
self.logger.log_info(f"๐ Starting VeRL-based AZR training for round {round_num}")
self.logger.log_info(f"๐ Training data: {training_data_path}")
# ๊ฐ๋จํ ์ฒดํฌ: ํ์ต ๋ฐ์ดํฐ๊ฐ ์กด์ฌํ๋์ง ํ์ธ
task_files = ['induction.parquet', 'deduction.parquet', 'abduction.parquet']
available_files = []
for task_file in task_files:
file_path = os.path.join(training_data_path, task_file)
if os.path.exists(file_path):
available_files.append(task_file)
# ํ์ผ ํฌ๊ธฐ ํ์ธ
file_size = os.path.getsize(file_path)
self.logger.log_info(f" ๐ {task_file}: {file_size} bytes")
if not available_files:
self.logger.log_warning("โ ๏ธ No training data files found in specified directory")
# ์ค์ ์์ฑ๋ ๋ฐ์ดํฐ ๋๋ ํ ๋ฆฌ ๊ฒ์
self.logger.log_info("๐ Searching for actual training data...")
actual_data_path = self._find_actual_training_data()
if actual_data_path:
self.logger.log_info(f"โ
Found actual training data: {actual_data_path}")
training_data_path = actual_data_path
# ๋ค์ ํ์ผ ํ์ธ
for task_file in task_files:
file_path = os.path.join(training_data_path, task_file)
if os.path.exists(file_path):
available_files.append(task_file)
file_size = os.path.getsize(file_path)
self.logger.log_info(f" ๐ {task_file}: {file_size} bytes")
else:
self.logger.log_error("โ No actual training data found anywhere")
return None
self.logger.log_info(f"๐ Processing {len(available_files)} task types")
# โญ Step 1-4๊ฐ ์๋ฃ๋์์ผ๋ฏ๋ก VLLM Ray Actor ํด์ ํ์ฌ ๋ฉ๋ชจ๋ฆฌ ํ๋ณด
if hasattr(self, 'remote_pipeline') and self.remote_pipeline is not None:
self.logger.log_info("๐งน Releasing VLLM Ray Actor memory before Step 5...")
try:
# ๋จผ์ cleanup ๋ฉ์๋ ํธ์ถํ์ฌ ๋ด๋ถ ๋ฆฌ์์ค ์ ๋ฆฌ
cleanup_result = ray.get(self.remote_pipeline.cleanup.remote())
if cleanup_result:
self.logger.log_info("โ
VLLM internal resources cleaned up")
# ๊ทธ ๋ค์ Ray Actor ์ข
๋ฃ
ray.kill(self.remote_pipeline)
self.remote_pipeline = None
self.logger.log_info("โ
VLLM Ray Actor killed successfully")
# GPU ๋ฉ๋ชจ๋ฆฌ ์ ๋ฆฌ
import torch
torch.cuda.empty_cache()
# ์ ์ ๋๊ธฐํ์ฌ ๋ฉ๋ชจ๋ฆฌ๊ฐ ์์ ํ ํด์ ๋๋๋ก ํจ
import time
time.sleep(2)
# GPU ๋ฉ๋ชจ๋ฆฌ ์ํ ํ์ธ
if torch.cuda.is_available():
for i in range(torch.cuda.device_count()):
memory_allocated = torch.cuda.memory_allocated(i) / 1024**3
memory_reserved = torch.cuda.memory_reserved(i) / 1024**3
self.logger.log_info(f" GPU {i}: Allocated={memory_allocated:.2f}GB, Reserved={memory_reserved:.2f}GB")
except Exception as e:
self.logger.log_warning(f"โ ๏ธ Error during VLLM cleanup: {e}")
# VeRL trainer ์ด๊ธฐํ (์ฒซ ๋ฒ์งธ ๋ผ์ด๋์์๋ง)
if self.verl_trainer is None:
self._initialize_verl_trainer(training_data_path)
else:
# ๊ธฐ์กด trainer์์ ๋ฐ์ดํฐ๋ง ์
๋ฐ์ดํธ
self._update_verl_trainer_data(training_data_path)
if self.verl_trainer is None:
self.logger.log_error("Failed to initialize VeRL trainer")
return self.current_model
# VeRL ๋ฉ๋ชจ๋ฆฌ ๋ด ํ์ต ์คํ
self.logger.log_info(f"๐ Starting in-memory VeRL training for round {round_num}")
# ํ์ต ์ค ์์ฑ๋ ์๋ต์ ์ ์ฅํ ๋๋ ํ ๋ฆฌ ์ค์
llm_responses_dir = os.path.join(os.path.dirname(training_data_path), "llm_responses")
os.makedirs(llm_responses_dir, exist_ok=True)
self.logger.log_info(f"๐ LLM responses will be saved to: {llm_responses_dir}")
# VeRL config์ rollout ๋ฐ์ดํฐ ์ ์ฅ ๊ฒฝ๋ก ์ค์
self.verl_config.trainer.rollout_data_dir = llm_responses_dir
# Epoch ์ ๋์ ์กฐ์ (ํ์์)
if hasattr(self, 'batch_epochs') and self.batch_epochs > 1:
original_epochs = self.verl_config.trainer.total_epochs
self.verl_config.trainer.total_epochs = self.batch_epochs
self.logger.log_info(f"๐ง Adjusted epochs from {original_epochs} to {self.batch_epochs}")
# main_azr_ppo.py์ฒ๋ผ ppo_mini_batch_size ์๋ ๊ณ์ฐ (์ค์!)
train_batch_size = self.verl_config.data.train_batch_size
problem_types = getattr(self.verl_config.azr, 'problem_types', ['code_i', 'code_o', 'code_f'])
train_propose = getattr(self.verl_config.azr, 'train_propose', False)
# ์๋ ๊ฐ ์ ์ฅ
original_ppo_mini_batch_size = self.verl_config.actor_rollout_ref.actor.ppo_mini_batch_size
# ์๋ ๊ณ์ฐ: train_batch_size * problem_types ๊ฐ์ * (propose ์ฌ๋ถ)
calculated_ppo_mini_batch_size = train_batch_size * len(problem_types) * (2 if train_propose else 1)
self.verl_config.actor_rollout_ref.actor.ppo_mini_batch_size = calculated_ppo_mini_batch_size
# data_len๋ ์๋ ๊ณ์ฐ (main_azr_ppo.py์ ๋์ผ)
update_iteration = getattr(self.verl_config.azr.data_selection_strategy, 'update_iteration', 1)
self.verl_config.azr.data_selection_strategy.data_len = train_batch_size * update_iteration
self.logger.log_info(f"๐ง Auto-calculated ppo_mini_batch_size: {original_ppo_mini_batch_size} โ {calculated_ppo_mini_batch_size}")
self.logger.log_info(f" - train_batch_size: {train_batch_size}")
self.logger.log_info(f" - problem_types: {len(problem_types)} ({problem_types})")
self.logger.log_info(f" - train_propose: {train_propose}")
self.logger.log_info(f"๐ง Auto-calculated data_len: {self.verl_config.azr.data_selection_strategy.data_len}")
# VeRL ํ์ต ์คํ
self.logger.log_info(f"๐ Calling verl_trainer.fit() for round {round_num}")
self.logger.log_info(f"๐ Config - total_epochs: {self.verl_config.trainer.total_epochs}")
self.logger.log_info(f"๐ Config - train_batch_size: {self.verl_config.data.train_batch_size}")
self.logger.log_info(f"๐ Config - total_training_steps: {self.verl_config.trainer.total_training_steps}")
# trainer ์ธ์คํด์ค์ config๋ ์
๋ฐ์ดํธ (์ค์!)
if hasattr(self.verl_trainer, 'config'):
self.verl_trainer.config.trainer.rollout_data_dir = llm_responses_dir
# ์ค์ fit ํธ์ถ
fit_start = datetime.now()
self.verl_trainer.fit()
fit_end = datetime.now()
fit_duration = (fit_end - fit_start).total_seconds()
self.logger.log_info(f"โฑ๏ธ verl_trainer.fit() completed in {fit_duration:.3f} seconds")
# JSONL ํ์ผ๋ค์ TTRLVR ํ์์ผ๋ก ๋ณํ
if os.path.exists(llm_responses_dir):
self.logger.log_info("๐ Converting VeRL outputs to TTRLVR format...")
jsonl_files = list(Path(llm_responses_dir).glob("*.jsonl"))
for jsonl_file in jsonl_files:
self._convert_jsonl_to_ttrlvr_format(str(jsonl_file), llm_responses_dir)
self.logger.log_info(f"โ
Converted {len(jsonl_files)} JSONL files to TTRLVR format")
# ํ์ต๋ ๋ชจ๋ธ์ ์ด๋ฏธ VeRL trainer ๋ด๋ถ์์ ์
๋ฐ์ดํธ๋จ
# ๋ชจ๋ธ ์ธ์คํด์ค๋ ๋ฉ๋ชจ๋ฆฌ์์ ๊ณ์ ์ ์ง๋จ
self.logger.log_info(f"โ
Model updated successfully with REINFORCE++ for round {round_num}")
# ํ์ต ํ ์ฒดํฌํฌ์ธํธ ์ ์ฅ (์กฐ๊ฑด๋ถ)
if self._should_save_checkpoint(round_num):
self._save_round_checkpoint(round_num)
# ํ์ฌ ๋ชจ๋ธ ๊ฐ์ฒด ๋ฐํ (๊ฐ์ค์น๊ฐ ์
๋ฐ์ดํธ๋จ)
# VeRL์์๋ ๋ชจ๋ธ์ด Ray worker ๋ด๋ถ์์ ์
๋ฐ์ดํธ๋๋ฏ๋ก, ์ฌ๋ณผ๋ฆญ ์ฐธ์กฐ ๋ฐํ
if self.current_model is None:
self.current_model = "verl_trained_model" # ์ฌ๋ณผ๋ฆญ ์ฐธ์กฐ
return self.current_model
except Exception as e:
self.logger.log_error(f"Failed to update model in memory: {e}")
import traceback
traceback.print_exc()
return None
def _combine_round_data(self, training_data_files: List[Dict[str, Any]],
round_num: int) -> Optional[str]:
"""๋ผ์ด๋์ ๋ชจ๋ ๋ฌธ์ ๋ฐ์ดํฐ๋ฅผ task๋ณ๋ก ํตํฉ"""
try:
# ํตํฉ ๋ฐ์ดํฐ ์ ์ฅ ๋๋ ํ ๋ฆฌ
output_dir = f"/tmp/ttrlvr_azr_training/round_{round_num}"
os.makedirs(output_dir, exist_ok=True)
# Task ํ์
๋ณ ๋ฐ์ดํฐ ์์ง
combined_data = {
'induction': [],
'deduction': [],
'abduction': []
}
total_files_processed = 0
# ๊ฐ ๋ฌธ์ ์ ๋ฐ์ดํฐ ํ์ผ๋ค์ ์ํ
for problem_data in training_data_files:
problem_id = problem_data['problem_id']
files = problem_data['files']
self.logger.log_info(f"๐ Processing data for {problem_id}")
# Task ํ์
๋ณ ํ์ผ ์ฒ๋ฆฌ
for task_type in ['induction', 'deduction', 'abduction']:
if task_type in files:
file_path = files[task_type]
if os.path.exists(file_path):
try:
df = pd.read_parquet(file_path)
task_data = df.to_dict('records')
combined_data[task_type].extend(task_data)
total_files_processed += 1
self.logger.log_info(f" โ
{task_type}: {len(task_data)} tasks from {file_path}")
except Exception as e:
self.logger.log_warning(f" โ ๏ธ Failed to read {file_path}: {e}")
else:
self.logger.log_warning(f" โ ๏ธ File not found: {file_path}")
if total_files_processed == 0:
self.logger.log_error("No training data files found to combine")
return None
# ํตํฉ๋ ๋ฐ์ดํฐ๋ฅผ task๋ณ parquet ํ์ผ๋ก ์ ์ฅ
combined_files = {}
total_tasks = 0
for task_type, data in combined_data.items():
if data:
# ipo_group_id๋ก ์ ๋ ฌํ์ฌ ๋ฐฐ์น ๋ณด์ฅ
df = pd.DataFrame(data)
df = df.sort_values('ipo_group_id')
# ํ์ผ ์ ์ฅ
file_path = os.path.join(output_dir, f"{task_type}.parquet")
df.to_parquet(file_path, index=False)
combined_files[task_type] = file_path
total_tasks += len(data)
self.logger.log_info(f"๐พ Saved {len(data)} {task_type} tasks to {file_path}")
else:
self.logger.log_warning(f"No {task_type} tasks found for round {round_num}")
# ํต๊ณ ์ ์ฅ
stats = {
'round': round_num,
'total_tasks': total_tasks,
'tasks_by_type': {k: len(v) for k, v in combined_data.items()},
'files': combined_files,
'problems_processed': len(training_data_files),
'batch_groups': len(set(
task['ipo_group_id']
for task_data in combined_data.values()
for task in task_data
))
}
stats_file = os.path.join(output_dir, 'round_training_stats.json')
with open(stats_file, 'w') as f:
json.dump(stats, f, indent=2)
self.logger.log_info(f"๐ Round {round_num} data summary:")
self.logger.log_info(f" - Total tasks: {total_tasks}")
self.logger.log_info(f" - Batch groups: {stats['batch_groups']}")
self.logger.log_info(f" - Files: {list(combined_files.keys())}")
return output_dir
except Exception as e:
self.logger.log_error(f"Failed to combine round data: {e}")
return None
def _save_checkpoint(self, round_num: int, model_path: str,
training_results: Dict[str, Any]):
"""์ฒดํฌํฌ์ธํธ ์ ์ฅ (๋ชจ๋ธ ์ํ, ํ์ต ํต๊ณ, ๋ผ์ด๋ ์ ๋ณด)"""
try:
checkpoint_path = os.path.join(self.checkpoint_dir, f"checkpoint_round_{round_num}")
os.makedirs(checkpoint_path, exist_ok=True)
# ์ฒดํฌํฌ์ธํธ ๋ฉํ๋ฐ์ดํฐ
checkpoint_data = {
'round_num': round_num,
'model_path': model_path,
'timestamp': datetime.now().isoformat(),
'total_rounds': training_results.get('total_rounds', 30),
'completed_rounds': round_num,
'training_results': training_results,
'round_times': self.round_times
}
# JSON์ผ๋ก ์ ์ฅ
checkpoint_file = os.path.join(checkpoint_path, 'checkpoint.json')
with open(checkpoint_file, 'w') as f:
json.dump(checkpoint_data, f, indent=2)
# ์์ฝ ํ
์คํธ ํ์ผ ์ ์ฅ
summary_file = os.path.join(checkpoint_path, 'summary.txt')
with open(summary_file, 'w') as f:
f.write(f"TTRLVR + AZR Training Checkpoint - Round {round_num}\n")
f.write("=" * 60 + "\n\n")
f.write(f"Timestamp: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}\n")
f.write(f"Completed Rounds: {round_num}/{training_results.get('total_rounds', 30)}\n")
f.write(f"Current Model: {model_path}\n")
f.write(f"Total Training Time: {sum(self.round_times.values()):.1f} seconds\n\n")
# ๋ผ์ด๋๋ณ ํต๊ณ
f.write("Round Statistics:\n")
f.write("-" * 20 + "\n")
for r_num, r_time in self.round_times.items():
if r_num <= round_num:
round_result = training_results['rounds'].get(r_num, {})
success = "โ
" if round_result.get('success', False) else "โ"
f.write(f"Round {r_num:2d}: {success} ({r_time:.1f}s)\n")
self.logger.log_info(f"๐พ Checkpoint saved: {checkpoint_path}")
except Exception as e:
self.logger.log_error(f"Failed to save checkpoint: {e}")
def _load_checkpoint(self, round_num: int) -> Optional[str]:
"""์ฒดํฌํฌ์ธํธ์์ ๋ชจ๋ธ ๋ก๋"""
try:
checkpoint_path = os.path.join(self.checkpoint_dir, f"checkpoint_round_{round_num}")
checkpoint_file = os.path.join(checkpoint_path, 'checkpoint.json')
if not os.path.exists(checkpoint_file):
self.logger.log_warning(f"Checkpoint not found: {checkpoint_file}")
return None
with open(checkpoint_file, 'r') as f:
checkpoint_data = json.load(f)
model_path = checkpoint_data.get('model_path')
if model_path and os.path.exists(model_path):
self.logger.log_info(f"๐ Loaded checkpoint from round {round_num}")
self.logger.log_info(f"๐ค Model: {model_path}")
# ์ด์ ๋ผ์ด๋ ์๊ฐ ๋ณต์
if 'round_times' in checkpoint_data:
self.round_times.update(checkpoint_data['round_times'])
return model_path
else:
self.logger.log_warning(f"Model path in checkpoint does not exist: {model_path}")
return None
except Exception as e:
self.logger.log_error(f"Failed to load checkpoint: {e}")
return None
def _log_round_summary(self, round_num: int, round_result: Dict[str, Any],
duration: float):
"""๋ผ์ด๋ ์๋ฃ ์์ฝ ๋ก๊ทธ"""
stats = round_result.get('stats', {})
self.logger.log_info(f"")
self.logger.log_info(f"๐ ROUND {round_num} SUMMARY")
self.logger.log_info(f"" + "="*50)
self.logger.log_info(f"โฑ๏ธ Duration: {duration:.1f} seconds")
self.logger.log_info(f"๐ Problems: {stats.get('successful_problems', 0)}/{stats.get('total_problems', 0)} successful")
self.logger.log_info(f"๐ฏ Total tasks: {stats.get('total_tasks', 0)}")
tasks_by_type = stats.get('tasks_by_type', {})
for task_type, count in tasks_by_type.items():
if count > 0:
self.logger.log_info(f" - {task_type}: {count}")
if round_result.get('success'):
self.logger.log_info(f"โ
Round {round_num} completed successfully")
else:
self.logger.log_info(f"โ Round {round_num} failed")
self.logger.log_info(f"")
def _log_final_summary(self, training_results: Dict[str, Any]):
"""์ ์ฒด ํ์ต ์๋ฃ ์์ฝ ๋ก๊ทธ"""
total_duration = training_results.get('total_duration_seconds', 0)
total_rounds = training_results.get('total_rounds', 0)
completed_rounds = len(training_results.get('rounds', {}))
self.logger.log_info(f"")
self.logger.log_info(f"๐ TTRLVR + AZR TRAINING COMPLETED")
self.logger.log_info(f"" + "="*60)
self.logger.log_info(f"โฑ๏ธ Total Duration: {total_duration:.1f} seconds ({total_duration/3600:.1f} hours)")
self.logger.log_info(f"๐ Completed Rounds: {completed_rounds}/{total_rounds}")
self.logger.log_info(f"๐ค Final Model: {training_results.get('final_model', 'N/A')}")
# ๋ผ์ด๋๋ณ ์ฑ๊ณต/์คํจ ํต๊ณ
successful_rounds = 0
failed_rounds = 0
for round_result in training_results['rounds'].values():
if round_result.get('success'):
successful_rounds += 1
else:
failed_rounds += 1
self.logger.log_info(f"๐ Round Statistics:")
self.logger.log_info(f" - Successful: {successful_rounds}")
self.logger.log_info(f" - Failed: {failed_rounds}")
self.logger.log_info(f" - Success Rate: {successful_rounds/completed_rounds*100:.1f}%")
# ํ๊ท ๋ผ์ด๋ ์๊ฐ
if self.round_times:
avg_round_time = sum(self.round_times.values()) / len(self.round_times)
self.logger.log_info(f"โ Average Round Time: {avg_round_time:.1f} seconds")
self.logger.log_info(f"")
self.logger.log_info(f"๐พ All results saved to: {self.checkpoint_dir}")
self.logger.log_info(f"๐ฏ Training completed successfully!")
self.logger.log_info(f"")
def _initialize_verl_trainer(self, training_data_path: str):
"""์ฒซ ๋ฒ์งธ ๋ผ์ด๋์์ VeRL trainer ๋ฐ Ray ํด๋ฌ์คํฐ ์ด๊ธฐํ"""
try:
self.logger.log_info("๐ Initializing VeRL trainer for AZR training")
# Ray ์ด๊ธฐํ (์ ์ฒด ์ธ์
์์ ํ ๋ฒ๋ง)
if not self.ray_initialized:
self.logger.log_info("๐ Initializing Ray cluster for first time")
self._initialize_ray_cluster()
else:
self.logger.log_info("โป๏ธ Using existing Ray cluster")
# VeRL config ๋ก๋ (์์ง ๋ก๋๋์ง ์์ ๊ฒฝ์ฐ)
if not hasattr(self, 'verl_config') or self.verl_config is None:
self._load_verl_config()
# ๋ฐ์ดํฐ ๊ฒฝ๋ก ๋์ ์ค์ (parquet ํ์ผ ๋ฆฌ์คํธ)
train_files = [
os.path.join(training_data_path, "induction.parquet"),
os.path.join(training_data_path, "deduction.parquet"),
os.path.join(training_data_path, "abduction.parquet")
]
# ์กด์ฌํ๋ ํ์ผ๋ง ์ ํ
valid_train_files = [f for f in train_files if os.path.exists(f)]
self.verl_config.data.train_files = valid_train_files
self.verl_config.data.val_files = valid_train_files
# ์ฒดํฌํฌ์ธํธ ๋นํ์ฑํ๋ก ์ธํด ๊ณ ์ ๋๋ ํ ๋ฆฌ ์ค์ ๋ถํ์
# VeRL์ด ๊ธฐ์กด ๋ชจ๋ธ ์ธ์คํด์ค๋ฅผ ์ฌ์ฉํ๋๋ก ์ค์ (๋ฉ๋ชจ๋ฆฌ ์ ์ฝ)
# Config์๋ ์๋ณธ ๊ฒฝ๋ก ์ ์ง (tokenizer ๋ก๋์ฉ)
self.verl_config.actor_rollout_ref.model.path = self.original_model_name
self.logger.log_info(f"๐ง VeRL config set to original model path: {self.original_model_name}")
# TTRLVR ๋ฐ์ดํฐ ์์ฑ์์ ์ฌ์ฉํ ์์ง ์ค์ ์ถ๊ฐ
inference_engine = getattr(self.verl_config.data, 'ttrlvr_inference_engine', 'vllm')
self.logger.log_info(f"๐ง TTRLVR inference engine: {inference_engine}")
self.logger.log_info(f"๐ VeRL config loaded successfully")
self.logger.log_info(f"๐ Training data files: {len(self.verl_config.data.train_files)}")
# VeRL trainer ์์ฑ์ ์ํ ํ์ ๊ตฌ์ฑ ์์๋ค ์ค๋น
from transformers import AutoTokenizer
from verl.trainer.ppo.ray_trainer import ResourcePoolManager, Role
# Worker ํด๋์ค๋ค import (main_azr_ppo.py์ ๋์ผ)
import ray
# VeRL ๋ก๊น
์ TTRLVR ๋ก๊ทธ์ ํตํฉ
import logging
# ์ฌ๋ฌ VeRL ๊ด๋ จ ๋ก๊ฑฐ๋ค ์ค์
verl_loggers = [
"verl",
"verl.workers",
"verl.trainer",
"verl.workers.fsdp_workers",
"verl.workers.sharding_manager",
"absolute_zero_reasoner.trainer.ppo"
]
# TTRLVR ๋ก๊ทธ ํ์ผ์ VeRL ๋ก๊ทธ ์ถ๊ฐ
if hasattr(self.logger, 'log_file_path') and self.logger.log_file_path:
file_handler = logging.FileHandler(self.logger.log_file_path)
file_handler.setFormatter(logging.Formatter('[VeRL] %(asctime)s - %(name)s - %(levelname)s - %(message)s'))
for logger_name in verl_loggers:
verl_logger = logging.getLogger(logger_name)
verl_logger.setLevel(logging.INFO)
verl_logger.addHandler(file_handler)
# strategy ํ์ธ
strategy = self.verl_config.actor_rollout_ref.actor.strategy
self.logger.log_info(f"๐ง Actor strategy: {strategy}")
if strategy in ["fsdp", "fsdp2"]:
from verl.single_controller.ray import RayWorkerGroup
from verl.workers.fsdp_workers import ActorRolloutRefWorker, AsyncActorRolloutRefWorker, CriticWorker
# VeRL worker ์ ํ (AZR๊ณผ ๋์ผํ๊ฒ ๋งค๋ฒ ์๋ก์ด vLLM ์์ฑ)
actor_rollout_cls = AsyncActorRolloutRefWorker if self.verl_config.actor_rollout_ref.rollout.mode == "async" else ActorRolloutRefWorker
ray_worker_group_cls = RayWorkerGroup
elif strategy == "none":
# ๋จ์ผ GPU ํ๊ฒฝ - FSDP worker๋ฅผ ์ฌ์ฉํ๋ FSDP๋ ๋นํ์ฑํ
self.logger.log_info("๐ง Using single GPU configuration (FSDP workers without FSDP)")
from verl.single_controller.ray import RayWorkerGroup
from verl.workers.fsdp_workers import ActorRolloutRefWorker, AsyncActorRolloutRefWorker, CriticWorker
# ๋จ์ผ GPU์์๋ FSDP worker ์ฌ์ฉ (FSDP๋ ๋ด๋ถ์์ ๋นํ์ฑํ๋จ)
actor_rollout_cls = AsyncActorRolloutRefWorker if self.verl_config.actor_rollout_ref.rollout.mode == "async" else ActorRolloutRefWorker
ray_worker_group_cls = RayWorkerGroup
else:
raise NotImplementedError(f"Strategy '{strategy}' not supported. Supported: fsdp, fsdp2, none")
# Tokenizer ์ด๊ธฐํ (์๋ณธ ๋ชจ๋ธ ๊ฒฝ๋ก ์ฌ์ฉ)
if self.current_model_path.startswith('memory://'):
# ๊ฐ์ ๊ฒฝ๋ก์ธ ๊ฒฝ์ฐ ์๋ณธ ๋ชจ๋ธ ๊ฒฝ๋ก ์ฌ์ฉ
tokenizer_path = self.original_model_name
self.logger.log_info(f"๐ง Using original model path for tokenizer: {self.original_model_name}")
else:
tokenizer_path = self.current_model_path
tokenizer = AutoTokenizer.from_pretrained(tokenizer_path)
if tokenizer.pad_token is None:
tokenizer.pad_token = tokenizer.eos_token
# Resource pool spec ์ค์ (VeRL API์ ๋ง๊ฒ)
resource_pool_spec = {
"actor_rollout": [0], # GPU 0 ์ฌ์ฉ
"critic": [0],
"ref": [0],
"reward": [0]
}
# Role mapping ์ค์ (main_azr_ppo.py์ ๋์ผํ๊ฒ ray.remote๋ก ๋ํ)
role_worker_mapping = {
Role.ActorRollout: ray.remote(actor_rollout_cls),
Role.Critic: ray.remote(CriticWorker),
}
# Resource pool manager ์ด๊ธฐํ (main_azr_ppo.py์ ๋์ผํ API)
global_pool_id = "global_pool"
resource_pool_spec = {
global_pool_id: [self.verl_config.trainer.n_gpus_per_node] * self.verl_config.trainer.nnodes,
}
mapping = {
Role.ActorRollout: global_pool_id,
Role.Critic: global_pool_id,
}
resource_pool_manager = ResourcePoolManager(
resource_pool_spec=resource_pool_spec,
mapping=mapping
)
# โญ ํต์ฌ: VeRL trainer ์์ฑ ์ ์ total_training_steps ๋ฏธ๋ฆฌ ๊ณ์ฐ
self.logger.log_info("๐ข Pre-calculating total_training_steps before trainer creation")
# ๋ฐ์ดํฐ๋ก๋ ํฌ๊ธฐ ์์ ๊ณ์ฐ (parquet ํ์ผ ๊ธฐ๋ฐ)
import pandas as pd
task_files = ['induction.parquet', 'deduction.parquet', 'abduction.parquet']
task_dataloader_sizes = []
for task_file in task_files:
file_path = os.path.join(training_data_path, task_file)
if os.path.exists(file_path):
df = pd.read_parquet(file_path)
train_batch_size = self.verl_config.data.train_batch_size
task_dataloader_size = (len(df) + train_batch_size - 1) // train_batch_size
task_dataloader_sizes.append(task_dataloader_size)
self.logger.log_info(f" ๐ {task_file}: {len(df)} samples โ {task_dataloader_size} batches")
# TTRLVR์์๋ ๋ชจ๋ task์์ ๋์์ ๋ฐฐ์น๋ฅผ ๊ฐ์ ธ์์ผ ํ๋ฏ๋ก ์ต์๊ฐ ์ฌ์ฉ
if task_dataloader_sizes:
estimated_dataloader_size = min(task_dataloader_sizes)
estimated_total_training_steps = estimated_dataloader_size * self.verl_config.trainer.total_epochs
self.logger.log_info(f" ๐ข Min dataloader size: {estimated_dataloader_size}, Total steps: {estimated_total_training_steps}")
else:
estimated_total_training_steps = 100 # fallback
self.logger.log_info(f"๐ Pre-calculated training steps:")
self.logger.log_info(f" - Task dataloader sizes: {task_dataloader_sizes}")
self.logger.log_info(f" - Min dataloader size: {estimated_dataloader_size}")
self.logger.log_info(f" - Total epochs: {self.verl_config.trainer.total_epochs}")
self.logger.log_info(f" - Estimated total_training_steps: {estimated_total_training_steps}")
# VeRL config์ ๋ฏธ๋ฆฌ ์ฃผ์
(VeRL trainer ์์ฑ ์ ์!)
from omegaconf import OmegaConf, open_dict
OmegaConf.set_struct(self.verl_config, True)
with open_dict(self.verl_config):
# Actor optim์ ์ฃผ์
self.verl_config.actor_rollout_ref.actor.optim.total_training_steps = estimated_total_training_steps
# Trainer ๋ ๋ฒจ์๋ ์ฃผ์
(VeRL์ด ์ด ๊ฐ์ ์ฐธ์กฐํจ)
self.verl_config.trainer.total_training_steps = estimated_total_training_steps
# Critic ์ฌ์ฉ์ ์ฃผ์
if hasattr(self.verl_config, 'critic') and self.verl_config.critic.get('include_critic', False):
self.verl_config.critic.optim.total_training_steps = estimated_total_training_steps
self.logger.log_info(f"โ
Injected total_training_steps={estimated_total_training_steps} into config before trainer creation")
# ์ฃผ์
๋ ๊ฐ ํ์ธ
actor_value = OmegaConf.select(self.verl_config, "actor_rollout_ref.actor.optim.total_training_steps")
trainer_value = OmegaConf.select(self.verl_config, "trainer.total_training_steps")
self.logger.log_info(f"๐ Verification: actor.optim.total_training_steps = {actor_value}")
self.logger.log_info(f"๐ Verification: trainer.total_training_steps = {trainer_value}")
# VeRL trainer ์์ฑ (main_azr_ppo.py์ ๋์ผํ ๋ฐฉ์)
self.logger.log_info("๐ Creating new VLLM for VeRL (AZR pattern)")
self.verl_trainer = CodeIORayPPOTrainer(
config=self.verl_config,
tokenizer=tokenizer,
role_worker_mapping=role_worker_mapping,
resource_pool_manager=resource_pool_manager,
ray_worker_group_cls=ray_worker_group_cls
)
# โญ ํต์ฌ: Worker ์ด๊ธฐํ (main_azr_ppo.py์ ๋์ผ)
self.logger.log_info("๐ง Initializing VeRL workers...")
self.verl_trainer.init_workers()
self.logger.log_info("โ
VeRL workers initialized")
# โญ ๊ฒ์ฆ: ์ค์ dataloader ํฌ๊ธฐ์ ๋น๊ต
self.logger.log_info(f"๐ Verifying dataloader after trainer creation:")
if hasattr(self.verl_trainer, 'train_dataloader'):
actual_dataloader_size = len(self.verl_trainer.train_dataloader) if self.verl_trainer.train_dataloader else 0
self.logger.log_info(f" - Actual dataloader size: {actual_dataloader_size}")
self.logger.log_info(f" - Estimated dataloader size: {estimated_dataloader_size}")
if actual_dataloader_size != estimated_dataloader_size:
self.logger.log_warning(f"โ ๏ธ Dataloader size mismatch! Estimated: {estimated_dataloader_size}, Actual: {actual_dataloader_size}")
else:
self.logger.log_info("โ
Dataloader size estimation was correct")
else:
self.logger.log_warning("โ ๏ธ No train_dataloader found after trainer creation")
# โญ ํต์ฌ: VeRL trainer์ ๋ชจ๋ธ์ ๊ธฐ์กด ์ธ์คํด์ค๋ก ๊ต์ฒด (๋ฉ๋ชจ๋ฆฌ ์ ์ฝ)
self._replace_verl_model_with_existing_instance()
self.logger.log_info("โ
VeRL trainer initialized successfully")
except Exception as e:
self.logger.log_error(f"Failed to initialize VeRL trainer: {e}")
import traceback
traceback.print_exc()
self.verl_trainer = None
def _replace_verl_model_with_existing_instance(self):
"""VeRL trainer์ ๋ชจ๋ธ์ ๊ธฐ์กด ์ธ์คํด์ค๋ก ๊ต์ฒดํ์ฌ ๋ฉ๋ชจ๋ฆฌ ์ ์ฝ"""
try:
self.logger.log_info("๐ Replacing VeRL models with existing instance for memory efficiency")
# Actor ๋ชจ๋ธ ๊ต์ฒด
if hasattr(self.verl_trainer, 'actor_rollout_ref'):
if hasattr(self.verl_trainer.actor_rollout_ref, 'actor'):
if hasattr(self.verl_trainer.actor_rollout_ref.actor, 'model'):
# ๊ธฐ์กด VeRL ๋ชจ๋ธ ์ญ์ (๋ฉ๋ชจ๋ฆฌ ํด์ )
del self.verl_trainer.actor_rollout_ref.actor.model
# ๊ธฐ์กด ์ธ์คํด์ค๋ก ๊ต์ฒด
self.verl_trainer.actor_rollout_ref.actor.model = self.current_model
self.logger.log_info("โ
Actor model replaced with existing instance")
# Rollout ๋ชจ๋ธ๋ ๋์ผํ๊ฒ ๊ต์ฒด (ํ์์)
if hasattr(self.verl_trainer.actor_rollout_ref, 'rollout'):
if hasattr(self.verl_trainer.actor_rollout_ref.rollout, 'llm'):
# VLLM ์์ง์ด ์๋ ๊ฒฝ์ฐ ๊ธฐ์กด ๋ชจ๋ธ๊ณผ ์ฐ๊ฒฐ
self.logger.log_info("๐ง Rollout engine detected - using existing model weights")
# ๋ฉ๋ชจ๋ฆฌ ์ ๋ฆฌ
import torch
if torch.cuda.is_available():
torch.cuda.empty_cache()
current_memory = torch.cuda.memory_allocated() / 1024**3
self.logger.log_info(f"๐ GPU memory after model replacement: {current_memory:.1f}GB")
self.logger.log_info("๐ฏ Single model instance now used across all steps (1-5)!")
except Exception as e:
self.logger.log_warning(f"Model replacement failed, using default VeRL behavior: {e}")
# ์คํจํด๋ VeRL์ด ์์ฒด ๋ชจ๋ธ์ ์ฌ์ฉํ๋ฏ๋ก ๊ณ์ ์งํ
def _update_verl_trainer_data(self, training_data_path: str):
"""๊ธฐ์กด VeRL trainer์์ ๋ฐ์ดํฐ ๊ฒฝ๋ก๋ง ์
๋ฐ์ดํธ"""
try:
self.logger.log_info("๐ Updating VeRL trainer data for new round")
# ๋ฐ์ดํฐ ๊ฒฝ๋ก ์
๋ฐ์ดํธ
new_train_files = [
os.path.join(training_data_path, "induction.parquet"),
os.path.join(training_data_path, "deduction.parquet"),
os.path.join(training_data_path, "abduction.parquet")
]
# ์กด์ฌํ๋ ํ์ผ๋ง ์ ํ
valid_files = [f for f in new_train_files if os.path.exists(f)]
if not valid_files:
self.logger.log_warning("โ ๏ธ No valid training files found for update")
return
# Config ์
๋ฐ์ดํธ
self.verl_config.data.train_files = valid_files
self.verl_config.data.val_files = valid_files
# Trainer์ ๋ฐ์ดํฐ ๋ก๋ ์
๋ฐ์ดํธ
if hasattr(self.verl_trainer, 'update_data_files'):
self.verl_trainer.update_data_files(valid_files)
else:
# Trainer ๋ด๋ถ์ config ์
๋ฐ์ดํธ
self.verl_trainer.config.data.train_files = valid_files
self.verl_trainer.config.data.val_files = valid_files
self.logger.log_info(f"โ
Updated training data: {len(valid_files)} files")
# โญ ์ค์: ๋ฐ์ดํฐ๊ฐ ๋ณ๊ฒฝ๋์์ผ๋ฏ๋ก worker๋ฅผ ์ฌ์ด๊ธฐํํด์ผ ํจ
self.logger.log_info("๐ง Re-initializing VeRL workers with new data...")
self.verl_trainer.init_workers()
self.logger.log_info("โ
VeRL workers re-initialized with actual training data")
except Exception as e:
self.logger.log_error(f"Failed to update VeRL trainer data: {e}")
import traceback
traceback.print_exc()
def _load_verl_config(self):
"""VeRL config ๋ก๋ - ๊ธฐ์กด YAML ํ์ผ ์ฌ์ฉ"""
try:
# VeRL config ํ์ผ ๊ฒฝ๋ก ์ค์ (์คํ ๋ชจ๋์ ๋ฐ๋ผ ์๋ ์ ํ)
if self.verl_config_path:
config_path = self.verl_config_path
else:
config_path = self._get_default_config_path()
self.logger.log_info(f"๐ง Loading VeRL config from: {config_path}")
self.logger.log_info(f"๐ง Config selected for {self.execution_mode} mode")
from omegaconf import OmegaConf
import os
if not os.path.exists(config_path):
raise FileNotFoundError(f"Config file not found: {config_path}")
# YAML ํ์ผ ๋ก๋
self.verl_config = OmegaConf.load(config_path)
# ๋ชจ๋ธ ๊ฒฝ๋ก๋ฅผ ์ค์ HuggingFace ๊ฒฝ๋ก๋ก ์ค์
if hasattr(self, 'current_model_path') and self.current_model_path:
if self.current_model_path.startswith('memory://'):
# ๊ฐ์ ๊ฒฝ๋ก์ธ ๊ฒฝ์ฐ ์๋ณธ ๋ชจ๋ธ ๊ฒฝ๋ก ์ฌ์ฉ
model_path_for_verl = self.original_model_name
self.logger.log_info(f"๐ง Using original model path for VeRL: {model_path_for_verl}")
else:
model_path_for_verl = self.current_model_path
self.verl_config.actor_rollout_ref.model.path = model_path_for_verl
self.logger.log_info(f"๐ง Updated VeRL model path to: {model_path_for_verl}")
self.logger.log_info("โ
VeRL config loaded successfully from YAML")
self.logger.log_info(f" - TTRLVR Ray parallel processing: {self.verl_config.data.ttrlvr_ray_config.parallel_processing}")
self.logger.log_info(f" - TTRLVR inference engine: {self.verl_config.data.ttrlvr_inference_engine}")
except Exception as e:
self.logger.log_error(f"Config loading failed: {e}")
self.verl_config = None
def _detect_available_gpus(self):
"""์ฌ์ฉ ๊ฐ๋ฅํ GPU ๋ฆฌ์คํธ ๊ฐ์ง"""
import os
cuda_visible_devices = os.environ.get('CUDA_VISIBLE_DEVICES', '0')
if cuda_visible_devices:
return [int(gpu.strip()) for gpu in cuda_visible_devices.split(',') if gpu.strip()]
else:
return [0] # ๊ธฐ๋ณธ๊ฐ
def _determine_execution_mode(self):
"""GPU ๊ฐ์์ ๋ฐ๋ฅธ ์คํ ๋ชจ๋ ๊ฒฐ์ """
num_gpus = len(self.available_gpus)
if num_gpus == 1:
return "single_gpu" # ์ ์ฒด ํ์ดํ๋ผ์ธ ๋จ์ผ GPU
else:
return "distributed" # ์ ์ฒด ํ์ดํ๋ผ์ธ ๋ถ์ฐ GPU
def _get_default_config_path(self):
"""์คํ ๋ชจ๋์ ๋ฐ๋ฅธ ๊ธฐ๋ณธ config ํ์ผ ๊ฒฝ๋ก ๋ฐํ"""
base_path = "/home/ubuntu/RLVR/TestTime-RLVR-v2/test/configs"
if self.execution_mode == "single_gpu":
return f"{base_path}/ttrlvr_azr_ppo.yaml" # ๋จ์ผ GPU config
else:
return f"{base_path}/ttrlvr_azr_ppo_4gpu.yaml" # ๋ค์ค GPU config
def _should_save_checkpoint(self, round_num: int) -> bool:
"""์ฒดํฌํฌ์ธํธ ์ ์ฅ ์ฌ๋ถ ๊ฒฐ์ """
if self.save_every_round:
return True
if round_num % self.save_round_interval == 0:
return True
return False
def _convert_jsonl_to_ttrlvr_format(self, jsonl_path: str, output_dir: str):
"""VeRL์ JSONL ์ถ๋ ฅ์ TTRLVR ํ์์ ๊ฐ๋ณ ํ
์คํธ ํ์ผ๋ก ๋ณํ"""
import json
try:
with open(jsonl_path, 'r') as f:
data = json.load(f)
# ๊ฐ ์ํ์ ๋ํด ๊ฐ๋ณ ํ์ผ ์์ฑ
for i in range(len(data.get('input', []))):
prompt = data['input'][i] if 'input' in data else ""
response = data['output'][i] if 'output' in data else ""
score = data['score'][i] if 'score' in data else 0.0
# ํ๋กฌํํธ์์ task type ์ถ์ถ (induction/deduction/abduction)
task_type = "unknown"
if "induction" in prompt.lower() or "input/output pairs" in prompt:
task_type = "induction"
elif "deduction" in prompt.lower() or "observed output" in prompt:
task_type = "deduction"
elif "abduction" in prompt.lower() or "which input produces" in prompt:
task_type = "abduction"
# task type๋ณ ์๋ธ๋๋ ํ ๋ฆฌ ์์ฑ
task_dir = os.path.join(output_dir, task_type)
os.makedirs(task_dir, exist_ok=True)
# ํ์ผ๋ช
์์ฑ
filename = f"verl_training_{task_type}_{self.response_counter}_response.txt"
filepath = os.path.join(task_dir, filename)
# TTRLVR ํ์์ผ๋ก ์ ์ฅ
with open(filepath, 'w') as f:
f.write(f"Task Type: {task_type}\n")
f.write(f"Task ID: verl_step_{data.get('step', 0)[i]}_{i}\n")
f.write(f"Generated: {datetime.now().strftime('%Y%m%d_%H%M%S')}\n")
f.write("="*80 + "\n")
f.write("ORIGINAL PROMPT:\n")
f.write("="*80 + "\n")
f.write(prompt + "\n")
f.write("="*80 + "\n")
f.write("LLM RESPONSE:\n")
f.write("="*80 + "\n")
f.write(response + "\n")
f.write("="*80 + "\n")
f.write("REWARD SCORE:\n")
f.write("="*80 + "\n")
f.write(f"Score: {score:.3f}\n")
# ์ถ๊ฐ ์ ๋ณด๊ฐ ์์ผ๋ฉด ํฌํจ
for key in data.keys():
if key not in ['input', 'output', 'score', 'step'] and isinstance(data[key], list):
f.write("="*80 + "\n")
f.write(f"{key.upper()}:\n")
f.write("="*80 + "\n")
f.write(f"{data[key][i] if i < len(data[key]) else 'N/A'}\n")
self.response_counter += 1
except Exception as e:
self.logger.log_error(f"Failed to convert JSONL to TTRLVR format: {e}")
def _save_round_checkpoint(self, round_num: int):
"""๋งค ๋ผ์ด๋๋ง๋ค VeRL ์ฒดํฌํฌ์ธํธ ์ ์ฅ"""
try:
if hasattr(self, 'verl_trainer') and self.verl_trainer:
# VeRL trainer์ ์ฒดํฌํฌ์ธํธ ์ ์ฅ ๋ฉ์๋ ํธ์ถ
checkpoint_path = f"checkpoint_round_{round_num}"
# VeRL trainer ์ค์ ์์ ์ ์ฅ ๊ฒฝ๋ก ์
๋ฐ์ดํธ
original_dir = self.verl_trainer.config.trainer.default_local_dir
round_checkpoint_dir = f"{original_dir}/{checkpoint_path}"
# ์์๋ก ์ ์ฅ ๊ฒฝ๋ก ๋ณ๊ฒฝ
self.verl_trainer.config.trainer.default_local_dir = round_checkpoint_dir
# ์ฒดํฌํฌ์ธํธ ์ ์ฅ
self.verl_trainer._save_checkpoint()
# ์๋ ๊ฒฝ๋ก ๋ณต์
self.verl_trainer.config.trainer.default_local_dir = original_dir
self.logger.log_info(f"๐พ Round {round_num} checkpoint saved to: {round_checkpoint_dir}")
return round_checkpoint_dir
else:
self.logger.log_warning("โ ๏ธ VeRL trainer not available for checkpoint saving")
return None
except Exception as e:
self.logger.log_error(f"Failed to save round {round_num} checkpoint: {e}")
import traceback
traceback.print_exc()
return None
def _initialize_ray_cluster(self):
"""Ray ํด๋ฌ์คํฐ ์ด๊ธฐํ (์ ์ฒด ์ธ์
์์ ํ ๋ฒ๋ง)"""
try:
import ray
import os
# Ray๊ฐ ์ด๋ฏธ ์ด๊ธฐํ๋์ด ์๋์ง ํ์ธ
if ray.is_initialized():
self.logger.log_info("โ ๏ธ Ray already initialized, using existing cluster")
self.ray_initialized = True
return
self.logger.log_info("๐ Initializing Ray cluster with all GPUs for shared usage")
# GPU ์ค์
cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES", "0")
self.logger.log_info(f"๐ฏ Ray initialization with CUDA_VISIBLE_DEVICES: {cuda_visible_devices}")
# GPU ๊ฐ์ ํ์ธ
available_gpus = cuda_visible_devices.split(',') if cuda_visible_devices else ['0']
self.logger.log_info(f"๐ฏ Available GPUs: {available_gpus} (count: {len(available_gpus)})")
# VeRL config์์ Ray ์ค์ ๊ฐ์ ธ์ค๊ธฐ
ray_config = getattr(self.verl_config, 'ray_init', None) if hasattr(self, 'verl_config') and self.verl_config else None
# Ray ์ด๊ธฐํ - AZR ๋ฐฉ์๋๋ก GPU ๊ฐ์๋ฅผ ๋ช
์ํ์ง ์์
# Ray๊ฐ GPU๋ฅผ ์ง์ ๊ด๋ฆฌํ์ง ์๊ณ CUDA_VISIBLE_DEVICES๋ก ์ ์ด
ray.init(
runtime_env={"env_vars": {
"TOKENIZERS_PARALLELISM": "true",
"NCCL_DEBUG": "WARN",
"VLLM_LOGGING_LEVEL": "WARN",
"VERL_LOGGING_LEVEL": "INFO", # VeRL ๋ก๊น
๋ ๋ฒจ ์ค์
"VLLM_ALLOW_RUNTIME_LORA_UPDATING": "true",
"CUDA_VISIBLE_DEVICES": cuda_visible_devices
}},
num_cpus=ray_config.num_cpus if ray_config else 16, # AZR config์ ๋์ผ
# num_gpus ์ค์ ํ์ง ์์ - AZR ๋ฐฉ์
ignore_reinit_error=True # ์ฌ์ด๊ธฐํ ์๋ฌ ๋ฌด์
)
self.ray_initialized = True
self.logger.log_info("โ
Ray cluster initialized successfully")
self.logger.log_info(f" - GPUs available via CUDA: {cuda_visible_devices}")
self.logger.log_info(f" - CPUs: {ray_config.num_cpus if ray_config else 16}")
self.logger.log_info(" - GPU management: CUDA_VISIBLE_DEVICES (not Ray)")
self.logger.log_info(" - GPU sharing enabled: VLLM (GPU 0,1) + FSDP (GPU 0,1,2,3)")
except Exception as e:
self.logger.log_error(f"Failed to initialize Ray cluster: {e}")
import traceback
traceback.print_exc()
raise
def _process_problems_sequential(self, benchmark_config: BenchmarkConfig,
problem_ids: List[str], round_num: int) -> Dict[str, Dict]:
"""์์ฐจ์ ์ผ๋ก ๋ฌธ์ ๋ค์ ์ฒ๋ฆฌ (๊ธฐ์กด ๋ฐฉ์)"""
results = {}
for i, problem_id in enumerate(problem_ids):
self.logger.log_info(f"๐ Processing problem {i+1}/{len(problem_ids)}: {problem_id}")
try:
# Ray Actor ํ์ดํ๋ผ์ธ ์ด๊ธฐํ (ํ์์)
if self.remote_pipeline is None:
self._initialize_pipeline()
# Ray Actor์์ ์์ ํ ํ์ดํ๋ผ์ธ ์คํ (์๊ฒฉ ํธ์ถ)
pipeline_result = ray.get(self.remote_pipeline.run_complete_pipeline.remote(
benchmark_config, problem_id, round_num, self.session_timestamp
))
results[problem_id] = pipeline_result
except Exception as e:
self.logger.log_error(f"๐ฅ Failed to process {problem_id}: {e}")
results[problem_id] = {
'success': False,
'error': str(e)
}
return results
def _process_problems_parallel(self, benchmark_config: BenchmarkConfig,
problem_ids: List[str], round_num: int) -> Dict[str, Dict]:
"""[DEPRECATED] Ray๋ฅผ ์ฌ์ฉํ ๋ณ๋ ฌ ๋ฌธ์ ์ฒ๋ฆฌ - ํ์ฌ ์ฌ์ฉํ์ง ์์
Note: ๋ฌธ์ ๊ฐ ๋ณ๋ ฌ ์ฒ๋ฆฌ๋ ๋นํ์ฑํ๋จ. ๋จ์ผ ๋ฌธ์ ๋ด VLLM ๋ฐฐ์น ์ฒ๋ฆฌ๋ง ์ฌ์ฉ.
"""
try:
# VeRL config์์ TTRLVR Ray ์ค์ ๊ฐ์ ธ์ค๊ธฐ
ray_config = getattr(self.verl_config.data, 'ttrlvr_ray_config', {}) if hasattr(self, 'verl_config') and self.verl_config else {}
# ๋ณ๋ ฌ ์ฒ๋ฆฌ ํ์ฑํ ์ฌ๋ถ ํ์ธ
parallel_enabled = ray_config.get('parallel_processing', False)
max_concurrent = ray_config.get('max_concurrent_problems', 4)
if not parallel_enabled or len(problem_ids) <= 1:
self.logger.log_info("๐ Using sequential processing (parallel_processing=False or single problem)")
return self._process_problems_sequential(benchmark_config, problem_ids, round_num)
# ์ค์ Ray ๋ณ๋ ฌ ์ฒ๋ฆฌ ๊ตฌํ
self.logger.log_info(f"๐ Using Ray parallel processing for {len(problem_ids)} problems")
self.logger.log_info(f" - Max concurrent: {min(max_concurrent, len(problem_ids))}")
import ray
# Ray Actor๋ฅผ ์ฌ์ฉํ ๋ณ๋ ฌ TTRLVR ํ์ดํ๋ผ์ธ ์ฒ๋ฆฌ
import os
cuda_visible_devices = os.environ.get("CUDA_VISIBLE_DEVICES", "0")
available_gpus = cuda_visible_devices.split(',') if cuda_visible_devices else ['0']
@ray.remote(num_gpus=1)
class TTRLVRPipelineActor:
def __init__(self, config, logger_config, gpu_id=0):
# GPU ์ค์ ๋จผ์
import os
import torch
# ํ๊ฒฝ๋ณ์์์ ์ค์ GPU ๋ฒํธ ๊ฐ์ ธ์ค๊ธฐ
cuda_devices = os.environ.get('CUDA_VISIBLE_DEVICES', '0')
available_gpus = cuda_devices.split(',') if cuda_devices else ['0']
actual_gpu = available_gpus[gpu_id % len(available_gpus)]
# ํ์ฌ ํ๋ก์ธ์ค์ CUDA_VISIBLE_DEVICES ์ค์
os.environ['CUDA_VISIBLE_DEVICES'] = actual_gpu
# CUDA ์ด๊ธฐํ ๊ฐ์
if torch.cuda.is_available():
torch.cuda.set_device(0) # ๋ก์ปฌ์์๋ ํญ์ 0๋ฒ (์ค์ ๋ก๋ actual_gpu)
print(f"๐ฏ Actor initialized on GPU {actual_gpu} (local:0)")
# TTRLVR ํ์ดํ๋ผ์ธ ์ด๊ธฐํ
from absolute_zero_reasoner.testtime.complete_pipeline import CompleteTestTimePipeline
from absolute_zero_reasoner.testtime.logger import TestTimeLogger
# ๋ก๊ฑฐ ์ฌ์์ฑ (์ง๋ ฌํ ๋ฌธ์ ํด๊ฒฐ)
logger = TestTimeLogger(log_dir=logger_config.get('log_dir', '/tmp'))
# ๋ชจ๋ธ ๋ก๋ (๊ฐ Actor๋ง๋ค ๋
๋ฆฝ์ ์ผ๋ก)
model, tokenizer = self._load_pipeline_model(config)
self.pipeline = CompleteTestTimePipeline(
model=model,
tokenizer=tokenizer,
config=config,
logger=logger
)
def _load_pipeline_model(self, config):
"""๊ฐ Actor์์ ๋
๋ฆฝ์ ์ผ๋ก ๋ชจ๋ธ ๋ก๋"""
from absolute_zero_reasoner.testtime.solution_generator import InitialSolutionGenerator
import torch
import os
# ์์ง ์ ํ (config ๊ธฐ๋ณธ๊ฐ ์ฌ์ฉ)
use_vllm = getattr(config, 'use_vllm_for_data_generation', True)
# GPU ์ค์ - ํ์ฌ Actor์ ํ ๋น๋ GPU ์ฌ์ฉ
device = 'cuda:0' # ๋ก์ปฌ์์๋ ํญ์ 0๋ฒ (์ค์ GPU๋ CUDA_VISIBLE_DEVICES๋ก ์ ์ด)
print(f"๐ Loading model on device {device} (actual GPU: {os.environ.get('CUDA_VISIBLE_DEVICES', 'unknown')})")
return InitialSolutionGenerator.load_model_with_optimizations(
config.model_name, device, config, use_vllm=use_vllm
)
def process_problem(self, benchmark_config, problem_id, round_num, session_timestamp):
"""๋จ์ผ ๋ฌธ์ ์ฒ๋ฆฌ"""
try:
result = self.pipeline.run_complete_pipeline(
benchmark_config, problem_id, round_num, session_timestamp
)
return problem_id, result
except Exception as e:
return problem_id, {
'success': False,
'error': str(e)
}
# Actor ์์ฑ (์ต๋ ๋์ ์คํ ์๋งํผ, GPU ์ ๊ณ ๋ ค)
num_actors = min(max_concurrent, len(problem_ids), len(available_gpus))
self.logger.log_info(f"๐ญ Creating {num_actors} Ray actors across {len(available_gpus)} GPUs")
self.logger.log_info(f" - Available GPUs: {available_gpus}")
self.logger.log_info(f" - Debug: max_concurrent={max_concurrent}, len(problem_ids)={len(problem_ids)}, len(available_gpus)={len(available_gpus)}")
# ๋ก๊ฑฐ ์ค์ ์ง๋ ฌํ
logger_config = {
'log_dir': self.logger.log_dir if hasattr(self.logger, 'log_dir') else '/tmp'
}
# GPU๋ณ๋ก Actor ์์ฑ
actors = []
for i in range(num_actors):
gpu_id = i % len(available_gpus)
self.logger.log_info(f" - Actor {i} -> GPU {available_gpus[gpu_id]}")
actors.append(TTRLVRPipelineActor.remote(self.config, logger_config, gpu_id))
# ์์
๋ถ๋ฐฐ ๋ฐ ์คํ
futures = []
for i, problem_id in enumerate(problem_ids):
actor_idx = i % num_actors
future = actors[actor_idx].process_problem.remote(
benchmark_config, problem_id, round_num, self.session_timestamp
)
futures.append(future)
# ๊ฒฐ๊ณผ ์์ง
self.logger.log_info(f"โณ Waiting for {len(futures)} parallel tasks to complete...")
results_list = ray.get(futures)
# ๊ฒฐ๊ณผ ๋์
๋๋ฆฌ ์์ฑ
results = {}
for problem_id, result in results_list:
results[problem_id] = result
self.logger.log_info(f"โ
Parallel processing completed: {len(results)} problems processed")
return results
except Exception as e:
self.logger.log_error(f"๐ฅ Parallel processing failed: {e}")
self.logger.log_info("๐ Falling back to sequential processing")
return self._process_problems_sequential(benchmark_config, problem_ids, round_num)
def _find_actual_training_data(self) -> Optional[str]:
"""์ต๊ทผ ์์ฑ๋ ์ค์ ํ์ต ๋ฐ์ดํฐ ๋๋ ํ ๋ฆฌ ์ฐพ๊ธฐ"""
try:
# tmp/batch_results์์ ์ต๊ทผ ์์ฑ๋ ๋๋ ํ ๋ฆฌ ๊ฒ์
base_path = "/home/ubuntu/RLVR/TestTime-RLVR-v2/tmp/batch_results"
# azr_training_data ํด๋ ๊ฒ์
import glob
search_pattern = os.path.join(base_path, "**/azr_training_data")
data_dirs = glob.glob(search_pattern, recursive=True)
if not data_dirs:
return None
# ๊ฐ์ฅ ์ต๊ทผ ์์ ๋ ๋๋ ํ ๋ฆฌ ์ฐพ๊ธฐ
latest_dir = max(data_dirs, key=os.path.getmtime)
# parquet ํ์ผ์ด ์ค์ ๋ก ์๋์ง ํ์ธ
task_files = ['induction.parquet', 'deduction.parquet', 'abduction.parquet']
parquet_count = 0
for task_file in task_files:
if os.path.exists(os.path.join(latest_dir, task_file)):
parquet_count += 1
if parquet_count > 0:
return latest_dir
else:
return None
except Exception as e:
self.logger.log_error(f"Error finding actual training data: {e}")
return None |