Spaces:
Running
Running
File size: 89,013 Bytes
6dc0c9c |
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 |
"""Model adapter registration."""
import math
import os
import re
import sys
from typing import Dict, List, Optional
import warnings
if sys.version_info >= (3, 9):
from functools import cache
else:
from functools import lru_cache as cache
import psutil
import torch
from transformers import (
AutoConfig,
AutoModel,
AutoModelForCausalLM,
AutoModelForSeq2SeqLM,
AutoTokenizer,
LlamaTokenizer,
LlamaForCausalLM,
T5Tokenizer,
)
from src.constants import CPU_ISA
from src.conversation import Conversation, get_conv_template
from src.model.compression import load_compress_model
from src.model.llama_condense_monkey_patch import replace_llama_with_condense
from src.model.model_chatglm import generate_stream_chatglm
from src.model.model_codet5p import generate_stream_codet5p
from src.model.model_falcon import generate_stream_falcon
from src.model.model_yuan2 import generate_stream_yuan2
from src.model.model_exllama import generate_stream_exllama
from src.model.model_xfastertransformer import generate_stream_xft
from src.model.model_cllm import generate_stream_cllm
from src.model.monkey_patch_non_inplace import (
replace_llama_attn_with_non_inplace_operations,
)
from src.modules.awq import AWQConfig, load_awq_quantized
from src.modules.exllama import ExllamaConfig, load_exllama_model
from src.modules.xfastertransformer import load_xft_model, XftConfig
from src.modules.gptq import GptqConfig, load_gptq_quantized
from src.utils import get_gpu_memory
# Check an environment variable to check if we should be sharing Peft model
# weights. When false we treat all Peft models as separate.
peft_share_base_weights = (
os.environ.get("PEFT_SHARE_BASE_WEIGHTS", "false").lower() == "true"
)
ANTHROPIC_MODEL_LIST = (
"claude-1",
"claude-2",
"claude-2.0",
"claude-2.1",
"claude-3-haiku-20240307",
"claude-3-haiku-20240307-vertex",
"claude-3-sonnet-20240229",
"claude-3-sonnet-20240229-vertex",
"claude-3-opus-20240229",
"claude-instant-1",
"claude-instant-1.2",
)
OPENAI_MODEL_LIST = (
"gpt-3.5-turbo",
"gpt-3.5-turbo-0301",
"gpt-3.5-turbo-0613",
"gpt-3.5-turbo-1106",
"gpt-3.5-turbo-0125",
"gpt-4",
"gpt-4-0314",
"gpt-4-0613",
"gpt-4-turbo",
"gpt-4-1106-preview",
"gpt-4-0125-preview",
"gpt-4-turbo-browsing",
"gpt-4-turbo-2024-04-09",
)
class BaseModelAdapter:
"""The base and the default model adapter."""
use_fast_tokenizer = True
def match(self, model_path: str):
return True
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
try:
tokenizer = AutoTokenizer.from_pretrained(
model_path,
use_fast=self.use_fast_tokenizer,
revision=revision,
trust_remote_code=True,
)
except TypeError:
tokenizer = AutoTokenizer.from_pretrained(
model_path, use_fast=False, revision=revision, trust_remote_code=True
)
try:
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
trust_remote_code=True,
**from_pretrained_kwargs,
)
except NameError:
model = AutoModel.from_pretrained(
model_path,
low_cpu_mem_usage=True,
trust_remote_code=True,
**from_pretrained_kwargs,
)
return model, tokenizer
def load_compress_model(self, model_path, device, torch_dtype, revision="main"):
return load_compress_model(
model_path,
device,
torch_dtype,
use_fast=self.use_fast_tokenizer,
revision=revision,
)
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("one_shot")
# A global registry for all model adapters
# TODO (lmzheng): make it a priority queue.
model_adapters: List[BaseModelAdapter] = []
def register_model_adapter(cls):
"""Register a model adapter."""
model_adapters.append(cls())
@cache
def get_model_adapter(model_path: str) -> BaseModelAdapter:
"""Get a model adapter for a model_path."""
model_path_basename = os.path.basename(os.path.normpath(model_path))
# Try the basename of model_path at first
for adapter in model_adapters:
if adapter.match(model_path_basename) and type(adapter) != BaseModelAdapter:
return adapter
# Then try the full path
for adapter in model_adapters:
if adapter.match(model_path):
return adapter
raise ValueError(f"No valid model adapter for {model_path}")
def raise_warning_for_incompatible_cpu_offloading_configuration(
device: str, load_8bit: bool, cpu_offloading: bool
):
if cpu_offloading:
if not load_8bit:
warnings.warn(
"The cpu-offloading feature can only be used while also using 8-bit-quantization.\n"
"Use '--load-8bit' to enable 8-bit-quantization\n"
"Continuing without cpu-offloading enabled\n"
)
return False
if not "linux" in sys.platform:
warnings.warn(
"CPU-offloading is only supported on linux-systems due to the limited compatability with the bitsandbytes-package\n"
"Continuing without cpu-offloading enabled\n"
)
return False
if device != "cuda":
warnings.warn(
"CPU-offloading is only enabled when using CUDA-devices\n"
"Continuing without cpu-offloading enabled\n"
)
return False
return cpu_offloading
def load_model(
model_path: str,
device: str = "cuda",
num_gpus: int = 1,
max_gpu_memory: Optional[str] = None,
dtype: Optional[torch.dtype] = None,
load_8bit: bool = False,
cpu_offloading: bool = False,
gptq_config: Optional[GptqConfig] = None,
awq_config: Optional[AWQConfig] = None,
exllama_config: Optional[ExllamaConfig] = None,
xft_config: Optional[XftConfig] = None,
revision: str = "main",
debug: bool = False,
):
"""Load a model from Hugging Face."""
import accelerate
# get model adapter
adapter = get_model_adapter(model_path)
# Handle device mapping
cpu_offloading = raise_warning_for_incompatible_cpu_offloading_configuration(
device, load_8bit, cpu_offloading
)
if device == "cpu":
kwargs = {"torch_dtype": torch.float32}
if CPU_ISA in ["avx512_bf16", "amx"]:
try:
import intel_extension_for_pytorch as ipex
kwargs = {"torch_dtype": torch.bfloat16}
except ImportError:
warnings.warn(
"Intel Extension for PyTorch is not installed, it can be installed to accelerate cpu inference"
)
elif device == "cuda":
kwargs = {"torch_dtype": torch.float16}
if num_gpus != 1:
kwargs["device_map"] = "auto"
if max_gpu_memory is None:
kwargs[
"device_map"
] = "sequential" # This is important for not the same VRAM sizes
available_gpu_memory = get_gpu_memory(num_gpus)
kwargs["max_memory"] = {
i: str(int(available_gpu_memory[i] * 0.85)) + "GiB"
for i in range(num_gpus)
}
else:
kwargs["max_memory"] = {i: max_gpu_memory for i in range(num_gpus)}
elif device == "mps":
kwargs = {"torch_dtype": torch.float16}
import transformers
version = tuple(int(v) for v in transformers.__version__.split("."))
if version < (4, 35, 0):
# NOTE: Recent transformers library seems to fix the mps issue, also
# it has made some changes causing compatibility issues with our
# original patch. So we only apply the patch for older versions.
# Avoid bugs in mps backend by not using in-place operations.
replace_llama_attn_with_non_inplace_operations()
elif device == "xpu":
kwargs = {"torch_dtype": torch.bfloat16}
# Try to load ipex, while it looks unused, it links into torch for xpu support
try:
import intel_extension_for_pytorch as ipex
except ImportError:
warnings.warn(
"Intel Extension for PyTorch is not installed, but is required for xpu inference."
)
elif device == "npu":
kwargs = {"torch_dtype": torch.float16}
# Try to load ipex, while it looks unused, it links into torch for xpu support
try:
import torch_npu
except ImportError:
warnings.warn("Ascend Extension for PyTorch is not installed.")
else:
raise ValueError(f"Invalid device: {device}")
if cpu_offloading:
# raises an error on incompatible platforms
from transformers import BitsAndBytesConfig
if "max_memory" in kwargs:
kwargs["max_memory"]["cpu"] = (
str(math.floor(psutil.virtual_memory().available / 2**20)) + "Mib"
)
kwargs["quantization_config"] = BitsAndBytesConfig(
load_in_8bit_fp32_cpu_offload=cpu_offloading
)
kwargs["load_in_8bit"] = load_8bit
elif load_8bit:
if num_gpus != 1:
warnings.warn(
"8-bit quantization is not supported for multi-gpu inference."
)
else:
model, tokenizer = adapter.load_compress_model(
model_path=model_path,
device=device,
torch_dtype=kwargs["torch_dtype"],
revision=revision,
)
if debug:
print(model)
return model, tokenizer
elif awq_config and awq_config.wbits < 16:
assert (
awq_config.wbits == 4
), "Currently we only support 4-bit inference for AWQ."
model, tokenizer = load_awq_quantized(model_path, awq_config, device)
if num_gpus != 1:
device_map = accelerate.infer_auto_device_map(
model,
max_memory=kwargs["max_memory"],
no_split_module_classes=[
"OPTDecoderLayer",
"LlamaDecoderLayer",
"BloomBlock",
"MPTBlock",
"DecoderLayer",
],
)
model = accelerate.dispatch_model(
model, device_map=device_map, offload_buffers=True
)
else:
model.to(device)
return model, tokenizer
elif gptq_config and gptq_config.wbits < 16:
model, tokenizer = load_gptq_quantized(model_path, gptq_config)
if num_gpus != 1:
device_map = accelerate.infer_auto_device_map(
model,
max_memory=kwargs["max_memory"],
no_split_module_classes=["LlamaDecoderLayer"],
)
model = accelerate.dispatch_model(
model, device_map=device_map, offload_buffers=True
)
else:
model.to(device)
return model, tokenizer
elif exllama_config:
model, tokenizer = load_exllama_model(model_path, exllama_config)
return model, tokenizer
elif xft_config:
model, tokenizer = load_xft_model(model_path, xft_config)
return model, tokenizer
kwargs["revision"] = revision
if dtype is not None: # Overwrite dtype if it is provided in the arguments.
kwargs["torch_dtype"] = dtype
if os.environ.get("FASTCHAT_USE_MODELSCOPE", "False").lower() == "true":
# download model from ModelScope hub,
# lazy import so that modelscope is not required for normal use.
try:
from modelscope.hub.snapshot_download import snapshot_download
if not os.path.exists(model_path):
model_path = snapshot_download(model_id=model_path, revision=revision)
except ImportError as e:
warnings.warn(
"Use model from www.modelscope.cn need pip install modelscope"
)
raise e
# Load model
model, tokenizer = adapter.load_model(model_path, kwargs)
if (
device == "cpu"
and kwargs["torch_dtype"] is torch.bfloat16
and CPU_ISA is not None
):
model = ipex.optimize(model, dtype=kwargs["torch_dtype"])
if (device == "cuda" and num_gpus == 1 and not cpu_offloading) or device in (
"mps",
"xpu",
"npu",
):
model.to(device)
if device == "xpu":
model = torch.xpu.optimize(model, dtype=kwargs["torch_dtype"], inplace=True)
if debug:
print(model)
return model, tokenizer
def get_conversation_template(model_path: str) -> Conversation:
"""Get the default conversation template."""
adapter = get_model_adapter(model_path)
return adapter.get_default_conv_template(model_path)
def get_generate_stream_function(model: torch.nn.Module, model_path: str):
"""Get the generate_stream function for inference."""
from fastchat.serve.inference import generate_stream
model_type = str(type(model)).lower()
is_peft = "peft" in model_type
is_chatglm = "chatglm" in model_type
is_falcon = "rwforcausallm" in model_type
is_codet5p = "codet5p" in model_type
is_exllama = "exllama" in model_type
is_xft = "xft" in model_type
is_yuan = "yuan" in model_type
is_cllm = "consistency-llm" in model_path.lower()
if is_chatglm:
return generate_stream_chatglm
elif is_falcon:
return generate_stream_falcon
elif is_codet5p:
return generate_stream_codet5p
elif is_exllama:
return generate_stream_exllama
elif is_xft:
return generate_stream_xft
elif is_yuan:
return generate_stream_yuan2
elif is_cllm:
return generate_stream_cllm
elif peft_share_base_weights and is_peft:
# Return a curried stream function that loads the right adapter
# according to the model_name available in this context. This ensures
# the right weights are available.
@torch.inference_mode()
def generate_stream_peft(
model,
tokenizer,
params: Dict,
device: str,
context_len: int,
stream_interval: int = 2,
judge_sent_end: bool = False,
):
model.set_adapter(model_path)
base_model_type = str(type(model.base_model.model))
is_chatglm = "chatglm" in base_model_type
is_falcon = "rwforcausallm" in base_model_type
is_codet5p = "codet5p" in base_model_type
is_exllama = "exllama" in base_model_type
is_xft = "xft" in base_model_type
is_yuan = "yuan" in base_model_type
is_cllm = "consistency-llm" in model_path.lower()
generate_stream_function = generate_stream
if is_chatglm:
generate_stream_function = generate_stream_chatglm
elif is_falcon:
generate_stream_function = generate_stream_falcon
elif is_codet5p:
generate_stream_function = generate_stream_codet5p
elif is_exllama:
generate_stream_function = generate_stream_exllama
elif is_xft:
generate_stream_function = generate_stream_xft
elif is_yuan:
generate_stream_function = generate_stream_yuan2
elif is_cllm:
generate_stream_function = generate_stream_cllm
for x in generate_stream_function(
model,
tokenizer,
params,
device,
context_len,
stream_interval,
judge_sent_end,
):
yield x
return generate_stream_peft
else:
return generate_stream
def add_model_args(parser):
parser.add_argument(
"--model-path",
type=str,
default="lmsys/vicuna-7b-v1.5",
help="The path to the weights. This can be a local folder or a Hugging Face repo ID.",
)
parser.add_argument(
"--revision",
type=str,
default="main",
help="Hugging Face Hub model revision identifier",
)
parser.add_argument(
"--device",
type=str,
choices=["cpu", "cuda", "mps", "xpu", "npu"],
default="cuda",
help="The device type",
)
parser.add_argument(
"--gpus",
type=str,
default=None,
help="A single GPU like 1 or multiple GPUs like 0,2",
)
parser.add_argument("--num-gpus", type=int, default=1)
parser.add_argument(
"--max-gpu-memory",
type=str,
help="The maximum memory per GPU for storing model weights. Use a string like '13Gib'",
)
parser.add_argument(
"--dtype",
type=str,
choices=["float32", "float16", "bfloat16"],
help="Override the default dtype. If not set, it will use float16 on GPU and float32 on CPU.",
default=None,
)
parser.add_argument(
"--load-8bit", action="store_true", help="Use 8-bit quantization"
)
parser.add_argument(
"--cpu-offloading",
action="store_true",
help="Only when using 8-bit quantization: Offload excess weights to the CPU that don't fit on the GPU",
)
parser.add_argument(
"--gptq-ckpt",
type=str,
default=None,
help="Used for GPTQ. The path to the local GPTQ checkpoint.",
)
parser.add_argument(
"--gptq-wbits",
type=int,
default=16,
choices=[2, 3, 4, 8, 16],
help="Used for GPTQ. #bits to use for quantization",
)
parser.add_argument(
"--gptq-groupsize",
type=int,
default=-1,
help="Used for GPTQ. Groupsize to use for quantization; default uses full row.",
)
parser.add_argument(
"--gptq-act-order",
action="store_true",
help="Used for GPTQ. Whether to apply the activation order GPTQ heuristic",
)
parser.add_argument(
"--awq-ckpt",
type=str,
default=None,
help="Used for AWQ. Load quantized model. The path to the local AWQ checkpoint.",
)
parser.add_argument(
"--awq-wbits",
type=int,
default=16,
choices=[4, 16],
help="Used for AWQ. #bits to use for AWQ quantization",
)
parser.add_argument(
"--awq-groupsize",
type=int,
default=-1,
help="Used for AWQ. Groupsize to use for AWQ quantization; default uses full row.",
)
parser.add_argument(
"--enable-exllama",
action="store_true",
help="Used for exllamabv2. Enable exllamaV2 inference framework.",
)
parser.add_argument(
"--exllama-max-seq-len",
type=int,
default=4096,
help="Used for exllamabv2. Max sequence length to use for exllamav2 framework; default 4096 sequence length.",
)
parser.add_argument(
"--exllama-gpu-split",
type=str,
default=None,
help="Used for exllamabv2. Comma-separated list of VRAM (in GB) to use per GPU. Example: 20,7,7",
)
parser.add_argument(
"--exllama-cache-8bit",
action="store_true",
help="Used for exllamabv2. Use 8-bit cache to save VRAM.",
)
parser.add_argument(
"--enable-xft",
action="store_true",
help="Used for xFasterTransformer Enable xFasterTransformer inference framework.",
)
parser.add_argument(
"--xft-max-seq-len",
type=int,
default=4096,
help="Used for xFasterTransformer. Max sequence length to use for xFasterTransformer framework; default 4096 sequence length.",
)
parser.add_argument(
"--xft-dtype",
type=str,
choices=["fp16", "bf16", "int8", "bf16_fp16", "bf16_int8"],
help="Override the default dtype. If not set, it will use bfloat16 for first token and float16 next tokens on CPU.",
default=None,
)
def remove_parent_directory_name(model_path):
"""Remove parent directory name."""
if model_path[-1] == "/":
model_path = model_path[:-1]
return model_path.split("/")[-1]
peft_model_cache = {}
class PeftModelAdapter:
"""Loads any "peft" model and it's base model."""
def match(self, model_path: str):
"""Accepts any model path with "peft" in the name"""
if os.path.exists(os.path.join(model_path, "adapter_config.json")):
return True
return "peft" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
"""Loads the base model then the (peft) adapter weights"""
from peft import PeftConfig, PeftModel
config = PeftConfig.from_pretrained(model_path)
base_model_path = config.base_model_name_or_path
if "peft" in base_model_path:
raise ValueError(
f"PeftModelAdapter cannot load a base model with 'peft' in the name: {config.base_model_name_or_path}"
)
# Basic proof of concept for loading peft adapters that share the base
# weights. This is pretty messy because Peft re-writes the underlying
# base model and internally stores a map of adapter layers.
# So, to make this work we:
# 1. Cache the first peft model loaded for a given base models.
# 2. Call `load_model` for any follow on Peft models.
# 3. Make sure we load the adapters by the model_path. Why? This is
# what's accessible during inference time.
# 4. In get_generate_stream_function, make sure we load the right
# adapter before doing inference. This *should* be safe when calls
# are blocked the same semaphore.
if peft_share_base_weights:
if base_model_path in peft_model_cache:
model, tokenizer = peft_model_cache[base_model_path]
# Super important: make sure we use model_path as the
# `adapter_name`.
model.load_adapter(model_path, adapter_name=model_path)
else:
base_adapter = get_model_adapter(base_model_path)
base_model, tokenizer = base_adapter.load_model(
base_model_path, from_pretrained_kwargs
)
# Super important: make sure we use model_path as the
# `adapter_name`.
model = PeftModel.from_pretrained(
base_model, model_path, adapter_name=model_path
)
peft_model_cache[base_model_path] = (model, tokenizer)
return model, tokenizer
# In the normal case, load up the base model weights again.
base_adapter = get_model_adapter(base_model_path)
base_model, tokenizer = base_adapter.load_model(
base_model_path, from_pretrained_kwargs
)
model = PeftModel.from_pretrained(base_model, model_path)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
"""Uses the conv template of the base model"""
from peft import PeftConfig, PeftModel
config = PeftConfig.from_pretrained(model_path)
if "peft" in config.base_model_name_or_path:
raise ValueError(
f"PeftModelAdapter cannot load a base model with 'peft' in the name: {config.base_model_name_or_path}"
)
base_model_path = config.base_model_name_or_path
base_adapter = get_model_adapter(base_model_path)
return base_adapter.get_default_conv_template(config.base_model_name_or_path)
class VicunaAdapter(BaseModelAdapter):
"Model adapter for Vicuna models (e.g., lmsys/vicuna-7b-v1.5)" ""
use_fast_tokenizer = False
def match(self, model_path: str):
return "vicuna" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
model_path, use_fast=self.use_fast_tokenizer, revision=revision
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
)
self.raise_warning_for_old_weights(model)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
if "v0" in remove_parent_directory_name(model_path):
return get_conv_template("one_shot")
return get_conv_template("vicuna_v1.1")
def raise_warning_for_old_weights(self, model):
if isinstance(model, LlamaForCausalLM) and model.model.vocab_size > 32000:
warnings.warn(
"\nYou are probably using the old Vicuna-v0 model, "
"which will generate unexpected results with the "
"current fastchat.\nYou can try one of the following methods:\n"
"1. Upgrade your weights to the new Vicuna-v1.3: https://github.com/lm-sys/FastChat#vicuna-weights.\n"
"2. Use the old conversation template by `python3 -m fastchat.serve.cli --model-path /path/to/vicuna-v0 --conv-template one_shot`\n"
"3. Downgrade fschat to fschat==0.1.10 (Not recommended).\n"
)
class AiroborosAdapter(BaseModelAdapter):
"""The model adapter for jondurbin/airoboros-*"""
def match(self, model_path: str):
if re.search(r"airoboros|spicyboros", model_path, re.I):
return True
return False
def get_default_conv_template(self, model_path: str) -> Conversation:
if "-3." in model_path or "-3p" in model_path:
return get_conv_template("airoboros_v3")
if "spicyboros" in model_path or re.search(r"-(2\.[2-9]+)", model_path):
return get_conv_template("airoboros_v2")
return get_conv_template("airoboros_v1")
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
if "mpt" not in model_path.lower():
return super().load_model(model_path, from_pretrained_kwargs)
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
trust_remote_code=True,
max_seq_len=8192,
**from_pretrained_kwargs,
)
tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True, use_fast=True
)
return model, tokenizer
class LongChatAdapter(BaseModelAdapter):
"Model adapter for LongChat models (e.g., lmsys/longchat-7b-16k)."
use_fast_tokenizer = False
def match(self, model_path: str):
return "longchat" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
# Apply monkey patch, TODO(Dacheng): Add flash attention support
config = AutoConfig.from_pretrained(model_path, revision=revision)
replace_llama_with_condense(config.rope_scaling["factor"])
tokenizer = AutoTokenizer.from_pretrained(
model_path, use_fast=self.use_fast_tokenizer, revision=revision
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("vicuna_v1.1")
class GoogleT5Adapter(BaseModelAdapter):
"""The model adapter for google/Flan based models, such as Salesforce/codet5p-6b, lmsys/fastchat-t5-3b-v1.0, flan-t5-*, flan-ul2"""
def match(self, model_path: str):
return any(
model_str in model_path.lower()
for model_str in ["flan-", "fastchat-t5", "codet5p"]
)
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = T5Tokenizer.from_pretrained(model_path, revision=revision)
model = AutoModelForSeq2SeqLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
trust_remote_code=True,
**from_pretrained_kwargs,
)
return model, tokenizer
class KoalaAdapter(BaseModelAdapter):
"""The model adapter for Koala"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "koala" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("koala_v1")
class AlpacaAdapter(BaseModelAdapter):
"""The model adapter for Alpaca"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "alpaca" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("alpaca")
class ChatGLMAdapter(BaseModelAdapter):
"""The model adapter for THUDM/chatglm-6b, THUDM/chatglm2-6b"""
def match(self, model_path: str):
return "chatglm" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
if "chatglm3" in model_path.lower():
tokenizer = AutoTokenizer.from_pretrained(
model_path,
encode_special_tokens=True,
trust_remote_code=True,
revision=revision,
)
else:
tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True, revision=revision
)
model = AutoModel.from_pretrained(
model_path, trust_remote_code=True, **from_pretrained_kwargs
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
model_path = model_path.lower()
if "chatglm2" in model_path.lower():
return get_conv_template("chatglm2")
if "chatglm3" in model_path.lower():
return get_conv_template("chatglm3")
return get_conv_template("chatglm")
class CodeGeexAdapter(BaseModelAdapter):
"""The model adapter for THUDM/codegeex-6b, THUDM/codegeex2-6b"""
def match(self, model_path: str):
return "codegeex" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True, revision=revision
)
model = AutoModel.from_pretrained(
model_path, trust_remote_code=True, **from_pretrained_kwargs
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("codegeex")
class DollyV2Adapter(BaseModelAdapter):
"""The model adapter for databricks/dolly-v2-12b"""
def match(self, model_path: str):
return "dolly-v2" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(model_path, revision=revision)
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
)
# 50277 means "### End"
tokenizer.eos_token_id = 50277
model.config.eos_token_id = tokenizer.eos_token_id
model.config.pad_token_id = tokenizer.pad_token_id
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("dolly_v2")
class OasstPythiaAdapter(BaseModelAdapter):
"""The model adapter for OpenAssistant/oasst-sft-4-pythia-12b-epoch-3.5"""
def match(self, model_path: str):
model_path = model_path.lower()
return "oasst" in model_path and "pythia" in model_path
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("oasst_pythia")
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
model, tokenizer = super().load_model(model_path, from_pretrained_kwargs)
model.config.eos_token_id = tokenizer.eos_token_id
model.config.pad_token_id = tokenizer.pad_token_id
return model, tokenizer
class OasstLLaMAAdapter(BaseModelAdapter):
"""The model adapter for OpenAssistant/oasst-sft-7-llama-30b"""
use_fast_tokenizer = False
def match(self, model_path: str):
model_path = model_path.lower()
if "openassistant-sft-7-llama-30b-hf" in model_path:
return True
return "oasst" in model_path and "pythia" not in model_path
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("oasst_llama")
class OpenChat35Adapter(BaseModelAdapter):
"""The model adapter for OpenChat 3.5 (e.g. openchat/openchat_3.5)"""
def match(self, model_path: str):
if "openchat" in model_path.lower() and "3.5" in model_path.lower():
return True
elif "starling-lm" in model_path.lower():
return True
return False
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("openchat_3.5")
class TenyxChatAdapter(BaseModelAdapter):
"""The model adapter for TenyxChat (e.g. tenyx/TenyxChat-7B-v1)"""
def match(self, model_path: str):
return "tenyxchat" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("tenyxchat")
class PythiaAdapter(BaseModelAdapter):
"""The model adapter for any EleutherAI/pythia model"""
def match(self, model_path: str):
return "pythia" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
model, tokenizer = super().load_model(model_path, from_pretrained_kwargs)
model.config.eos_token_id = tokenizer.eos_token_id
model.config.pad_token_id = tokenizer.pad_token_id
return model, tokenizer
class StableLMAdapter(BaseModelAdapter):
"""The model adapter for StabilityAI/stablelm-tuned-alpha-7b"""
def match(self, model_path: str):
return "stablelm" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("stablelm")
class MPTAdapter(BaseModelAdapter):
"""The model adapter for MPT series (mosaicml/mpt-7b-chat, mosaicml/mpt-30b-chat)"""
def match(self, model_path: str):
model_path = model_path.lower()
return "mpt" in model_path and not "airoboros" in model_path
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
trust_remote_code=True,
max_seq_len=8192,
**from_pretrained_kwargs,
)
tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True, revision=revision
)
model.config.eos_token_id = tokenizer.eos_token_id
model.config.pad_token_id = tokenizer.pad_token_id
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
model_path = model_path.lower()
if "mpt-7b-chat" in model_path:
return get_conv_template("mpt-7b-chat")
elif "mpt-30b-chat" in model_path:
return get_conv_template("mpt-30b-chat")
elif "mpt-30b-instruct" in model_path:
return get_conv_template("mpt-30b-instruct")
else:
print(
"Warning: Loading base MPT model with `zero_shot` conversation configuration. "
"If this is not desired, inspect model configurations and names."
)
return get_conv_template("zero_shot")
class BaizeAdapter(BaseModelAdapter):
"""The model adapter for project-baize/baize-v2-7b"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "baize" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("baize")
class RwkvAdapter(BaseModelAdapter):
"""The model adapter for BlinkDL/RWKV-4-Raven"""
def match(self, model_path: str):
return "rwkv-4" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
from fastchat.model.rwkv_model import RwkvModel
model = RwkvModel(model_path)
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
"EleutherAI/pythia-160m", revision=revision
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("rwkv")
class OpenBuddyAdapter(BaseModelAdapter):
"""The model adapter for OpenBuddy/openbuddy-7b-v1.1-bf16-enc"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "openbuddy" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("openbuddy")
class PhoenixAdapter(BaseModelAdapter):
"""The model adapter for FreedomIntelligence/phoenix-inst-chat-7b"""
def match(self, model_path: str):
return "phoenix" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("phoenix")
class ReaLMAdapter(BaseModelAdapter):
"""The model adapter for FreedomIntelligence/ReaLM-7b"""
def match(self, model_path: str):
return "ReaLM" in model_path
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
tokenizer = AutoTokenizer.from_pretrained(model_path, use_fast=True)
model = AutoModelForCausalLM.from_pretrained(
model_path, low_cpu_mem_usage=True, **from_pretrained_kwargs
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("ReaLM-7b-v1")
class ChatGPTAdapter(BaseModelAdapter):
"""The model adapter for ChatGPT"""
def match(self, model_path: str):
return model_path in OPENAI_MODEL_LIST
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
raise NotImplementedError()
def get_default_conv_template(self, model_path: str) -> Conversation:
if "browsing" in model_path:
return get_conv_template("api_based_default")
if "gpt-4-turbo-2024-04-09" in model_path:
return get_conv_template("gpt-4-turbo-2024-04-09")
return get_conv_template("chatgpt")
class AzureOpenAIAdapter(BaseModelAdapter):
"""The model adapter for Azure OpenAI"""
def match(self, model_path: str):
return model_path in ("azure-gpt-35-turbo", "azure-gpt-4")
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
raise NotImplementedError()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("chatgpt")
class PplxAIAdapter(BaseModelAdapter):
"""The model adapter for Perplexity AI"""
def match(self, model_path: str):
return model_path in (
"pplx-7b-online",
"pplx-70b-online",
)
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
raise NotImplementedError()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("pplxai")
class ClaudeAdapter(BaseModelAdapter):
"""The model adapter for Claude"""
def match(self, model_path: str):
return model_path in ANTHROPIC_MODEL_LIST
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
raise NotImplementedError()
def get_default_conv_template(self, model_path: str) -> Conversation:
if "claude-3-haiku" in model_path:
return get_conv_template("claude-3-haiku-20240307")
if "claude-3-sonnet" in model_path:
return get_conv_template("claude-3-sonnet-20240229")
if "claude-3-opus" in model_path:
return get_conv_template("claude-3-opus-20240229")
return get_conv_template("claude")
class BardAdapter(BaseModelAdapter):
"""The model adapter for Bard"""
def match(self, model_path: str):
return model_path == "bard"
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
raise NotImplementedError()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("bard")
class PaLM2Adapter(BaseModelAdapter):
"""The model adapter for PaLM2"""
def match(self, model_path: str):
return model_path == "palm-2"
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
raise NotImplementedError()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("bard")
class GeminiAdapter(BaseModelAdapter):
"""The model adapter for Gemini"""
def match(self, model_path: str):
return "gemini" in model_path.lower() or "bard" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
raise NotImplementedError()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("gemini")
class GeminiDevAdapter(BaseModelAdapter):
"""The model adapter for Gemini 1.5 Pro"""
def match(self, model_path: str):
return "gemini-1.5-pro" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
raise NotImplementedError()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("gemini-dev")
class BiLLaAdapter(BaseModelAdapter):
"""The model adapter for Neutralzz/BiLLa-7B-SFT"""
def match(self, model_path: str):
return "billa" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("billa")
class RedPajamaINCITEAdapter(BaseModelAdapter):
"""The model adapter for togethercomputer/RedPajama-INCITE-7B-Chat"""
def match(self, model_path: str):
return "redpajama-incite" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(model_path, revision=revision)
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("redpajama-incite")
class H2OGPTAdapter(BaseModelAdapter):
"""The model adapter for h2oai/h2ogpt-gm-oasst1-en-2048-open-llama-7b"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "h2ogpt" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("h2ogpt")
class RobinAdapter(BaseModelAdapter):
"""The model adapter for LMFlow/Full-Robin-7b-v2"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "robin" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("Robin")
class SnoozyAdapter(BaseModelAdapter):
"""The model adapter for nomic-ai/gpt4all-13b-snoozy"""
use_fast_tokenizer = False
def match(self, model_path: str):
model_path = model_path.lower()
return "gpt4all" in model_path and "snoozy" in model_path
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("snoozy")
class WizardLMAdapter(BaseModelAdapter):
"""The model adapter for WizardLM/WizardLM-13B-V1.0"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "wizardlm" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
model_path = model_path.lower()
if "13b" in model_path or "30b" in model_path or "70b" in model_path:
return get_conv_template("vicuna_v1.1")
else:
# TODO: use the recommended template for 7B
# (https://huggingface.co./WizardLM/WizardLM-13B-V1.0)
return get_conv_template("one_shot")
class ManticoreAdapter(BaseModelAdapter):
"""The model adapter for openaccess-ai-collective/manticore-13b-chat-pyg"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "manticore" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("manticore")
class GuanacoAdapter(BaseModelAdapter):
"""The model adapter for timdettmers/guanaco-33b-merged"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "guanaco" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
model_path, use_fast=self.use_fast_tokenizer, revision=revision
)
model = AutoModelForCausalLM.from_pretrained(
model_path, low_cpu_mem_usage=True, **from_pretrained_kwargs
)
# Fix a bug in tokenizer config
tokenizer.eos_token_id = model.config.eos_token_id
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("zero_shot")
class ChangGPTAdapter(BaseModelAdapter):
"""The model adapter for lcw99/polyglot-ko-12.8b-chang-instruct-chat"""
def match(self, model_path: str):
model_path = model_path.lower()
return "polyglot" in model_path and "chang" in model_path
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("polyglot_changgpt")
class CamelAdapter(BaseModelAdapter):
"""The model adapter for camel-ai/CAMEL-13B-Combined-Data"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "camel" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("vicuna_v1.1")
class TuluAdapter(BaseModelAdapter):
"""The model adapter for allenai/tulu-30b"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "tulu" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("tulu")
class FalconAdapter(BaseModelAdapter):
"""The model adapter for tiiuae/falcon-40b"""
def match(self, model_path: str):
return "falcon" in model_path.lower() and "chat" not in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
# Strongly suggest using bf16, which is recommended by the author of Falcon
tokenizer = AutoTokenizer.from_pretrained(model_path, revision=revision)
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
trust_remote_code=True,
**from_pretrained_kwargs,
)
# In Falcon tokenizer config and special config there is not any pad token
# Setting `pad_token_id` to 9, which corresponds to special token '>>SUFFIX<<'
tokenizer.pad_token_id = 9
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("falcon")
class FalconChatAdapter(BaseModelAdapter):
def match(self, model_path: str):
return "falcon" in model_path.lower() and "chat" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("falcon-chat")
class TigerBotAdapter(BaseModelAdapter):
"""The model adapter for TigerResearch/tigerbot-7b-sft"""
def match(self, model_path: str):
return "tigerbot" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
model_path,
trust_remote_code=True,
revision=revision,
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
trust_remote_code=True,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("tigerbot")
class BaichuanAdapter(BaseModelAdapter):
"""The model adapter for Baichuan models (e.g., baichuan-inc/Baichuan-7B)"""
def match(self, model_path: str):
return "baichuan" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True, revision=revision
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
trust_remote_code=True,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
# for Baichuan-13B-Chat
if "chat" in model_path.lower():
if "baichuan2" in model_path.lower():
return get_conv_template("baichuan2-chat")
return get_conv_template("baichuan-chat")
return get_conv_template("zero_shot")
class XGenAdapter(BaseModelAdapter):
"""The model adapter for Salesforce/xgen-7b"""
def match(self, model_path: str):
return "xgen" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
trust_remote_code=True,
**from_pretrained_kwargs,
)
tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True, revision=revision
)
model.config.eos_token_id = 50256
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("xgen")
class NousHermesAdapter(BaseModelAdapter):
"""The model adapter for NousResearch/Nous-Hermes-13b"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "nous-hermes" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("alpaca")
class InternLMChatAdapter(BaseModelAdapter):
"""The model adapter for internlm/internlm-chat-7b"""
def match(self, model_path: str):
return "internlm" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
trust_remote_code=True,
**from_pretrained_kwargs,
)
model = model.eval()
if "8k" in model_path.lower():
model.config.max_sequence_length = 8192
tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True, revision=revision
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("internlm-chat")
class StarChatAdapter(BaseModelAdapter):
"""The model adapter for HuggingFaceH4/starchat-beta"""
def match(self, model_path: str):
return "starchat" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("starchat")
class MistralAdapter(BaseModelAdapter):
"""The model adapter for Mistral AI models"""
def match(self, model_path: str):
return "mistral" in model_path.lower() or "mixtral" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
model, tokenizer = super().load_model(model_path, from_pretrained_kwargs)
model.config.eos_token_id = tokenizer.eos_token_id
model.config.pad_token_id = tokenizer.pad_token_id
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("mistral")
class Llama2Adapter(BaseModelAdapter):
"""The model adapter for Llama-2 (e.g., meta-llama/Llama-2-7b-hf)"""
def match(self, model_path: str):
return "llama-2" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
model, tokenizer = super().load_model(model_path, from_pretrained_kwargs)
model.config.eos_token_id = tokenizer.eos_token_id
model.config.pad_token_id = tokenizer.pad_token_id
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("llama-2")
class Llama3Adapter(BaseModelAdapter):
"""The model adapter for Llama-3 (e.g., meta-llama/Meta-Llama-3-8B-Instruct)"""
def match(self, model_path: str):
return "llama-3" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
model, tokenizer = super().load_model(model_path, from_pretrained_kwargs)
model.config.eos_token_id = tokenizer.eos_token_id
model.config.pad_token_id = tokenizer.pad_token_id
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("llama-3")
class CuteGPTAdapter(BaseModelAdapter):
"""The model adapter for CuteGPT"""
def match(self, model_path: str):
return "cutegpt" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
tokenizer = LlamaTokenizer.from_pretrained(model_path)
model = AutoModelForCausalLM.from_pretrained(
model_path, low_cpu_mem_usage=True, **from_pretrained_kwargs
)
tokenizer.eos_token_id = tokenizer.convert_tokens_to_ids("<end>")
model.config.eos_token_id = tokenizer.eos_token_id
model.config.pad_token_id = tokenizer.eos_token_id
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("cutegpt")
class OpenOrcaAdapter(BaseModelAdapter):
"""Model adapter for Open-Orca models which may use different prompt templates
- (e.g. Open-Orca/OpenOrcaxOpenChat-Preview2-13B, Open-Orca/Mistral-7B-OpenOrca)
- `OpenOrcaxOpenChat-Preview2-13B` uses their "OpenChat Llama2 V1" prompt template.
- [Open-Orca/OpenOrcaxOpenChat-Preview2-13B #Prompt Template](https://huggingface.co./Open-Orca/OpenOrcaxOpenChat-Preview2-13B#prompt-template)
- `Mistral-7B-OpenOrca` uses the [OpenAI's Chat Markup Language (ChatML)](https://github.com/openai/openai-python/blob/main/chatml.md)
format, with <|im_start|> and <|im_end|> tokens added to support this.
- [Open-Orca/Mistral-7B-OpenOrca #Prompt Template](https://huggingface.co./Open-Orca/Mistral-7B-OpenOrca#prompt-template)
"""
use_fast_tokenizer = False
def match(self, model_path: str):
return (
"mistral-7b-openorca" in model_path.lower()
or "openorca" in model_path.lower()
)
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
model_path, use_fast=self.use_fast_tokenizer, revision=revision
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
).eval()
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
if "mistral-7b-openorca" in model_path.lower():
return get_conv_template("mistral-7b-openorca")
return get_conv_template("open-orca")
class DolphinAdapter(OpenOrcaAdapter):
"""Model adapter for ehartford/dolphin-2.2.1-mistral-7b"""
def match(self, model_path: str):
return "dolphin" in model_path.lower() and "mistral" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("dolphin-2.2.1-mistral-7b")
class Hermes2Adapter(BaseModelAdapter):
"""Model adapter for teknium/OpenHermes-2.5-Mistral-7B and teknium/OpenHermes-2-Mistral-7B models"""
use_fast_tokenizer = False
def match(self, model_path: str):
return any(
model_str in model_path.lower()
for model_str in ["openhermes-2.5-mistral-7b", "openhermes-2-mistral-7b"]
)
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
model_path, use_fast=self.use_fast_tokenizer, revision=revision
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
).eval()
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("OpenHermes-2.5-Mistral-7B")
class NousHermes2MixtralAdapter(BaseModelAdapter):
"""Model adapter for NousResearch/Nous-Hermes-2-Mixtral-8x7B-DPO model"""
def match(self, model_path: str):
return any(
model_str in model_path.lower()
for model_str in [
"nous-hermes-2-mixtral-8x7b-dpo",
"nous-hermes-2-mixtral-8x7b-sft",
]
)
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("Nous-Hermes-2-Mixtral-8x7B-DPO")
class WizardCoderAdapter(BaseModelAdapter):
"""The model adapter for WizardCoder (e.g., WizardLM/WizardCoder-Python-34B-V1.0)"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "wizardcoder" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
# Same as Alpaca, see :
# https://github.com/nlpxucan/WizardLM/blob/main/WizardCoder/src/inference_wizardcoder.py#L60
return get_conv_template("alpaca")
class QwenChatAdapter(BaseModelAdapter):
"""The model adapter for Qwen/Qwen-7B-Chat
To run this model, you need to ensure additional flash attention installation:
``` bash
git clone https://github.com/Dao-AILab/flash-attention
cd flash-attention && pip install .
pip install csrc/layer_norm
pip install csrc/rotary
```
Since from 2.0, the following change happened
- `flash_attn_unpadded_func` -> `flash_attn_varlen_func`
- `flash_attn_unpadded_qkvpacked_func` -> `flash_attn_varlen_qkvpacked_func`
- `flash_attn_unpadded_kvpacked_func` -> `flash_attn_varlen_kvpacked_func`
You may need to revise the code in: https://huggingface.co./Qwen/Qwen-7B-Chat/blob/main/modeling_qwen.py#L69
to from flash_attn.flash_attn_interface import flash_attn_varlen_func as flash_attn_unpadded_func
"""
def match(self, model_path: str):
return "qwen" in model_path.lower()
def float_set(self, config, option):
config.bf16 = False
config.fp16 = False
config.fp32 = False
if option == "bf16":
config.bf16 = True
elif option == "fp16":
config.fp16 = True
elif option == "fp32":
config.fp32 = True
else:
print("Invalid option. Please choose one from 'bf16', 'fp16' and 'fp32'.")
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
from transformers.generation import GenerationConfig
revision = from_pretrained_kwargs.get("revision", "main")
config = AutoConfig.from_pretrained(
model_path,
trust_remote_code=True,
)
# NOTE: if you use the old version of model file, please remove the comments below
# config.use_flash_attn = False
self.float_set(config, "fp16")
generation_config = GenerationConfig.from_pretrained(
model_path, trust_remote_code=True
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
config=config,
low_cpu_mem_usage=True,
trust_remote_code=True,
**from_pretrained_kwargs,
).eval()
if hasattr(model.config, "use_dynamic_ntk") and model.config.use_dynamic_ntk:
model.config.max_sequence_length = 16384
tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True, revision=revision
)
tokenizer.eos_token_id = config.eos_token_id
tokenizer.bos_token_id = config.bos_token_id
tokenizer.pad_token_id = generation_config.pad_token_id
model.config.eos_token_id = tokenizer.eos_token_id
model.config.bos_token_id = tokenizer.bos_token_id
model.config.pad_token_id = tokenizer.pad_token_id
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("qwen-7b-chat")
class SmaugChatAdapter(BaseModelAdapter):
"""The model adapter for abacusai/Smaug-2-72B."""
def match(self, model_path: str):
return "smaug" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("qwen-7b-chat")
class BGEAdapter(BaseModelAdapter):
"""The model adapter for BGE (e.g., BAAI/bge-large-en-v1.5)"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "bge" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
model = AutoModel.from_pretrained(
model_path,
**from_pretrained_kwargs,
)
tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True, revision=revision
)
if hasattr(model.config, "max_position_embeddings") and hasattr(
tokenizer, "model_max_length"
):
model.config.max_sequence_length = min(
model.config.max_position_embeddings, tokenizer.model_max_length
)
model.use_cls_pooling = True
model.eval()
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("one_shot")
class E5Adapter(BaseModelAdapter):
"""The model adapter for E5 (e.g., intfloat/e5-large-v2)"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "e5-" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
model = AutoModel.from_pretrained(
model_path,
**from_pretrained_kwargs,
)
tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True, revision=revision
)
if hasattr(model.config, "max_position_embeddings") and hasattr(
tokenizer, "model_max_length"
):
model.config.max_sequence_length = min(
model.config.max_position_embeddings, tokenizer.model_max_length
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("one_shot")
class AquilaChatAdapter(BaseModelAdapter):
"""The model adapter for BAAI/Aquila
Now supports:
- BAAI/AquilaChat-7B
- BAAI/AquilaChat2-7B
- BAAI/AquilaChat2-34B
"""
def match(self, model_path: str):
return "aquila" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
model = AutoModelForCausalLM.from_pretrained(
model_path,
low_cpu_mem_usage=True,
trust_remote_code=True,
**from_pretrained_kwargs,
)
model = model.eval()
tokenizer = AutoTokenizer.from_pretrained(
model_path, trust_remote_code=True, revision=revision
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
model_path = model_path.lower()
# See: https://huggingface.co./BAAI/AquilaChat2-34B/blob/4608b75855334b93329a771aee03869dbf7d88cc/predict.py#L347
if "aquilachat2" in model_path:
if "16k" in model_path:
return get_conv_template("aquila")
elif "34b" in model_path:
return get_conv_template("aquila-legacy")
else:
return get_conv_template("aquila-v1")
else:
return get_conv_template("aquila-chat")
class Lamma2ChineseAdapter(BaseModelAdapter):
"""The model adapter for FlagAlpha/LLama2-Chinese sft"""
def match(self, model_path: str):
return "llama2-chinese" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
model_path,
trust_remote_code=True,
revision=revision,
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
trust_remote_code=True,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("llama2-chinese")
class Lamma2ChineseAlpacaAdapter(BaseModelAdapter):
"""The model adapter for ymcui/Chinese-LLaMA-Alpaca sft"""
def match(self, model_path: str):
return "chinese-alpaca" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
model_path,
trust_remote_code=True,
revision=revision,
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
trust_remote_code=True,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("chinese-alpaca2")
class VigogneAdapter(BaseModelAdapter):
"""The model adapter for vigogne (e.g., bofenghuang/vigogne-2-7b-chat)"""
use_fast_tokenizer = False
def match(self, model_path: str):
return bool(re.search(r"vigogne|vigostral", model_path, re.I))
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
model_path,
use_fast=self.use_fast_tokenizer,
trust_remote_code=True,
revision=revision,
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
trust_remote_code=True,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
).eval()
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
if "chat" in model_path.lower():
if "vigostral" in model_path.lower():
return get_conv_template("vigogne_chat_v3")
return get_conv_template("vigogne_chat_v2")
return get_conv_template("vigogne_instruct")
class OpenLLaMaOpenInstructAdapter(BaseModelAdapter):
"""The model adapter for OpenLLaMa-Open-Instruct (e.g., VMware/open-llama-7b-open-instruct)"""
use_fast_tokenizer = False
def match(self, model_path: str):
return (
"open-llama" in model_path.lower() and "open-instruct" in model_path.lower()
)
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
tokenizer = AutoTokenizer.from_pretrained(
model_path,
use_fast=self.use_fast_tokenizer,
trust_remote_code=True,
revision=revision,
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
trust_remote_code=True,
low_cpu_mem_usage=True,
**from_pretrained_kwargs,
).eval()
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("alpaca")
class CodeLlamaAdapter(BaseModelAdapter):
"""The model adapter for CodeLlama (e.g., codellama/CodeLlama-34b-hf)"""
def match(self, model_path: str):
return "codellama" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
model, tokenizer = super().load_model(model_path, from_pretrained_kwargs)
model.config.eos_token_id = tokenizer.eos_token_id
model.config.pad_token_id = tokenizer.pad_token_id
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("llama-2")
class StableVicunaAdapter(BaseModelAdapter):
"""The model adapter for StableVicuna"""
def match(self, model_path: str):
return "stable-vicuna" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
model, tokenizer = super().load_model(model_path, from_pretrained_kwargs)
model.config.eos_token_id = tokenizer.eos_token_id
model.config.pad_token_id = tokenizer.pad_token_id
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("stable-vicuna")
class PhindCodeLlamaAdapter(CodeLlamaAdapter):
"""The model adapter for Phind-CodeLlama (e.g., Phind/Phind-CodeLlama-34B-v2)"""
def match(self, model_path: str):
return "phind-codellama-" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("phind")
class Llama2ChangAdapter(Llama2Adapter):
"""The model adapter for Llama2-ko-chang (e.g., lcw99/llama2-ko-chang-instruct-chat)"""
def match(self, model_path: str):
return "llama2-ko-chang" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("polyglot_changgpt")
class ZephyrAdapter(BaseModelAdapter):
"""The model adapter for Zephyr (e.g. HuggingFaceH4/zephyr-7b-alpha)"""
def match(self, model_path: str):
return "zephyr" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("zephyr")
class NotusAdapter(BaseModelAdapter):
"""The model adapter for Notus (e.g. argilla/notus-7b-v1)"""
def match(self, model_path: str):
return "notus" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("zephyr")
class CatPPTAdapter(BaseModelAdapter):
"""The model adapter for CatPPT (e.g. rishiraj/CatPPT)"""
def match(self, model_path: str):
return "catppt" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("catppt")
class TinyLlamaAdapter(BaseModelAdapter):
"""The model adapter for TinyLlama (e.g. TinyLlama/TinyLlama-1.1B-Chat-v1.0)"""
def match(self, model_path: str):
return "tinyllama" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("TinyLlama")
class XwinLMAdapter(BaseModelAdapter):
"""The model adapter for Xwin-LM V0.1 and V0.2 series of models(e.g., Xwin-LM/Xwin-LM-70B-V0.1)"""
# use_fast_tokenizer = False
def match(self, model_path: str):
return "xwin-lm" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("vicuna_v1.1")
class LemurAdapter(BaseModelAdapter):
"""The model adapter for OpenLemur/lemur-70b-chat-v1"""
use_fast_tokenizer = False
def match(self, model_path: str):
return "lemur-70b-chat" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("lemur-70b-chat")
class PygmalionAdapter(BaseModelAdapter):
"""The model adapter for Pygmalion/Metharme series of models(e.g., PygmalionAI/mythalion-13b)"""
# use_fast_tokenizer = False
def match(self, model_path: str):
return bool(
re.search(r"pygmalion|mythalion|metharme", model_path.lower(), re.I)
)
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("metharme")
class XdanAdapter(BaseModelAdapter):
"""The model adapter for xDAN-AI (e.g. xDAN-AI/xDAN-L1-Chat-RL-v1)"""
def match(self, model_path: str):
return "xdan" in model_path.lower() and "v1" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("xdan-v1")
class MicrosoftOrcaAdapter(BaseModelAdapter):
"""The model adapter for Microsoft/Orca-2 series of models (e.g. Microsoft/Orca-2-7b, Microsoft/Orca-2-13b)"""
use_fast_tokenizer = False # Flag neeeded since tokenizers>=0.13.3 is required for a normal functioning of this module
def match(self, model_path: str):
return "orca-2" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("orca-2")
class YiAdapter(BaseModelAdapter):
"""The model adapter for Yi models"""
def match(self, model_path: str):
return "yi-" in model_path.lower() and "chat" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("Yi-34b-chat")
class DeepseekCoderAdapter(BaseModelAdapter):
"""The model adapter for deepseek-ai's coder models"""
def match(self, model_path: str):
return "deepseek-coder" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("deepseek-coder")
class DeepseekChatAdapter(BaseModelAdapter):
"""The model adapter for deepseek-ai's chat models"""
# Note: that this model will require tokenizer version >= 0.13.3 because the tokenizer class is LlamaTokenizerFast
def match(self, model_path: str):
return "deepseek-llm" in model_path.lower() and "chat" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("deepseek-chat")
class Yuan2Adapter(BaseModelAdapter):
"""The model adapter for Yuan2.0"""
def match(self, model_path: str):
return "yuan2" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
revision = from_pretrained_kwargs.get("revision", "main")
# from_pretrained_kwargs["torch_dtype"] = torch.bfloat16
tokenizer = LlamaTokenizer.from_pretrained(
model_path,
add_eos_token=False,
add_bos_token=False,
eos_token="<eod>",
eod_token="<eod>",
sep_token="<sep>",
revision=revision,
)
tokenizer.add_tokens(
[
"<sep>",
"<pad>",
"<mask>",
"<predict>",
"<FIM_SUFFIX>",
"<FIM_PREFIX>",
"<FIM_MIDDLE>",
"<commit_before>",
"<commit_msg>",
"<commit_after>",
"<jupyter_start>",
"<jupyter_text>",
"<jupyter_code>",
"<jupyter_output>",
"<empty_output>",
],
special_tokens=True,
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
# device_map='auto',
trust_remote_code=True,
**from_pretrained_kwargs,
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("yuan2")
class MetaMathAdapter(BaseModelAdapter):
"""The model adapter for MetaMath models"""
def match(self, model_path: str):
return "metamath" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("metamath")
class BagelAdapter(BaseModelAdapter):
"""Model adapter for jondurbin/bagel-* models"""
def match(self, model_path: str):
return "bagel" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("airoboros_v3")
class SolarAdapter(BaseModelAdapter):
"""The model adapter for upstage/SOLAR-10.7B-Instruct-v1.0"""
def match(self, model_path: str):
return "solar-" in model_path.lower() and "instruct" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("solar")
class SteerLMAdapter(BaseModelAdapter):
"""The model adapter for nvidia/Llama2-70B-SteerLM-Chat"""
def match(self, model_path: str):
return "steerlm-chat" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("steerlm")
class GemmaAdapter(BaseModelAdapter):
"""The model adapter for google/gemma"""
def match(self, model_path: str):
return "gemma" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("gemma")
class LlavaAdapter(BaseModelAdapter):
"""The model adapter for liuhaotian/llava-v1.5 series of models"""
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
# TODO(chris): Implement huggingface-compatible load_model
pass
def match(self, model_path: str):
return "llava" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
model_path = model_path.lower()
if "34b" in model_path:
return get_conv_template("llava-chatml")
return get_conv_template("vicuna_v1.1")
class YuanAdapter(BaseModelAdapter):
"""The model adapter for Yuan"""
def match(self, model_path: str):
return "yuan" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
model, tokenizer = super().load_model(model_path, from_pretrained_kwargs)
tokenizer.add_tokens(
[
"<sep>",
"<pad>",
"<mask>",
"<predict>",
"<FIM_SUFFIX>",
"<FIM_PREFIX>",
"<FIM_MIDDLE>",
"<commit_before>",
"<commit_msg>",
"<commit_after>",
"<jupyter_start>",
"<jupyter_text>",
"<jupyter_code>",
"<jupyter_output>",
"<empty_output>",
],
special_tokens=True,
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("yuan")
class OlmoAdapter(BaseModelAdapter):
"""The model adapter for allenai/OLMo-7B-Instruct"""
def match(self, model_path: str):
return "olmo" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("api_based_default")
class YandexGPTAdapter(BaseModelAdapter):
"""The model adapter for YandexGPT"""
def match(self, model_path: str):
return "yandexgpt" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("yandexgpt")
class CllmAdapter(BaseModelAdapter):
"""The model adapter for CLLM"""
def match(self, model_path: str):
return "consistency-llm" in model_path.lower()
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
config = AutoConfig.from_pretrained(
model_path,
)
tokenizer = AutoTokenizer.from_pretrained(
model_path,
model_max_length=2048,
padding_side="right",
)
model = AutoModelForCausalLM.from_pretrained(
model_path,
config=config,
torch_dtype=torch.bfloat16,
low_cpu_mem_usage=True,
device_map="cuda",
)
return model, tokenizer
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("cllm")
class CohereAdapter(BaseModelAdapter):
"""The model adapter for Cohere"""
def match(self, model_path: str):
return model_path in ["command-r"]
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
raise NotImplementedError()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("api_based_default")
class DBRXAdapter(BaseModelAdapter):
"""The model adapter for Cohere"""
def match(self, model_path: str):
return model_path in ["dbrx-instruct"]
def load_model(self, model_path: str, from_pretrained_kwargs: dict):
raise NotImplementedError()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("api_based_default")
class RekaAdapter(BaseModelAdapter):
"""The model adapter for Reka"""
def match(self, model_path: str):
return "reka" in model_path.lower()
def get_default_conv_template(self, model_path: str) -> Conversation:
return get_conv_template("api_based_default")
# Note: the registration order matters.
# The one registered earlier has a higher matching priority.
register_model_adapter(PeftModelAdapter)
register_model_adapter(StableVicunaAdapter)
register_model_adapter(VicunaAdapter)
register_model_adapter(AiroborosAdapter)
register_model_adapter(LongChatAdapter)
register_model_adapter(GoogleT5Adapter)
register_model_adapter(KoalaAdapter)
register_model_adapter(AlpacaAdapter)
register_model_adapter(ChatGLMAdapter)
register_model_adapter(CodeGeexAdapter)
register_model_adapter(DollyV2Adapter)
register_model_adapter(OasstPythiaAdapter)
register_model_adapter(OasstLLaMAAdapter)
register_model_adapter(OpenChat35Adapter)
register_model_adapter(TenyxChatAdapter)
register_model_adapter(StableLMAdapter)
register_model_adapter(BaizeAdapter)
register_model_adapter(RwkvAdapter)
register_model_adapter(OpenBuddyAdapter)
register_model_adapter(PhoenixAdapter)
register_model_adapter(BardAdapter)
register_model_adapter(PaLM2Adapter)
register_model_adapter(GeminiAdapter)
register_model_adapter(GeminiDevAdapter)
register_model_adapter(GemmaAdapter)
register_model_adapter(ChatGPTAdapter)
register_model_adapter(AzureOpenAIAdapter)
register_model_adapter(ClaudeAdapter)
register_model_adapter(MPTAdapter)
register_model_adapter(BiLLaAdapter)
register_model_adapter(RedPajamaINCITEAdapter)
register_model_adapter(H2OGPTAdapter)
register_model_adapter(RobinAdapter)
register_model_adapter(SnoozyAdapter)
register_model_adapter(WizardLMAdapter)
register_model_adapter(ManticoreAdapter)
register_model_adapter(GuanacoAdapter)
register_model_adapter(CamelAdapter)
register_model_adapter(ChangGPTAdapter)
register_model_adapter(TuluAdapter)
register_model_adapter(FalconChatAdapter)
register_model_adapter(FalconAdapter)
register_model_adapter(TigerBotAdapter)
register_model_adapter(BaichuanAdapter)
register_model_adapter(XGenAdapter)
register_model_adapter(PythiaAdapter)
register_model_adapter(InternLMChatAdapter)
register_model_adapter(StarChatAdapter)
register_model_adapter(Llama2Adapter)
register_model_adapter(Llama3Adapter)
register_model_adapter(CuteGPTAdapter)
register_model_adapter(OpenOrcaAdapter)
register_model_adapter(DolphinAdapter)
register_model_adapter(Hermes2Adapter)
register_model_adapter(NousHermes2MixtralAdapter)
register_model_adapter(NousHermesAdapter)
register_model_adapter(MistralAdapter)
register_model_adapter(WizardCoderAdapter)
register_model_adapter(QwenChatAdapter)
register_model_adapter(AquilaChatAdapter)
register_model_adapter(BGEAdapter)
register_model_adapter(E5Adapter)
register_model_adapter(Lamma2ChineseAdapter)
register_model_adapter(Lamma2ChineseAlpacaAdapter)
register_model_adapter(VigogneAdapter)
register_model_adapter(OpenLLaMaOpenInstructAdapter)
register_model_adapter(ReaLMAdapter)
register_model_adapter(PhindCodeLlamaAdapter)
register_model_adapter(CodeLlamaAdapter)
register_model_adapter(Llama2ChangAdapter)
register_model_adapter(ZephyrAdapter)
register_model_adapter(NotusAdapter)
register_model_adapter(CatPPTAdapter)
register_model_adapter(TinyLlamaAdapter)
register_model_adapter(XwinLMAdapter)
register_model_adapter(LemurAdapter)
register_model_adapter(PygmalionAdapter)
register_model_adapter(MicrosoftOrcaAdapter)
register_model_adapter(XdanAdapter)
register_model_adapter(YiAdapter)
register_model_adapter(PplxAIAdapter)
register_model_adapter(DeepseekCoderAdapter)
register_model_adapter(DeepseekChatAdapter)
register_model_adapter(Yuan2Adapter)
register_model_adapter(MetaMathAdapter)
register_model_adapter(BagelAdapter)
register_model_adapter(SolarAdapter)
register_model_adapter(SteerLMAdapter)
register_model_adapter(LlavaAdapter)
register_model_adapter(YuanAdapter)
register_model_adapter(OlmoAdapter)
register_model_adapter(CohereAdapter)
register_model_adapter(DBRXAdapter)
register_model_adapter(GemmaAdapter)
register_model_adapter(YandexGPTAdapter)
register_model_adapter(CllmAdapter)
register_model_adapter(RekaAdapter)
register_model_adapter(SmaugChatAdapter)
# After all adapters, try the default base adapter.
register_model_adapter(BaseModelAdapter)
|