Spaces:
Build error
Build error
File size: 102,281 Bytes
1ad16ff 4566c4c 1ad16ff 4566c4c 1ad16ff 4566c4c 1ad16ff 4566c4c 1ad16ff 4566c4c 1ad16ff 4566c4c 1ad16ff 4566c4c 1ad16ff 4566c4c 1ad16ff 4566c4c 1ad16ff 817c8e4 46a721d 817c8e4 46a721d 817c8e4 46a721d 817c8e4 46a721d 817c8e4 46a721d 817c8e4 46a721d 817c8e4 7ba4c2d 46a721d 7ba4c2d 46a721d 7ba4c2d 817c8e4 46a721d 817c8e4 46a721d 817c8e4 46a721d 817c8e4 46a721d 817c8e4 46a721d 8fc5582 46a721d 8fc5582 46a721d 8fc5582 46a721d 8fc5582 46a721d 8fc5582 46a721d 817c8e4 46a721d 817c8e4 46a721d 817c8e4 46a721d 817c8e4 46a721d 8fc5582 46a721d fb76828 46a721d fb76828 1ad16ff b174c8a 1ad16ff b174c8a | 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 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn import GCNConv, GAE, VGAE
import gc
import os
import json
import pickle
import signal
import sys
import time
import glob
import uuid
import statistics
import gradio as gr
from datetime import datetime
from typing import Dict, List, Optional, Any, Union, Tuple, Iterator
from dataclasses import dataclass
from sentence_transformers import SentenceTransformer
from transformers import AutoModelForCausalLM, BitsAndBytesConfig
from transformers import AutoModelForCausalLM, AutoTokenizer, AutoConfig
from torch.optim import Adam
# Constants
MAX_ROUNDS = 3
CONFIDENCE_THRESHOLD = 3
JSON_DIRECTORY = './evaluation'
#G-Designer Agents
class BaseAgent(nn.Module):
"""Base class for all agents with learning capabilities."""
def __init__(self, role: str, base_model: str, plugins: List[str]):
super().__init__()
self.role = role
self.base_model = base_model
self.plugins = plugins
self.state_history = []
self.learning_rate = 0.001
# Initialize neural components
self.message_encoder = nn.LSTM(768, 256, bidirectional=True)
self.state_encoder = nn.Linear(512, 256)
self.decision_network = nn.Sequential(
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 64),
nn.ReLU(),
nn.Linear(64, 32)
)
self.optimizer = Adam(self.parameters(), lr=self.learning_rate)
def update_state(self, interaction: Dict):
"""Update agent's state based on interaction."""
self.state_history.append(interaction)
if len(self.state_history) > 1000: # Limit history size
self.state_history = self.state_history[-1000:]
def encode_messages(self, messages: List[str]) -> torch.Tensor:
"""Encode incoming messages."""
message_embeddings = []
for msg in messages:
embedding = self.sentence_transformer.encode(msg)
message_embeddings.append(torch.tensor(embedding))
if message_embeddings:
message_tensor = torch.stack(message_embeddings)
encoded, _ = self.message_encoder(message_tensor.unsqueeze(0))
return encoded.mean(dim=1) # Average over sequence
return torch.zeros(512) # Default empty embedding
def learn_from_feedback(self, feedback: Dict):
"""Learn from feedback about agent's performance."""
raise NotImplementedError
class PatternAnalystAgent(BaseAgent):
"""Specializes in analyzing patterns in ARC tasks."""
def __init__(self):
super().__init__(
role="Pattern Analyst",
base_model="gpt-4",
plugins=["grid_analyzer", "pattern_matcher"]
)
# Pattern recognition components
self.pattern_encoder = nn.Sequential(
nn.Conv2d(1, 16, 3, padding=1),
nn.ReLU(),
nn.MaxPool2d(2),
nn.Conv2d(16, 32, 3, padding=1),
nn.ReLU(),
nn.AdaptiveAvgPool2d((4, 4))
)
self.pattern_memory = {}
def process(self, task_input: Dict, messages: List[str]) -> Dict:
"""Process task input and identify patterns."""
try:
# Encode grid patterns
grid_patterns = self._encode_grids(task_input['train'])
# Encode messages from other agents
message_encoding = self.encode_messages(messages)
# Combine information
combined_features = torch.cat([
grid_patterns.view(-1),
message_encoding
])
# Generate pattern analysis
pattern_description = self._analyze_patterns(combined_features)
# Update state
self.update_state({
'input': task_input,
'patterns': pattern_description,
'timestamp': time.time()
})
return {
'role': self.role,
'patterns': pattern_description,
'confidence': self._calculate_confidence()
}
except Exception as e:
print(f"Error in pattern analysis: {str(e)}")
return None
def learn_from_feedback(self, feedback: Dict):
"""Learn from feedback about pattern analysis accuracy."""
try:
if 'pattern_accuracy' not in feedback:
return
# Calculate loss
accuracy = feedback['pattern_accuracy']
loss = 1 - accuracy
# Backpropagate
self.optimizer.zero_grad()
loss_tensor = torch.tensor(loss, requires_grad=True)
loss_tensor.backward()
self.optimizer.step()
# Update pattern memory
if accuracy > 0.8: # Store successful patterns
task_id = feedback['task_id']
self.pattern_memory[task_id] = {
'patterns': feedback['patterns'],
'accuracy': accuracy
}
except Exception as e:
print(f"Error in pattern learning: {str(e)}")
class GridTransformerAgent(BaseAgent):
"""Specializes in applying transformations to grids."""
def __init__(self):
super().__init__(
role="Grid Transformer",
base_model="gpt-4",
plugins=["grid_transformer", "rule_executor"]
)
# Transformation components
self.transform_network = nn.Sequential(
nn.Linear(512, 256),
nn.ReLU(),
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 64)
)
self.transformation_memory = {}
def process(self, task_input: Dict, messages: List[str]) -> Dict:
"""Apply transformations based on identified patterns."""
try:
# Extract patterns from analyst's messages
patterns = self._extract_patterns(messages)
# Encode current grid
grid_encoding = self._encode_grid(task_input['test'])
# Generate transformation
transformation = self._generate_transformation(
patterns, grid_encoding)
# Apply transformation
transformed_grid = self._apply_transformation(
task_input['test'], transformation)
# Update state
self.update_state({
'input': task_input,
'transformation': transformation,
'output': transformed_grid,
'timestamp': time.time()
})
return {
'role': self.role,
'transformed_grid': transformed_grid,
'confidence': self._calculate_confidence()
}
except Exception as e:
print(f"Error in grid transformation: {str(e)}")
return None
def learn_from_feedback(self, feedback: Dict):
"""Learn from feedback about transformation accuracy."""
try:
if 'transformation_accuracy' not in feedback:
return
accuracy = feedback['transformation_accuracy']
loss = 1 - accuracy
# Update transformation network
self.optimizer.zero_grad()
loss_tensor = torch.tensor(loss, requires_grad=True)
loss_tensor.backward()
self.optimizer.step()
# Store successful transformations
if accuracy > 0.8:
task_id = feedback['task_id']
self.transformation_memory[task_id] = {
'transformation': feedback['transformation'],
'accuracy': accuracy
}
except Exception as e:
print(f"Error in transformation learning: {str(e)}")
class ValidatorAgent(BaseAgent):
"""Specializes in validating transformed grids."""
def __init__(self):
super().__init__(
role="Validator",
base_model="gpt-4",
plugins=["grid_validator", "consistency_checker"]
)
# Validation components
self.validation_network = nn.Sequential(
nn.Linear(768, 256),
nn.ReLU(),
nn.Linear(256, 128),
nn.ReLU(),
nn.Linear(128, 1),
nn.Sigmoid()
)
self.validation_memory = {}
def process(self, task_input: Dict, messages: List[str]) -> Dict:
"""Validate transformed grids."""
try:
# Extract transformed grid
transformed_grid = self._extract_grid(messages)
# Validate grid
validation_result = self._validate_grid(
transformed_grid, task_input)
# Check consistency
consistency_score = self._check_consistency(
transformed_grid, task_input['train'])
# Update state
self.update_state({
'input': task_input,
'validation': validation_result,
'consistency': consistency_score,
'timestamp': time.time()
})
return {
'role': self.role,
'is_valid': validation_result,
'consistency_score': consistency_score,
'confidence': self._calculate_confidence()
}
except Exception as e:
print(f"Error in validation: {str(e)}")
return None
def learn_from_feedback(self, feedback: Dict):
"""Learn from feedback about validation accuracy."""
try:
if 'validation_accuracy' not in feedback:
return
accuracy = feedback['validation_accuracy']
loss = 1 - accuracy
# Update validation network
self.optimizer.zero_grad()
loss_tensor = torch.tensor(loss, requires_grad=True)
loss_tensor.backward()
self.optimizer.step()
# Store successful validations
if accuracy > 0.8:
task_id = feedback['task_id']
self.validation_memory[task_id] = {
'validation_criteria': feedback['validation_criteria'],
'accuracy': accuracy
}
except Exception as e:
print(f"Error in validation learning: {str(e)}")
class ARCDataLoader:
"""Handles loading and processing of ARC task data."""
JSON_directory='./evaluation'
def __init__(self, base_path: str = JSON_directory):
self.base_path = base_path
if not os.path.exists(base_path):
raise ValueError(f"Base path does not exist: {base_path}")
if not os.access(base_path, os.R_OK):
raise ValueError(f"No read permission for base path: {base_path}")
def load_task(self, file_path: str) -> Optional[Dict]:
"""Load a single ARC task from JSON file."""
try:
if not file_path.endswith('.json'):
return None
if not os.path.exists(file_path):
print(f"File not found: {file_path}")
return None
if not os.access(file_path, os.R_OK):
print(f"No read permission for file: {file_path}")
return None
with open(file_path, 'r') as f:
data = json.load(f)
# Validate the expected structure
if not isinstance(data, dict):
print(f"Invalid data structure in {file_path}: not a dictionary")
return None
if 'train' not in data or 'test' not in data:
print(f"Invalid data structure in {file_path}: missing train or test data")
return None
# Validate that train and test are lists
if not isinstance(data['train'], list) or not isinstance(data['test'], list):
print(f"Invalid data structure in {file_path}: train or test is not a list")
return None
return data
except json.JSONDecodeError:
print(f"Invalid JSON format in file: {file_path}")
return None
except Exception as e:
print(f"Unexpected error reading {file_path}: {str(e)}")
return None
def load_all_tasks(self) -> List[Dict]:
"""Load all ARC tasks from the evaluation directory."""
tasks = []
for filename in os.listdir(self.base_path):
if not filename.endswith('.json'):
continue
file_path = os.path.join(self.base_path, filename)
task = self.load_task(file_path)
if task is not None:
tasks.append({
'filename': filename,
'data': task
})
if not tasks:
print(f"Warning: No valid JSON files found in {self.base_path}")
return tasks
def validate_grid(self, grid: List[List[int]]) -> bool:
"""Validate a grid according to ARC specifications."""
if not grid or not grid[0]:
return False
rows, cols = len(grid), len(grid[0])
# Check size constraints
if rows < 1 or rows > 30 or cols < 1 or cols > 30:
return False
# Check all rows have same length and valid values
return all(
len(row) == cols and all(0 <= val <= 9 for val in row)
for row in grid
)
def validate_task_format(self, task: Dict) -> bool:
"""Validate that a task follows ARC format specifications."""
try:
# Verify required fields
if not isinstance(task.get('train'), list) or not isinstance(task.get('test'), list):
return False
# Validate all pairs
for pair in task['train'] + task['test']:
if not isinstance(pair, dict):
return False
if 'input' not in pair or 'output' not in pair:
return False
if not self.validate_grid(pair['input']) or not self.validate_grid(pair['output']):
return False
return True
except Exception:
return False
class ARCTaskConverter:
"""Converts ARC tasks into format suitable for agent system."""
def __init__(self):
self.cached_descriptions = {}
def grid_to_text(self, grid: List[List[int]]) -> str:
"""Convert a grid to a text description."""
rows = len(grid)
cols = len(grid[0]) if rows > 0 else 0
return f"Grid of size {rows}x{cols} with values:\n" + \
"\n".join([" ".join(map(str, row)) for row in grid])
def analyze_pattern(self, input_grid: List[List[int]], output_grid: List[List[int]]) -> str:
"""Analyze the transformation pattern between input and output grids."""
in_rows, in_cols = len(input_grid), len(input_grid[0]) if input_grid else 0
out_rows, out_cols = len(output_grid), len(output_grid[0]) if output_grid else 0
pattern = f"Transform {in_rows}x{in_cols} grid into {out_rows}x{out_cols} grid.\n"
# Detect basic patterns
if out_rows == in_rows * 3 and out_cols == in_cols * 3:
pattern += "Pattern appears to involve 3x3 expansion of the input."
elif all(all(val in [0, 1] for val in row) for row in input_grid):
pattern += "Binary grid transformation task."
return pattern
def create_task_description(self, task: Dict) -> str:
"""Create a natural language description of the ARC task."""
train_pairs = task.get('train', [])
test_pairs = task.get('test', [])
# Create a description including both training and testing pairs
description = "ARC reasoning task with the following examples:\n\n"
for idx, pair in enumerate(train_pairs):
input_desc = self.grid_to_text(pair['input'])
output_desc = self.grid_to_text(pair['output'])
pattern = self.analyze_pattern(pair['input'], pair['output'])
description += f"Training Example {idx + 1}:\nInput:\n{input_desc}\n"
description += f"Output:\n{output_desc}\nPattern: {pattern}\n\n"
for idx, pair in enumerate(test_pairs):
input_desc = self.grid_to_text(pair['input'])
description += f"Test Example {idx + 1}:\nInput:\n{input_desc}\nExpected output needs to be inferred.\n\n"
return description
class ARCEvaluator:
def __init__(self, max_trials: int = 3):
self.max_trials = max_trials
self.results = {}
self.rounds = {} # Track rounds per task
def evaluate_output(self, predicted: List[List[int]], actual: List[List[int]]) -> bool:
if not predicted or not actual:
return False
if len(predicted) != len(actual) or len(predicted[0]) != len(actual[0]):
return False
return all(predicted[i][j] == actual[i][j]
for i in range(len(predicted))
for j in range(len(predicted[0])))
def record_result(self, task_id: str, trial: int, success: bool):
if task_id not in self.results:
self.results[task_id] = {'trials': [], 'success': False}
self.rounds[task_id] = 0
self.results[task_id]['trials'].append(success)
self.rounds[task_id] += 1
if success:
self.results[task_id]['success'] = True
def get_summary(self) -> Dict:
total_tasks = len(self.results)
if total_tasks == 0:
return {
'total_tasks': 0,
'successful_tasks': 0,
'success_rate': 0.0,
'average_trials_to_success': 0.0,
'rounds': 0
}
successful_tasks = sum(1 for result in self.results.values() if result['success'])
avg_rounds = sum(self.rounds.values()) / total_tasks if total_tasks > 0 else 0
trials_to_success = []
for result in self.results.values():
if result['success']:
trial_num = next(i + 1 for i, success in enumerate(result['trials']) if success)
trials_to_success.append(trial_num)
avg_trials = statistics.mean(trials_to_success) if trials_to_success else 0
return {
'total_tasks': total_tasks,
'successful_tasks': successful_tasks,
'success_rate': successful_tasks / total_tasks,
'average_trials_to_success': avg_trials,
'rounds': avg_rounds
}
class GPUMemoryManager:
def __init__(self):
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
# Simplified CUDA allocation config
os.environ['PYTORCH_CUDA_ALLOC_CONF'] = 'max_split_size_mb:128'
# Set CUDA_LAUNCH_BLOCKING for debugging
os.environ['CUDA_LAUNCH_BLOCKING'] = '1'
if torch.cuda.is_available():
# More conservative memory fraction
torch.cuda.set_per_process_memory_fraction(0.7)
self.force_memory_release()
def optimize_memory(self):
gc.collect()
if torch.cuda.is_available():
torch.cuda.empty_cache()
torch.cuda.synchronize()
def force_memory_release(self):
if torch.cuda.is_available():
torch.cuda.empty_cache()
gc.collect()
torch.cuda.synchronize()
torch.cuda.reset_peak_memory_stats()
# Clear CUDA cache more aggressively
with torch.cuda.device('cuda'):
torch.cuda.empty_cache()
torch.cuda.ipc_collect()
def check_memory(self, required_memory_mb: int = 1000) -> bool:
if not torch.cuda.is_available():
return True
try:
with torch.cuda.device('cuda'):
total = torch.cuda.get_device_properties(0).total_memory
allocated = torch.cuda.memory_allocated()
free_memory = (total - allocated) / (1024 * 1024) # Convert to MB
return free_memory >= required_memory_mb
except Exception:
return False
def get_memory_stats(self) -> Dict[str, float]:
if not torch.cuda.is_available():
return {"allocated": 0, "cached": 0, "max_allocated": 0}
return {
"allocated": torch.cuda.memory_allocated() / (1024 * 1024),
"cached": torch.cuda.memory_reserved() / (1024 * 1024),
"max_allocated": torch.cuda.max_memory_allocated() / (1024 * 1024)
}
class RoleLearningManager:
def __init__(self, checkpoint_dir: str = "./role_checkpoints"):
self.checkpoint_dir = checkpoint_dir
os.makedirs(checkpoint_dir, exist_ok=True)
self.role_experiences = {
'boss': [],
'agent1': [],
'agent2': [],
'agent3': [],
'summarizer': []
}
self.role_metrics = {role: {'success_rate': 0.0, 'total_tasks': 0} for role in self.role_experiences.keys()}
self.load_experiences()
def save_experience(self, role: str, experience: Dict):
self.role_experiences[role].append(experience)
self._update_metrics(role, experience['success'])
self.save_checkpoint(role)
def _update_metrics(self, role: str, success: bool):
metrics = self.role_metrics[role]
metrics['total_tasks'] += 1
metrics['success_rate'] = (
(metrics['success_rate'] * (metrics['total_tasks'] - 1) + int(success))
/ metrics['total_tasks']
)
def get_role_experience(self, role: str, n_recent: int = 5) -> List[Dict]:
experiences = self.role_experiences.get(role, [])
return experiences[-n_recent:] if experiences else []
def save_checkpoint(self, role: str):
checkpoint_path = os.path.join(self.checkpoint_dir, f"{role}_experience.pkl")
metrics_path = os.path.join(self.checkpoint_dir, f"{role}_metrics.json")
with open(checkpoint_path, 'wb') as f:
pickle.dump(self.role_experiences[role], f)
with open(metrics_path, 'w') as f:
json.dump(self.role_metrics[role], f)
def load_experiences(self):
for role in self.role_experiences.keys():
exp_path = os.path.join(self.checkpoint_dir, f"{role}_experience.pkl")
metrics_path = os.path.join(self.checkpoint_dir, f"{role}_metrics.json")
if os.path.exists(exp_path):
with open(exp_path, 'rb') as f:
self.role_experiences[role] = pickle.load(f)
if os.path.exists(metrics_path):
with open(metrics_path, 'r') as f:
self.role_metrics[role] = json.load(f)
class NodeEncoder(nn.Module):
def __init__(self, input_dim):
super().__init__()
self.encoder = SentenceTransformer('all-MiniLM-L6-v2')
self.linear = nn.Linear(384, input_dim)
def forward(self, text: str) -> torch.Tensor:
with torch.no_grad():
embeddings = self.encoder.encode(text, convert_to_tensor=True)
return self.linear(embeddings)
class GCNEncoder(nn.Module):
def __init__(self, input_dim: int, hidden_dim: int, latent_dim: int):
super().__init__()
self.gcn1 = GCNConv(input_dim, hidden_dim)
self.gcn2 = GCNConv(hidden_dim, latent_dim)
def forward(self, x: torch.Tensor, edge_index: torch.Tensor) -> Tuple[torch.Tensor, torch.Tensor]:
h = F.relu(self.gcn1(x, edge_index))
h = F.dropout(h, p=0.5, training=self.training)
mu = self.gcn2(h, edge_index)
log_std = self.gcn2(h, edge_index)
return mu, log_std
class GraphDecoder(nn.Module):
def __init__(self, latent_dim: int, hidden_dim: int):
super().__init__()
self.ffn = nn.Sequential(
nn.Linear(latent_dim * 3, hidden_dim),
nn.ReLU(),
nn.Linear(hidden_dim, 1)
)
def forward(self, z: torch.Tensor, task_embed: torch.Tensor) -> torch.Tensor:
N = z.size(0)
device = z.device
rows = z.repeat_interleave(N, dim=0)
cols = z.repeat(N, 1)
tasks = task_embed.repeat(N * N, 1)
edge_inputs = torch.cat([rows, cols, tasks], dim=1)
edge_logits = self.ffn(edge_inputs).view(N, N)
return torch.sigmoid(edge_logits)
class VGAE(torch.nn.Module):
def __init__(self, encoder, decoder):
super().__init__()
self.encoder = encoder
self.decoder = decoder
def forward(self, x):
z = self.encoder(x)
return self.decoder(z)
class AgentEncoder(torch.nn.Module): #Set the torch with the self learning module.
"""Encodes agent properties into embeddings."""
def __init__(self, input_dim): #def __init__(self, input_dim=768, hidden_dim=256, output_dim=128):
super().__init__()
self.encoder = torch.nn.Linear(input_dim, 128)
#self.encoder = nn.Sequential( #Most likely won't do anything for the user query. May need to be turned on for dataset evaluation.
## nn.Linear(input_dim, hidden_dim),
# nn.ReLU(),
# nn.Linear(hidden_dim, output_dim)
# )
def forward(self, x):
return self.encoder(x)
class GraphEncoder(torch.nn.Module):
def __init__(self, input_dim):
super().__init__()
self.encoder = torch.nn.Linear(input_dim, 128)
def forward(self, x):
return F.relu(self.encoder(x))
class GraphDecoder(torch.nn.Module):
def __init__(self, hidden_dim):
super().__init__()
self.decoder = torch.nn.Linear(hidden_dim, hidden_dim)
def forward(self, z):
return torch.sigmoid(self.decoder(z))
class GDesigner:
"""Graph-based Designer for Multi-agent Communication"""
def __init__(self, num_agents=3, input_dim=768, roles=None):
self.num_agents = num_agents
self.roles = roles if roles else {}
self.device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
self.checkpoint_dir = "checkpoints"
# Initialize components
self.agent_encoder = AgentEncoder(input_dim).to(self.device)
self.graph_encoder = GraphEncoder(input_dim).to(self.device)
self.graph_decoder = GraphDecoder(128).to(self.device)
# Initialize VGAE
self.vgae = VGAE(self.graph_encoder, self.graph_decoder)
# Optimization
self.optimizer = Adam(list(self.vgae.parameters()) +
list(self.agent_encoder.parameters()), lr=0.001)
# Learning history
self.learning_history = {}
self.current_utility = -float('inf')
self.performance_history = {}
# Initialize communication graph
self.communication_graph = self._initialize_graph()
# Task-specific components
self.task_embeddings = {}
self.anchor_topologies = {}
self.experience_buffer = [] # Initialize experience buffer
def _initialize_graph(self):
"""Initialize the communication graph with basic structure."""
num_nodes = self.num_agents + 1 # +1 for task-specific virtual node
return torch.zeros((num_nodes, num_nodes), device=self.device)
def update_roles(self, new_roles):
"""Update agent roles dynamically"""
self.roles = new_roles
self.num_agents = len(new_roles)
self.communication_graph = self._initialize_graph()
def _initialize_graph(self):
"""Initialize the communication graph with basic structure."""
num_nodes = self.num_agents + 1 # +1 for task-specific virtual node
return torch.zeros((num_nodes, num_nodes), device=self.device)
def encode_agent(self, agent_data):
"""Encode agent properties into embeddings."""
# Convert agent properties to tensor
agent_tensor = self._prepare_agent_tensor(agent_data)
return self.agent_encoder(agent_tensor)
def _prepare_agent_tensor(self, agent_data):
"""Convert agent properties to tensor format."""
# Combine agent properties into a single vector
properties = [
agent_data['base_model'],
agent_data['role'],
agent_data['state'],
agent_data['plugins']
]
# Use sentence transformer to get embeddings
embeddings = self.sentence_transformer.encode(properties)
return torch.tensor(embeddings, device=self.device)
def update_graph(self, task_id: str, agents_data: List[Dict],
performance_metrics: Dict):
"""Update communication graph based on task performance."""
try:
# Encode agents
agent_embeddings = [self.encode_agent(agent) for agent in agents_data]
agent_embeddings = torch.stack(agent_embeddings)
# Add task-specific virtual node
task_embedding = self.task_embeddings.get(task_id,
torch.randn(768, device=self.device))
node_embeddings = torch.cat([agent_embeddings, task_embedding.unsqueeze(0)])
# Get anchor topology
anchor_topology = self.anchor_topologies.get(task_id,
self._initialize_graph())
# Optimize graph structure
self.optimizer.zero_grad()
# VGAE forward pass
mu, logvar = self.graph_encoder(node_embeddings, self.communication_graph)
z = self.vgae.reparametrize(mu, logvar)
reconstructed_graph = self.graph_decoder(z)
# Calculate losses
recon_loss = F.binary_cross_entropy(reconstructed_graph,
self.communication_graph)
kl_loss = 0.01 * torch.mean(torch.sum(
torch.exp(logvar) + mu**2 - 1 - logvar, dim=1))
# Add sparsity constraint
sparsity_loss = 0.1 * torch.norm(reconstructed_graph, p=1)
# Add anchor topology constraint
anchor_loss = 0.05 * F.mse_loss(reconstructed_graph, anchor_topology)
# Total loss
loss = recon_loss + kl_loss + sparsity_loss + anchor_loss
# Backward pass and optimization
loss.backward()
self.optimizer.step()
# Update communication graph if improved
utility = self._calculate_utility(performance_metrics)
if utility > self.current_utility:
self.communication_graph = reconstructed_graph.detach()
self.current_utility = utility
# Store learning history
self.learning_history[task_id] = {
'utility': utility.item(),
'loss': loss.item(),
'graph_structure': self.communication_graph.clone(),
'performance': performance_metrics
}
except Exception as e:
print(f"Error updating graph: {str(e)}")
class TaskAdapter:
"""Handles task-specific adaptation of the communication graph."""
def __init__(self, hidden_dim=256):
self.hidden_dim = hidden_dim
self.task_memory = {}
self.sentence_transformer = SentenceTransformer('all-MiniLM-L6-v2')
def create_task_embedding(self, task: Dict) -> torch.Tensor:
"""Create task-specific embedding."""
# Extract task features
train_examples = self._format_examples(task['train'])
test_input = self._format_examples([task['test'][0]]) # First test case
# Create task description
task_desc = f"Task with {len(task['train'])} training examples. "
task_desc += f"Input grid size: {len(task['test'][0]['input'])}x{len(task['test'][0]['input'][0])}. "
# Get embedding
embedding = self.sentence_transformer.encode(task_desc)
return torch.tensor(embedding)
def generate_anchor_topology(self, task: Dict, agents: List[str]) -> torch.Tensor:
"""Generate initial anchor topology based on task type."""
num_agents = len(agents)
topology = torch.zeros((num_agents, num_agents))
# Analyze task type and create appropriate topology
if self._is_pattern_recognition_task(task):
# Chain topology: analyzer -> transformer -> validator
for i in range(num_agents - 1):
topology[i][i + 1] = 1
else:
# Fully connected for complex tasks
topology.fill_(1)
topology.fill_diagonal_(0)
return topology
def _is_pattern_recognition_task(self, task: Dict) -> bool:
"""Determine if task is pattern recognition based."""
try:
# Check if all grids have same dimensions
input_dims = set()
output_dims = set()
for example in task['train'] + task['test']:
input_dims.add((len(example['input']), len(example['input'][0])))
output_dims.add((len(example['output']), len(example['output'][0])))
return len(input_dims) == 1 and len(output_dims) == 1
except:
return False
class CommunicationProtocol:
"""Manages communication between agents."""
def __init__(self, max_rounds=3):
self.max_rounds = max_rounds
self.message_history = {}
self.execution_order = []
def optimize_execution_order(self, graph: torch.Tensor) -> List[int]:
"""Determine optimal execution order based on graph structure."""
num_agents = graph.shape[0]
dependencies = {i: set() for i in range(num_agents)}
# Build dependency graph
for i in range(num_agents):
for j in range(num_agents):
if graph[i][j] > 0.5: # Edge exists
dependencies[j].add(i)
# Topological sort
visited = set()
temp = set()
order = []
def visit(node):
if node in temp:
raise ValueError("Cycle detected in agent dependencies")
if node in visited:
return
temp.add(node)
for dep in dependencies[node]:
visit(dep)
temp.remove(node)
visited.add(node)
order.append(node)
for node in range(num_agents):
if node not in visited:
visit(node)
return order[::-1] # Reverse for correct execution order
def execute_round(self, agents: List[Any], graph: torch.Tensor,
task_input: Any) -> Dict:
"""Execute one round of inter-agent communication."""
try:
# Get execution order
execution_order = self.optimize_execution_order(graph)
self.execution_order = execution_order
# Initialize message storage
round_messages = {i: [] for i in range(len(agents))}
# Execute agents in order
for agent_idx in execution_order:
# Collect incoming messages
incoming_messages = []
for other_idx in range(len(agents)):
if graph[other_idx][agent_idx] > 0.5:
incoming_messages.extend(round_messages[other_idx])
# Execute agent
agent_output = agents[agent_idx].process(
task_input,
incoming_messages
)
# Store messages
round_messages[agent_idx].append(agent_output)
return round_messages
except Exception as e:
print(f"Error in communication round: {str(e)}")
return {}
def aggregate_results(self, round_messages: Dict,
aggregation_type: str = 'majority') -> Any:
"""Aggregate results from all agents."""
try:
if aggregation_type == 'majority':
# Collect all predictions
predictions = []
for agent_messages in round_messages.values():
if agent_messages:
predictions.append(agent_messages[-1])
# Return most common prediction
if predictions:
return max(set(predictions), key=predictions.count)
elif aggregation_type == 'last':
# Return last agent's output
last_agent = self.execution_order[-1]
if round_messages[last_agent]:
return round_messages[last_agent][-1]
return None
except Exception as e:
print(f"Error in result aggregation: {str(e)}")
return None
def learn_from_experience(self, task_description: str, agents: List[Any],
success: bool, execution_time: float, feedback: Dict):
experience = {
'task': task_description,
'agents': [agent.to_dict() for agent in agents],
'success': success,
'execution_time': execution_time,
'feedback': feedback,
'topology': self.last_topology.clone() if hasattr(self, 'last_topology') else None
}
self.experience_buffer.append(experience)
self.update_model_from_experience()
def save_checkpoint(self):
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
checkpoint_path = os.path.join(self.checkpoint_dir, f"gdesigner_checkpoint_{timestamp}")
cpu_state_dict = {k: v.cpu() for k, v in self.state_dict().items()}
cpu_optimizer_state = {k: v.cpu() if isinstance(v, torch.Tensor) else v
for k, v in self.optimizer.state_dict().items()}
torch.save({
'model_state_dict': cpu_state_dict,
'optimizer_state_dict': cpu_optimizer_state,
'performance_history': self.performance_history,
}, f"{checkpoint_path}_model.pt")
with open(f"{checkpoint_path}_experiences.pkl", 'wb') as f:
pickle.dump(self.experience_buffer, f)
def load_checkpoint(self):
try:
checkpoints = [f for f in os.listdir(self.checkpoint_dir) if f.endswith('_model.pt')]
if not checkpoints:
return
latest_checkpoint = max(checkpoints)
checkpoint_base = latest_checkpoint.replace('_model.pt', '')
checkpoint = torch.load(
os.path.join(self.checkpoint_dir, latest_checkpoint),
map_location=self.device
)
self.load_state_dict(checkpoint['model_state_dict'])
self.optimizer.load_state_dict(checkpoint['optimizer_state_dict'])
self.performance_history = checkpoint['performance_history']
with open(os.path.join(self.checkpoint_dir, f"{checkpoint_base}_experiences.pkl"), 'rb') as f:
self.experience_buffer = pickle.load(f)
except Exception as e:
print(f"Error loading checkpoint: {str(e)}")
self.experience_buffer = []
self.performance_history = {}
class DynamicLLM:
def __init__(self):
self.model_name = "jpacifico/Chocolatine-3B-Instruct-DPO-Revised"
self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
self.tokenizer = AutoTokenizer.from_pretrained(self.model_name)
self.model = self._initialize_model()
def _initialize_model(self):
config = AutoConfig.from_pretrained(self.model_name)
model = AutoModelForCausalLM.from_pretrained(
self.model_name,
config=config,
device_map='auto',
torch_dtype=torch.float16
)
return model
def generate_response(self, prompt: str, role: str = None) -> str:
try:
inputs = self.tokenizer(prompt, return_tensors="pt").to(self.device)
outputs = self.model.generate(
**inputs,
max_length=512,
temperature=0.7,
do_sample=True
)
return self.tokenizer.decode(outputs[0], skip_special_tokens=True)
except Exception as e:
print(f"Error generating response: {str(e)}")
return None
def generate_prediction(train_pairs: List[Dict], test_input: List[List[int]], trial: int) -> List[List[int]]:
"""Generate a prediction for a test input using the multi-agent system."""
try:
# Create more specific task description
task_description = (
"Analyze these training examples and predict the output for the test input.\n"
"Rules:\n"
"1. Only use numbers 0-9\n"
"2. Maintain grid structure\n"
"3. Look for consistent patterns between input and output\n\n"
"Training Examples:\n"
)
# Add formatted training examples
for idx, pair in enumerate(train_pairs, 1):
task_description += f"\nExample {idx}:\n"
task_description += "Input:\n"
task_description += grid_to_string(pair['input']) + "\n"
task_description += "Output:\n"
task_description += grid_to_string(pair['output']) + "\n"
# Add test input
task_description += "\nTest Input:\n"
task_description += grid_to_string(test_input)
# Initialize agents with more specific roles
agent_specs = [
{
"role": "Pattern Analyst",
"specialty": "grid_analysis",
"context": {
"task": "Identify the exact transformation pattern from input to output grids",
"trial": trial + 1,
"examples": train_pairs
}
},
{
"role": "Grid Transformer",
"specialty": "transformation",
"context": {
"task": "Apply the identified pattern to generate the output grid",
"trial": trial + 1,
"test_input": test_input
}
},
{
"role": "Validator",
"specialty": "validation",
"context": {
"task": "Verify the generated grid follows the pattern and constraints",
"trial": trial + 1,
"valid_values": list(range(10))
}
}
]
# Execute the prediction pipeline with better error handling
pattern_analysis = None
transformation_result = None
validation_result = None
try:
pattern_analysis = dynamic_mas.execute_agent_query(
task_description,
agent_specs[0],
context={"phase": "analysis", "trial": trial}
)
if not pattern_analysis:
raise ValueError("Pattern analysis failed")
transformation_result = dynamic_mas.execute_agent_query(
task_description,
agent_specs[1],
context={
"phase": "transformation",
"pattern_analysis": pattern_analysis,
"trial": trial
}
)
if not transformation_result:
raise ValueError("Transformation failed")
validation_result = dynamic_mas.execute_agent_query(
task_description,
agent_specs[2],
context={
"phase": "validation",
"transformed_grid": transformation_result,
"trial": trial
}
)
if not validation_result:
raise ValueError("Validation failed")
except Exception as e:
print(f"Agent pipeline error: {str(e)}")
return None
# Parse and validate the final grid
predicted_grid = parse_grid_from_response(validation_result)
if predicted_grid and is_valid_grid(predicted_grid):
return predicted_grid
return None
except Exception as e:
print(f"Error in generate_prediction: {str(e)}")
return None
def switch_role(self, role: str, context: Dict = None):
self.current_role = role
experiences = self.learning_manager.get_role_experience(role)
metrics = self.learning_manager.role_metrics[role]
return self._create_role_context(role, experiences, metrics, context)
def _get_role_context(self) -> str:
if not self.current_role:
return ""
experiences = self.learning_manager.get_role_experience(self.current_role)
metrics = self.learning_manager.role_metrics[self.current_role]
return self._create_role_context(self.current_role, experiences, metrics)
def learn_from_interaction(self, role: str, task: str, success: bool, learning: str, feedback: Optional[str] = None):
experience = {
'task': task,
'success': success,
'learning': learning,
'feedback': feedback,
'timestamp': datetime.now().isoformat()
}
self.learning_manager.save_experience(role, experience)
if role not in self.role_performance:
self.role_performance[role] = []
self.role_performance[role].append({
'timestamp': datetime.now().isoformat(),
'success': success,
'task': task
})
class TaskAdapter:
"""Handles task-specific adaptation of the communication graph."""
def __init__(self, hidden_dim=256):
self.hidden_dim = hidden_dim
self.task_memory = {}
self.sentence_transformer = SentenceTransformer('all-MiniLM-L6-v2')
def create_task_embedding(self, task: Dict) -> torch.Tensor:
"""Create task-specific embedding."""
task_desc = f"Task with {len(task.get('train', []))} training examples."
embedding = self.sentence_transformer.encode(task_desc)
return torch.tensor(embedding)
def generate_anchor_topology(self, task: Dict, agents: List[str]) -> torch.Tensor:
"""Generate initial anchor topology based on task type."""
num_agents = len(agents)
topology = torch.zeros((num_agents, num_agents))
if self._is_pattern_recognition_task(task):
for i in range(num_agents - 1):
topology[i][i + 1] = 1
else:
topology.fill_(1)
topology.fill_diagonal_(0)
return topology
def _is_pattern_recognition_task(self, task: Dict) -> bool:
try:
input_dims = set()
output_dims = set()
for example in task.get('train', []) + task.get('test', []):
input_dims.add((len(example['input']), len(example['input'][0])))
output_dims.add((len(example['output']), len(example['output'][0])))
return len(input_dims) == 1 and len(output_dims) == 1
except:
return False
class CommunicationProtocol:
"""Manages communication between agents."""
def __init__(self, max_rounds=3):
self.max_rounds = max_rounds
self.message_history = {}
self.execution_order = []
def optimize_execution_order(self, graph: torch.Tensor) -> List[int]:
"""Determine optimal execution order based on graph structure."""
num_agents = graph.shape[0]
dependencies = {i: set() for i in range(num_agents)}
for i in range(num_agents):
for j in range(num_agents):
if graph[i][j] > 0.5:
dependencies[j].add(i)
visited = set()
temp = set()
order = []
def visit(node):
if node in temp:
raise ValueError("Cycle detected in agent dependencies")
if node in visited:
return
temp.add(node)
for dep in dependencies[node]:
visit(dep)
temp.remove(node)
visited.add(node)
order.append(node)
for node in range(num_agents):
if node not in visited:
visit(node)
return order[::-1]
class DynamicMultiAgentSystem ():
"""Coordinates a single LLM that switches between agent roles."""
def __init__(self):
self.llm = DynamicLLM() # Single LLM instance
self.g_designer = GDesigner() # Initialize with default parameters
self.task_adapter = TaskAdapter()
self.protocol = CommunicationProtocol()
self.is_string_response = False
def initialize_roles(self, boss_response=None):
"""Initialize roles based on boss response or default configuration."""
if boss_response and isinstance(boss_response, dict):
self.roles = boss_response
self.is_string_response = True
else:
# Role definitions for evaluation dataset only.
self.roles = {
'analyst': {
'name': 'Pattern Analyst',
'state': {},
'memory': {},
'performance_history': []
},
'transformer': {
'name': 'Grid Transformer',
'state': {},
'memory': {},
'performance_history': []
},
'validator': {
'name': 'Validator',
'state': {},
'memory': {},
'performance_history': []
}
}
self.is_string_response = False
def _process_string_task(self, task: Dict) -> Dict:
"""Process tasks that require string responses."""
try:
messages = {}
current_state = {}
for role_id, role_info in self.roles.items():
# Switch LLM to current role
role_state = self.llm.switch_role(
role_info['name'],
{
'task': task,
'current_state': current_state,
'role_memory': role_info['memory']
}
)
# Process with current role
result = self._process_role(role_id, task, messages, role_state)
# Store result
messages[role_id] = result
current_state[role_id] = result
# Update role's memory
self._update_role_memory(role_id, task, result)
# Aggregate string responses
final_response = self.protocol.aggregate_string_results(messages)
return {
'result': final_response,
'messages': messages
}
except Exception as e:
print(f"Error in string task processing: {str(e)}")
return None
def process_task(self, task: Dict) -> Dict:
"""Process task using single LLM switching between roles."""
try:
# Create task embedding and anchor topology
task_embedding = self.task_adapter.create_task_embedding(task)
anchor_topology = self.task_adapter.generate_anchor_topology(
task, list(self.roles.keys()))
# Initialize performance tracking
best_performance = None
best_result = None
current_state = {}
# Multiple rounds of processing
for round_num in range(self.protocol.max_rounds):
# Get current graph structure
graph = self.g_designer.get_communication_graph()
# Process through each role sequentially
round_messages = {}
for role_id, role_info in self.roles.items():
# Switch LLM to current role
role_state = self.llm.switch_role(
role_info['name'],
{
'task': task,
'current_state': current_state,
'role_memory': role_info['memory'],
'performance_history': role_info['performance_history']
}
)
# Get incoming messages based on graph structure
incoming_messages = self._get_role_messages(
role_id, round_messages, graph)
# Process with current role
result = self._process_role(
role_id,
task,
incoming_messages,
role_state
)
# Store result
round_messages[role_id] = result
current_state[role_id] = result
# Update role's state and memory
self._update_role_memory(role_id, task, result)
# Aggregate results
round_result = self.protocol.aggregate_results(round_messages)
# Evaluate performance
performance = self._evaluate_performance(round_result, task)
# Update performance histories
self._update_performance_histories(performance, round_messages)
# Update best result
if not best_performance or performance > best_performance:
best_performance = performance
best_result = round_result
# Update graph based on performance
self.g_designer.update_graph(
task['id'],
[{'role': role} for role in self.roles.keys()],
{'performance': performance}
)
# Early stopping if perfect performance
if performance == 1.0:
break
return {
'result': best_result,
'performance': best_performance,
'rounds': round_num + 1
}
except Exception as e:
print(f"Error processing task: {str(e)}")
return None
def _process_role(self, role_id: str, task: Dict,
messages: List[Dict], role_state: Dict) -> Dict:
"""Process task with current role."""
try:
if role_id == 'analyst':
return self._analyze_patterns(task, messages, role_state)
elif role_id == 'transformer':
return self._transform_grid(task, messages, role_state)
elif role_id == 'validator':
return self._validate_result(task, messages, role_state)
return None
except Exception as e:
print(f"Error in role processing: {str(e)}")
return None
def _update_role_memory(self, role_id: str, task: Dict, result: Dict):
"""Update role-specific memory with results."""
try:
role = self.roles[role_id]
role['state'] = result
if self.is_string_response:
if 'string_responses' not in role['memory']:
role['memory']['string_responses'] = []
role['memory']['string_responses'].append({
'task': task,
'response': result
})
else:
if result.get('confidence', 0) > 0.8:
task_type = self._get_task_type(task)
if task_type not in role['memory']:
role['memory'][task_type] = []
role['memory'][task_type].append({
'task_features': self._extract_task_features(task),
'solution_approach': result.get('approach'),
'success': True
})
# Limit memory size
for key in role['memory']:
if len(role['memory'][key]) > 100:
role['memory'][key] = role['memory'][key][-100:]
except Exception as e:
print(f"Error updating role memory: {str(e)}")
def _update_performance_histories(self, performance: float,
round_messages: Dict):
"""Update performance history for each role."""
for role_id, result in round_messages.items():
self.roles[role_id]['performance_history'].append({
'timestamp': time.time(),
'performance': performance,
'confidence': result.get('confidence', 0)
})
# Limit history size
if len(self.roles[role_id]['performance_history']) > 1000:
self.roles[role_id]['performance_history'] = \
self.roles[role_id]['performance_history'][-1000:]
def parse_grid_from_response(response) -> Optional[List[List[int]]]:
"""Parse the grid from the agent's response."""
try:
# First try to extract grid from structured response
if isinstance(response, dict) and 'grid' in response:
return response['grid']
# Handle case where response is already a grid
if isinstance(response, list) and all(isinstance(row, list) for row in response):
if all(all(isinstance(val, int) and 0 <= val <= 9 for val in row) for row in response):
return response
# Parse from string response
grid_lines = []
in_grid = False
for line in str(response).split('\n'):
# Look for grid-like patterns
if ('[' in line and ']' in line) or any(str(i) for i in range(10) if str(i) in line):
in_grid = True
# Clean and parse numbers
clean_line = (line.strip()
.strip('[]')
.replace(',', ' ')
.replace(' ', ' '))
try:
row = [int(x) for x in clean_line.split() if x.isdigit()]
if row:
grid_lines.append(row)
except ValueError:
continue
elif in_grid and not line.strip():
break
# Validate parsed grid
if grid_lines:
width = len(grid_lines[0])
if (all(len(row) == width for row in grid_lines) and
all(all(0 <= val <= 9 for val in row) for row in grid_lines)):
return grid_lines
return None
except Exception as e:
print(f"Error parsing grid: {str(e)}")
return None
def generate_prediction(train_pairs: List[Dict], test_input: List[List[int]], trial: int) -> List[List[int]]:
"""
Generate a prediction for a test input using the multi-agent system.
Args:
train_pairs: List of training input/output pairs
test_input: The input grid for prediction
trial: Current trial number (0-2)
Returns:
List[List[int]]: Predicted output grid
"""
try:
# Initialize agents with specific roles
agent_specs = [
{
"role": "Pattern Analyst",
"specialty": "grid_analysis",
"context": {
"task": "Analyze patterns in training examples and identify transformation rules",
"trial": trial + 1
}
},
{
"role": "Grid Transformer",
"specialty": "transformation",
"context": {
"task": "Apply identified patterns to generate output grid",
"trial": trial + 1
}
},
{
"role": "Validator",
"specialty": "validation",
"context": {
"task": "Verify generated grid follows identified patterns",
"trial": trial + 1
}
}
]
# Create task description for the agents
task_description = create_task_description(train_pairs, test_input)
# Initialize the multi-agent system
g_designer = GDesigner()
llm = DynamicLLM(g_designer)
mas = DynamicMultiAgentSystem(g_designer)
# Execute the prediction pipeline
# 1. Pattern Analysis
pattern_analysis = mas.execute_agent_query(
task_description,
agent_specs[0],
context={"phase": "analysis", "trial": trial}
)
# 2. Grid Transformation
transformation_result = mas.execute_agent_query(
task_description,
agent_specs[1],
context={
"phase": "transformation",
"pattern_analysis": pattern_analysis,
"trial": trial
}
)
# 3. Validation
validation_result = mas.execute_agent_query(
task_description,
agent_specs[2],
context={
"phase": "validation",
"transformed_grid": transformation_result,
"trial": trial
}
)
# Parse the final grid from the validation result
predicted_grid = parse_grid_from_response(validation_result)
# Verify grid format
if not is_valid_grid(predicted_grid):
raise ValueError("Invalid grid format generated")
return predicted_grid
except Exception as e:
print(f"Error in generate_prediction: {str(e)}")
return None
def process_all_tasks() -> Iterator[str]:
"""
Process all evaluation tasks sequentially with progress tracking.
Returns:
Iterator[str]: Yields status updates and results as strings
"""
try:
tasks = load_evaluation_tasks()
total_tasks = len(tasks)
results = []
progress = gr.Progress()
progress(0, desc="Initializing...")
for idx, (filename, task) in enumerate(tasks):
try:
progress((idx / total_tasks),
desc=f"Processing task {idx + 1}/{total_tasks}: {filename}")
# Process task and get results
task_result = process_query(task) # Now passing task dict directly
results.append(f"\nTask {idx + 1}/{total_tasks}: {filename}\n{task_result}")
yield "\n".join(results)
except Exception as e:
error_msg = f"\nError processing {filename}: {str(e)}\n"
results.append(error_msg)
yield "\n".join(results)
progress(1.0, desc="Processing complete!")
# Add final summary
summary = ARCEvaluator.get_summary()
summary_text = "\nEvaluation Complete!\n"
summary_text += f"Total tasks processed: {total_tasks}\n"
summary_text += f"Success rate: {summary['success_rate']*100:.2f}%\n"
results.append(summary_text)
yield "\n".join(results)
except Exception as e:
yield f"Fatal error during task processing: {str(e)}"
def process_query(task: Dict) -> str:
try:
arc_loader = ARCDataLoader()
arc_evaluator = ARCEvaluator(max_trials=3)
# Validate the task
if not arc_loader.validate_task_format(task):
return "Error: Invalid ARC task format"
# Process each test case with up to 3 trials
results = []
for test_idx, test_case in enumerate(task['test']):
success = False
predicted_grid = None
for trial in range(3): # 3 trials per test case
try:
# Generate prediction using the agent system
predicted_grid = generate_prediction(task['train'], test_case['input'], trial)
if predicted_grid:
# Parse the grid from the response
predicted_grid = parse_grid_from_response(predicted_grid)
if predicted_grid:
success = arc_evaluator.evaluate_output(predicted_grid, test_case['output'])
arc_evaluator.record_result(f"task_{test_idx}", trial + 1, success)
if success:
break # Stop trials if successful
except Exception as e:
print(f"Trial {trial + 1} failed: {str(e)}")
continue
results.append({
'test_case': test_idx + 1,
'success': success,
'predicted_grid': predicted_grid
})
# Format response
response = "Evaluation Results:\n\n"
for result in results:
response += f"Test Case {result['test_case']}:\n"
response += f"Success: {result['success']}\n"
if result['predicted_grid']:
response += "Predicted Grid:\n"
response += "\n".join(" ".join(str(cell) for cell in row)
for row in result['predicted_grid'])
response += "\n\n"
# Add summary statistics
summary = arc_evaluator.get_summary()
response += f"Overall Success Rate: {summary['success_rate']*100:.2f}%\n"
response += f"Average Trials to Success: {summary['average_trials_to_success']:.2f}\n"
return response
except Exception as e:
return f"Error processing query: {str(e)}"
def create_task_description(train_pairs: List[Dict], test_input: List[List[int]]) -> str:
"""
Create a detailed task description from training pairs and test input.
"""
description = "ARC Task Analysis:\n\nTraining Examples:\n"
# Add training examples
for idx, pair in enumerate(train_pairs):
description += f"\nExample {idx + 1}:\n"
description += "Input Grid:\n"
description += grid_to_string(pair['input'])
description += "\nOutput Grid:\n"
description += grid_to_string(pair['output'])
description += "\n"
# Add test input
description += "\nTest Input Grid:\n"
description += grid_to_string(test_input)
return description
def grid_to_string(grid: List[List[int]]) -> str:
"""
Convert a grid to a string representation.
"""
return "\n".join(" ".join(str(cell) for cell in row) for row in grid)
def is_valid_grid(grid: List[List[int]]) -> bool:
"""
Validate grid format according to ARC specifications.
"""
if not grid or not isinstance(grid, list) or not all(isinstance(row, list) for row in grid):
return False
# Check dimensions
rows = len(grid)
cols = len(grid[0]) if rows > 0 else 0
if rows < 1 or rows > 30 or cols < 1 or cols > 30:
return False
# Check values and consistency
return all(
len(row) == cols and all(isinstance(val, int) and 0 <= val <= 9 for val in row)
for row in grid
)
def execute_agent_query(self, task_description: str, agent_spec: Dict, context: Dict) -> str:
"""
Execute a query for a specific agent role.
Args:
task_description: Description of the task
agent_spec: Specification of the agent role
context: Additional context for the query
Returns:
str: Agent's response
"""
try:
# Create role-specific prompt
role = agent_spec["role"]
specialty = agent_spec["specialty"]
phase = context.get("phase", "unknown")
trial = context.get("trial", 0)
prompt = f"""As the {role} with expertise in {specialty}, analyze the following task.
Task Phase: {phase}
Trial: {trial + 1}/3
{task_description}
Previous Context:
{json.dumps(context, indent=2)}
Your task is to {agent_spec['context']['task']}.
Provide your response in the following format:
1. Analysis: Describe your understanding and approach
2. Implementation: Show your work step by step
3. Result: Provide the final output in grid format using integers 0-9
Response:"""
# Generate response using the LLM
response = self.llm.generate_response(prompt, role=role)
# Record the interaction for learning
self.llm.learn_from_interaction(
role=role,
task=task_description,
success=True, # This should be based on validation
learning="Interaction completed successfully",
feedback=context
)
return response
except Exception as e:
print(f"Error in execute_agent_query: {str(e)}")
return None
def load_evaluation_tasks():
"""Load all JSON files from evaluation directory."""
eval_path = './evaluation'
tasks = []
for filename in sorted(os.listdir(eval_path)):
if filename.endswith('.json'):
with open(os.path.join(eval_path, filename), 'r') as f:
tasks.append((filename, json.load(f)))
return tasks
def grid_to_string(grid: List[List[int]]) -> str:
"""Convert a grid to a formatted string representation."""
if not grid:
return "Empty grid"
# Calculate maximum width needed for each number
max_width = max(len(str(cell)) for row in grid for cell in row)
# Create formatted string with aligned columns
return "\n".join(
" ".join(f"{cell:>{max_width}}" for cell in row)
for row in grid
)
def load_evaluation_tasks() -> List[Tuple[str, Dict]]:
"""Load all JSON files from evaluation directory."""
eval_path = './evaluation'
if not os.path.exists(eval_path):
raise ValueError(f"Evaluation directory not found: {eval_path}")
tasks = []
for filename in sorted(os.listdir(eval_path)):
if filename.endswith('.json'):
try:
with open(os.path.join(eval_path, filename), 'r') as f:
task_data = json.load(f)
# Validate task format
if 'train' in task_data and 'test' in task_data:
tasks.append((filename, task_data))
else:
print(f"Warning: Invalid task format in {filename}")
except Exception as e:
print(f"Error loading {filename}: {str(e)}")
if not tasks:
raise ValueError("No valid task files found in evaluation directory")
return tasks
def create_gradio_interface():
"""Create and configure the Gradio interface for the ARC system."""
import gradio as gr
from datetime import datetime
# Initialize system components
arc_loader = ARCDataLoader()
arc_evaluator = ARCEvaluator()
def save_summary(results: str) -> str:
"""Save evaluation results to a file and return the file path."""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"arc_evaluation_summary_{timestamp}.txt"
with open(filename, "w") as f:
f.write(results)
return filename
def process_and_save():
"""Process tasks and generate downloadable summary."""
results_generator = process_all_tasks()
final_results = None
# Process all results from generator
for results in results_generator:
final_results = results
yield results, None # Update display but not file yet
# Save final results to file
if final_results:
summary_file = save_summary(final_results)
yield final_results, summary_file
with gr.Blocks() as interface:
gr.Markdown("# ARC Task Solver - Automated Evaluation")
gr.Markdown("""
Automated evaluation of ARC tasks using AI agents.
Processing tasks from ./evaluation directory.
Results will update in real-time as tasks are processed.
""")
with gr.Row():
start_button = gr.Button("Start Evaluation")
status = gr.HTML("<div id='progress-status'>Ready to start evaluation...</div>")
with gr.Row():
# Results display
output = gr.Textbox(
label="Evaluation Results",
lines=20,
max_lines=50,
autoscroll=True
)
# Download button for summary
summary_file = gr.File(
label="Download Evaluation Summary",
visible=True,
interactive=False
)
# Add custom CSS
gr.HTML("""
<style>
#progress-status {
margin: 10px 0;
padding: 10px;
background-color: #f0f0f0;
border-radius: 5px;
}
.progress-bar {
height: 20px;
background-color: #4CAF50;
transition: width 0.5s ease-in-out;
}
.output-box {
max-height: 500px;
overflow-y: auto;
}
</style>
""")
# Connect the start button to the processing function
start_button.click(
fn=process_and_save,
outputs=[output, summary_file]
)
return interface
def process_all_tasks() -> Iterator[str]:
"""Process all evaluation tasks sequentially with progress tracking."""
try:
tasks = load_evaluation_tasks()
total_tasks = len(tasks)
results = []
# Add header with timestamp
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
results.append(f"ARC Evaluation Summary\nGenerated: {timestamp}\n")
results.append("=" * 50 + "\n")
progress = gr.Progress()
progress(0, desc="Initializing...")
for idx, (filename, task) in enumerate(tasks):
try:
progress((idx / total_tasks),
desc=f"Processing task {idx + 1}/{total_tasks}: {filename}")
# Process task and get results
task_result = process_query(task)
results.append(f"\nTask {idx + 1}/{total_tasks}: {filename}\n{task_result}")
results.append("-" * 30 + "\n")
yield "\n".join(results)
except Exception as e:
error_msg = f"\nError processing {filename}: {str(e)}\n"
results.append(error_msg)
yield "\n".join(results)
progress(1.0, desc="Processing complete!")
arc_evaluator = ARCEvaluator()
# Add final summary with detailed statistics
summary = arc_evaluator.get_summary()
summary_text = "\nFINAL EVALUATION SUMMARY\n"
summary_text += "=" * 50 + "\n"
summary_text += f"Total tasks processed: {total_tasks}\n"
summary_text += f"Successful tasks: {summary['successful_tasks']}\n"
summary_text += f"Success rate: {summary['success_rate']*100:.2f}%\n"
summary_text += f"Average trials to success: {summary['average_trials_to_success']:.2f}\n"
summary_text += "\nDetailed Statistics:\n"
summary_text += "-" * 30 + "\n"
summary_text += f"Tasks completed: {total_tasks}\n"
summary_text += f"Tasks successful: {summary['successful_tasks']}\n"
summary_text += f"Tasks failed: {total_tasks - summary['successful_tasks']}\n"
results.append(summary_text)
yield "\n".join(results)
except Exception as e:
yield f"Fatal error during task processing: {str(e)}"
def process_arc_task(task_data: Dict, trial: int = 0) -> Dict:
"""Process a single ARC task using the advanced learning framework."""
try:
# Initialize the dynamic multi-agent system if not exists
global dynamic_mas
if 'dynamic_mas' not in globals():
dynamic_mas = DynamicMultiAgentSystem()
# Format task for processing
formatted_task = {
'id': task_data.get('id', f"task_{trial}"),
'train': [
{
'input': pair['input'],
'output': pair['output']
} for pair in task_data['train']
],
'test': [
{
'input': task_data['test'][0]['input']
}
]
}
# Process task with new framework
result = dynamic_mas.process_task(formatted_task)
if result and result.get('result'):
return {
'prediction': result['result'],
'performance': result['performance'],
'rounds': result['rounds'],
'boss_specs': result['boss_specs']
}
return None
except Exception as e:
print(f"Error in ARC task processing: {str(e)}")
return None
def evaluate_prediction(predicted: List[List[int]], actual: List[List[int]]) -> bool:
"""Evaluate if predicted grid matches actual grid."""
try:
if not predicted or not actual:
print("Empty prediction or actual grid")
return False
# Check dimensions match
if len(predicted) != len(actual) or len(predicted[0]) != len(actual[0]):
print(f"Dimension mismatch: predicted {len(predicted)}x{len(predicted[0])} "
f"vs actual {len(actual)}x{len(actual[0])}")
return False
# Check all values match exactly
for i in range(len(predicted)):
for j in range(len(predicted[0])):
if predicted[i][j] != actual[i][j]:
print(f"Mismatch at position [{i}][{j}]: "
f"predicted={predicted[i][j]}, actual={actual[i][j]}")
return False
return True
except Exception as e:
print(f"Error in evaluate_prediction: {str(e)}")
return False
def save_results(results: List[Dict], output_file: str) -> None:
"""Save evaluation results to JSON file with additional metrics."""
try:
# Calculate additional metrics
task_metrics = {
'total_tasks_processed': len(results),
'successful_tasks': sum(1 for r in results if r.get('success', False)),
'average_rounds': statistics.mean(r['rounds'] for r in results),
'average_performance': statistics.mean(r['performance'] for r in results),
'boss_strategy_distribution': _calculate_strategy_distribution(results)
}
# Prepare output data
output_data = {
'timestamp': datetime.now().isoformat(),
'metrics': task_metrics,
'detailed_results': results
}
# Save to file
with open(output_file, 'w') as f:
json.dump(output_data, f, indent=2)
except Exception as e:
print(f"Error saving results: {str(e)}")
def _calculate_strategy_distribution(results: List[Dict]) -> Dict:
"""Calculate distribution of boss strategies used."""
try:
strategy_counts = {}
for result in results:
boss_strategy = str(result.get('boss_strategy', [])) # Convert to string for hashing
strategy_counts[boss_strategy] = strategy_counts.get(boss_strategy, 0) + 1
# Calculate percentages
total = len(results)
return {
strategy: {
'count': count,
'percentage': (count / total) * 100 if total > 0 else 0
}
for strategy, count in strategy_counts.items()
}
except Exception as e:
print(f"Error calculating strategy distribution: {str(e)}")
return {}
def grid_to_string(grid: List[List[int]]) -> str:
"""Convert a grid to a formatted string representation."""
if not grid:
return "Empty grid"
# Calculate maximum width needed for each number
max_width = max(len(str(cell)) for row in grid for cell in row)
# Create formatted string with aligned columns
return "\n".join(
" ".join(f"{cell:>{max_width}}" for cell in row)
for row in grid
)
def evaluate_arc_tasks(task_files: List[str], output_file: str):
"""Evaluate ARC tasks using the new learning framework."""
results = []
total_tasks = len(task_files)
successful_tasks = 0
try:
for trial, task_file in enumerate(task_files):
# Load task
with open(task_file, 'r') as f:
task_data = json.load(f)
# Process task
result = process_arc_task(task_data, trial)
if result:
# Evaluate prediction
correct = evaluate_prediction(
result['prediction'],
task_data['test'][0]['output']
)
# Store results with additional metrics
task_result = {
'task_id': task_data.get('id', f"task_{trial}"),
'success': correct,
'performance': result['performance'],
'rounds': result['rounds'],
'boss_strategy': result['boss_specs']['role_specs'],
'grid_size': {
'input': [len(task_data['test'][0]['input']),
len(task_data['test'][0]['input'][0])],
'output': [len(task_data['test'][0]['output']),
len(task_data['test'][0]['output'][0])]
},
'prediction_visualization': grid_to_string(result['prediction'])
}
results.append(task_result)
if correct:
successful_tasks += 1
# Save progress periodically with detailed metrics
if (trial + 1) % 10 == 0:
save_results(results, output_file)
# Calculate final statistics with additional metrics
final_stats = {
'total_tasks': total_tasks,
'successful_tasks': successful_tasks,
'success_rate': successful_tasks / total_tasks if total_tasks > 0 else 0,
'average_rounds': statistics.mean(r['rounds'] for r in results) if results else 0,
'performance_distribution': {
'mean': statistics.mean(r['performance'] for r in results) if results else 0,
'std': statistics.stdev(r['performance'] for r in results) if len(results) > 1 else 0
},
'timestamp': datetime.now().isoformat()
}
# Save final results with all metrics
save_results(results + [final_stats], output_file)
return results, final_stats
except Exception as e:
print(f"Error in ARC evaluation: {str(e)}")
return None, None
def get_user_input(user_input: str) -> str:
"""Get user input for the query variable."""
try:
return user_input
except Exception as e:
print(f"Error reading input: {str(e)}")
return ""
#This class is for the user query boss llm for creating agents to solve user query tasks.
class BossAgent:
def __init__(self, llm: DynamicLLM):
self.llm = llm
def create_prompt(self, query: str) -> str:
"""Creates structured prompt for boss agent."""
task_history = self.llm.g_designer.experience_buffer[-5:] if hasattr(self.llm, 'g_designer') else []
historical_insights = "\n".join([
f"- Previous task: {exp['task']}, Success: {exp['success']}, Time: {exp['execution_time']:.1f}s"
for exp in task_history
])
return f"""You are the Boss AI responsible for managing a team of AI agents to solve complex tasks.
CURRENT TASK: {query}
HISTORICAL CONTEXT:
{historical_insights if task_history else 'No previous task history available.'}
YOUR RESPONSIBILITIES:
1. Analyze the given task thoroughly
2. Define exactly 3 specialized AI agents that would be best suited for solving this task
3. Ensure the agents have complementary skills and clear responsibilities
4. Consider any insights from previous similar tasks
5. Provide structured response in the required format
Remember:
- A dedicated summarizer agent will be added automatically
- Focus on creating agents with distinct, complementary roles
- Consider both general capabilities and specialized knowledge needed
- Agents should collaborate effectively to solve the task
Please provide your response in the following format:
TASK ANALYSIS:
[Provide a brief analysis of the task's requirements and complexity]
AGENT SPECIFICATIONS:
1. [Role1]
Primary Function: [Main responsibility]
Specialty: [Key areas of expertise]
Plugins: [Relevant tools/capabilities]
Reasoning: [Why this agent is needed]
2. [Role2]
Primary Function: [Main responsibility]
Specialty: [Key areas of expertise]
Plugins: [Relevant tools/capabilities]
Reasoning: [Why this agent is needed]
3. [Role3]
Primary Function: [Main responsibility]
Specialty: [Key areas of expertise]
Plugins: [Relevant tools/capabilities]
Reasoning: [Why this agent is needed]
COLLABORATION STRATEGY:
[Brief description of how these agents should work together]
EXECUTION PLAN:
Recommended Rounds: [Number between 1-8]
Rationale: [Brief explanation for the number of rounds]"""
def parse_response(self, response: str) -> Tuple[List[Dict], int]:
"""Parses boss response to extract agent specifications and round count."""
try:
# Extract agent specifications
agent_specs = []
agent_sections = response.split('\n\n')
for section in agent_sections:
if 'Primary Function:' in section:
lines = section.strip().split('\n')
role = lines[0].strip().replace('1.', '').replace('2.', '').replace('3.', '').strip()
plugins = [p.strip() for p in
next(l for l in lines if 'Plugins:' in l)
.replace('Plugins:', '')
.strip()
.split(',')]
agent_specs.append({
"role": role,
"base": self.llm.model_name,
"plugins": plugins
})
# Extract recommended rounds #Rounds is turned off to save on memory but can be turned on and added easily to the program by adding it to the dynamic agent framework class.
# rounds_match = re.search(r'Recommended Rounds:\s*(\d+)', response)
# rounds = min(max(int(rounds_match.group(1)) if rounds_match else 3, 1), 8)
# Ensure exactly 3 agents
if len(agent_specs) != 3:
raise ValueError("Boss must specify exactly 3 agents")
return agent_specs, #rounds
except Exception as e:
print(f"Error parsing boss response: {str(e)}")
# Return default specifications if parsing fails
return [
{"base": self.llm.model_name, "role": "Analyst", "plugins": ["analysis"]},
{"base": self.llm.model_name, "role": "Expert", "plugins": ["domain"]},
{"base": self.llm.model_name, "role": "Critic", "plugins": ["evaluation"]}
], 3
def process_query(self, query: str) -> Tuple[List[Dict], int]:
"""Process user query and return agent specifications and rounds."""
prompt = self.create_prompt(query)
response = self.llm.generate_response(prompt, role="boss")
return self.parse_response(response)
#These (the 2 functions below) are for processing the queries for the Arc test. They currently are turned off and do not do anything but could be added in place of the pre-generated LLMs in the Dynamic Agent Framework.
'''def _create_boss_prompt(self, query: str) -> str:
"""
Creates a structured prompt for the boss agent to interpret tasks and define specialized agents.
Args:
query (str): The user's input query/task description
Returns:
str: A formatted prompt for the boss agent
"""
# Get historical performance if available
task_history = self.g_designer.experience_buffer[-5:] if self.g_designer.experience_buffer else []
historical_insights = "\n".join([
f"- Previous task: {exp['task']}, Success: {exp['success']}, Time: {exp['execution_time']:.1f}s"
for exp in task_history
])
boss_prompt = f"""You are the Boss AI responsible for managing a team of AI agents to solve complex tasks.
CURRENT TASK: {query}
HISTORICAL CONTEXT:
{historical_insights if task_history else 'No previous task history available.'}
YOUR RESPONSIBILITIES:
1. Analyze the given task thoroughly
2. Define exactly 3 specialized AI agents that would be best suited for solving this task
3. Ensure the agents have complementary skills and clear responsibilities
4. Consider any insights from previous similar tasks
5. Provide structured response in the required format
Remember:
- A dedicated summarizer agent will be added automatically
- Focus on creating agents with distinct, complementary roles
- Consider both general capabilities and specialized knowledge needed
- Agents should collaborate effectively to solve the task
Please provide your response in the following format:
TASK ANALYSIS:
[Provide a brief analysis of the task's requirements and complexity]
AGENT SPECIFICATIONS:
1. [Role1]
Primary Function: [Main responsibility]
Specialty: [Key areas of expertise]
Plugins: [Relevant tools/capabilities]
Reasoning: [Why this agent is needed]
2. [Role2]
Primary Function: [Main responsibility]
Specialty: [Key areas of expertise]
Plugins: [Relevant tools/capabilities]
Reasoning: [Why this agent is needed]
3. [Role3]
Primary Function: [Main responsibility]
Specialty: [Key areas of expertise]
Plugins: [Relevant tools/capabilities]
Reasoning: [Why this agent is needed]
COLLABORATION STRATEGY:
[Brief description of how these agents should work together]
EXECUTION PLAN:
Recommended Rounds: [Number between 1-8]
Rationale: [Brief explanation for the number of rounds]
Based on your analysis, provide the complete response following this format."""
return boss_prompt
def _parse_boss_response(self, response: str) -> Tuple[List[Dict], int]:
"""
Parses the boss's response to extract agent specifications and round count.
Args:
response (str): The boss agent's formatted response
Returns:
Tuple[List[Dict], int]: A tuple containing the list of agent specifications and recommended rounds
"""
try:
# Extract agent specifications
agent_specs = []
agent_sections = response.split('\n\n')
for section in agent_sections:
if 'Primary Function:' in section:
lines = section.strip().split('\n')
role = lines[0].strip().replace('1.', '').replace('2.', '').replace('3.', '').strip()
plugins = [p.strip() for p in
next(l for l in lines if 'Plugins:' in l)
.replace('Plugins:', '')
.strip()
.split(',')]
agent_specs.append({
"role": role,
"base": self.llm.model_name,
"plugins": plugins
})
# Extract recommended rounds
rounds_match = re.search(r'Recommended Rounds:\s*(\d+)', response)
rounds = min(max(int(rounds_match.group(1)) if rounds_match else 3, 1), 8)
# Ensure exactly 3 agents
if len(agent_specs) != 3:
raise ValueError("Boss must specify exactly 3 agents")
return agent_specs, rounds
except Exception as e:
print(f"Error parsing boss response: {str(e)}")
# Return default specifications if parsing fails
return [
{"base": self.llm.model_name, "role": "Analyst", "plugins": ["analysis"]},
{"base": self.llm.model_name, "role": "Expert", "plugins": ["domain"]},
{"base": self.llm.model_name, "role": "Critic", "plugins": ["evaluation"]}
], 3'''
#Function below allows the Boss LLM to handle both grid (evaluation for Arc only) and user queries. Only the generic user query is used but the grid can be easily added in the main def function.
''' #The query handler function does nothing and was replaced with the query processing in the main function.
class QueryHandler:
"""Handles different types of queries and generates appropriate prompts."""
def __init__(self):
self.default_prompt = self._create_default_prompt
self.grid_prompt = self._create_grid_prompt
def create_prompt(self, query: str, is_grid_query: bool = True) -> str:
"""Create appropriate prompt based on query type."""
if not is_grid_query:
return self._create_custom_prompt(query) #This is in case the user wants to use a dataset as this can be turned on by removing the comments to allow the user to use a dataset.
return self._create_grid_prompt(query)
def _create_default_prompt(self, query: str) -> str:
"""Create a standard prompt for non-grid queries."""
return f"""Analyze and respond to the following query:
Query: {query}
Please provide a clear and concise response that addresses the query directly.
Focus on providing practical, implementable solutions.
Your response should include:
1. Direct answer to the query
2. Any relevant explanations or context
3. Specific recommendations or solutions"""
def _create_grid_prompt(self, query: str) -> str:
"""Create a prompt for grid-based ARC tasks."""
return f"""Analyze the following ARC task with grid patterns:
Task Description: {query}
Training Examples:
[Grid examples will be formatted here]
Your analysis should include:
1. Pattern identification
2. Transformation rules
3. Grid-based solution approach
4. Step-by-step implementation
5. Final output grid"""
def _create_custom_prompt(self, query: str) -> str:
"""Create a customized prompt for specific query types."""
return f"""Process the following specialized query:
Query: {query}
Please provide:
1. Direct response
2. Key insights
3. Actionable recommendations
Note: This is a non-grid query that requires specific domain expertise."""
def process_query(self, query: str, is_grid_query: bool = True) -> Dict[str, Any]:
"""Process the query and return appropriate response format."""
prompt = self.create_prompt(query, is_grid_query)
return {
'prompt': prompt,
'is_grid_query': is_grid_query,
'query_type': 'grid' if is_grid_query else 'standard',
'timestamp': time.time()
}'''
def main():
try:
# Get user input for query or use the dataset query
use_dataset_query = False # Set this to False to use user input
if use_dataset_query == True:
evaluator = ARCEvaluator()
interface = create_gradio_interface()
interface.launch()
"""Main execution function."""
# Setup paths
task_dir = "evaluation/tasks"
output_file = f"results/arc_results_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
# Get task files
task_files = glob.glob(os.path.join(task_dir, "*.json"))
# Create results directory if needed
os.makedirs("results", exist_ok=True)
# Run evaluation
results, stats = evaluate_arc_tasks(task_files, output_file)
if results and stats:
print("\nEvaluation Complete!")
print(f"Total Tasks: {stats['total_tasks']}")
print(f"Successful Tasks: {stats['successful_tasks']}")
print(f"Success Rate: {stats['success_rate']:.2%}")
print(f"Results saved to: {output_file}")
else:
print("Evaluation failed!")
else:
llm = DynamicLLM()
boss_agent = BossAgent(llm)
system = DynamicMultiAgentSystem()
def process_query(query: str) -> str:
if not query.strip():
return "Please enter a query"
try:
response = llm.generate_response(query)
return response if response else "No response generated"
except Exception as e:
return f"Error processing query: {str(e)}"
# Create Gradio interface
interface = gr.Interface(
fn=process_query,
inputs=gr.Textbox(lines=3, placeholder="Enter your query..."),
outputs=gr.Textbox(),
title="Dynamic LLM Query System"
)
interface.launch()
except Exception as e:
print(f"Error in main execution: {str(e)}")
if __name__ == "__main__":
main()
#Need to create a switch in the multiagent class so it will take the response from the bossllm class to set-up the agents. if this response is not recieved, then the
#ai agent framework will just handle the dataset as before. This will need to be edited from claude's response. |