File size: 79,925 Bytes
b5a178d 777dbcc b5a178d 777dbcc b5a178d 777dbcc b5a178d 777dbcc b5a178d 777dbcc b5a178d 777dbcc 464c02e b5a178d 777dbcc b5a178d 777dbcc b5a178d 777dbcc b5a178d 777dbcc 50c753d 777dbcc b5a178d 777dbcc b5a178d 777dbcc b5a178d |
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 |
# coding=utf-8
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
New VGCN-BERT model
Paper: https://arxiv.org/abs/2004.05707
"""
from collections import Counter
import math
from typing import Dict, List, Optional, Set, Tuple, Union
import scipy.sparse as sp
import numpy as np
import torch
from torch import nn
from torch.nn import BCEWithLogitsLoss, CrossEntropyLoss, MSELoss
from transformers.configuration_utils import PretrainedConfig
from transformers.activations import get_activation
from transformers.deepspeed import is_deepspeed_zero3_enabled
from transformers.modeling_outputs import (
BaseModelOutput,
MaskedLMOutput,
MultipleChoiceModelOutput,
QuestionAnsweringModelOutput,
SequenceClassifierOutput,
TokenClassifierOutput,
)
from transformers.modeling_utils import PreTrainedModel
from transformers.tokenization_utils import PreTrainedTokenizerBase
from transformers.pytorch_utils import apply_chunking_to_forward, find_pruneable_heads_and_indices, prune_linear_layer
from transformers.utils import (
add_code_sample_docstrings,
add_start_docstrings,
add_start_docstrings_to_model_forward,
logging,
replace_return_docstrings,
)
from .configuration_vgcn_bert import VGCNBertConfig
logger = logging.get_logger(__name__)
_CHECKPOINT_FOR_DOC = "zhibinlu/vgcn-bert-distilbert-base-uncased"
_CONFIG_FOR_DOC = "VGCNBertConfig"
VGCNBERT_PRETRAINED_MODEL_ARCHIVE_LIST = [
"zhibinlu/vgcn-bert-distilbert-base-uncased",
# See all VGCN-BERT models at https://huggingface.co/models?filter=vgcn-bert
]
# Word Graph construction utils #
ENGLISH_STOP_WORDS = frozenset(
{
"herself",
"each",
"him",
"been",
"only",
"yourselves",
"into",
"where",
"them",
"very",
"we",
"that",
"re",
"too",
"some",
"what",
"those",
"me",
"whom",
"have",
"yours",
"an",
"during",
"any",
"nor",
"ourselves",
"has",
"do",
"when",
"about",
"same",
"our",
"then",
"himself",
"their",
"all",
"no",
"a",
"hers",
"off",
"why",
"how",
"more",
"between",
"until",
"not",
"over",
"your",
"by",
"here",
"most",
"above",
"up",
"of",
"is",
"after",
"from",
"being",
"i",
"as",
"other",
"so",
"her",
"ours",
"on",
"because",
"against",
"and",
"out",
"had",
"these",
"at",
"both",
"down",
"you",
"can",
"she",
"few",
"the",
"if",
"it",
"to",
"but",
"its",
"be",
"he",
"once",
"further",
"such",
"there",
"through",
"are",
"themselves",
"which",
"in",
"now",
"his",
"yourself",
"this",
"were",
"below",
"should",
"my",
"myself",
"am",
"or",
"while",
"itself",
"again",
"with",
"they",
"will",
"own",
"than",
"before",
"under",
"was",
"for",
"who",
}
)
def _normalize_adj(adj):
"""Symmetrically normalize adjacency matrix."""
rowsum = np.array(adj.sum(1)) # D-degree matrix
d_inv_sqrt = np.power(rowsum, -0.5).flatten()
d_inv_sqrt[np.isinf(d_inv_sqrt)] = 0.0
d_mat_inv_sqrt = sp.diags(d_inv_sqrt)
return adj.dot(d_mat_inv_sqrt).transpose().dot(d_mat_inv_sqrt)
def _scipy_to_torch(sparse):
sparse = sparse.tocoo() if sparse.getformat() != "coo" else sparse
i = torch.LongTensor(np.vstack((sparse.row, sparse.col)))
v = torch.from_numpy(sparse.data)
return torch.sparse_coo_tensor(i, v, torch.Size(sparse.shape)).coalesce()
def _delete_special_terms(words: list, terms: set):
return set([w for w in words if w not in terms])
def _build_pmi_graph(
texts: List[str],
tokenizer: PreTrainedTokenizerBase,
window_size=20,
algorithm="npmi",
edge_threshold=0.0,
remove_stopwords=False,
min_freq_to_keep=2,
) -> Tuple[sp.csr_matrix, Dict[str, int], Dict[int, int]]:
"""
Build statistical word graph from text samples using PMI or NPMI algorithm.
"""
# Tokenize the text samples. The tokenizer should be same as that in the combined Bert-like model.
# Remove stopwords and special terms
# Get vocabulary and the word frequency
words_to_remove = (
set({"[CLS]", "[SEP]"}).union(ENGLISH_STOP_WORDS) if remove_stopwords else set({"[CLS]", "[SEP]"})
)
vocab_counter = Counter()
texts_words = []
for t in texts:
words = tokenizer.tokenize(t)
words = _delete_special_terms(words, words_to_remove)
if len(words) > 0:
vocab_counter.update(Counter(words))
texts_words.append(words)
# Set [PAD] as the head of vocabulary
# Remove word with freq<n and re generate texts
new_vocab_counter = Counter({"[PAD]": 0})
new_vocab_counter.update(
Counter({k: v for k, v in vocab_counter.items() if v >= min_freq_to_keep})
if min_freq_to_keep > 1
else vocab_counter
)
vocab_counter = new_vocab_counter
# Generate new texts by removing words with freq<n
if min_freq_to_keep > 1:
texts_words = [list(filter(lambda w: vocab_counter[w] >= min_freq_to_keep, words)) for words in texts_words]
texts = [" ".join(words).strip() for words in texts_words if len(words) > 0]
vocab_size = len(vocab_counter)
vocab = list(vocab_counter.keys())
assert vocab[0] == "[PAD]"
vocab_indices = {k: i for i, k in enumerate(vocab)}
# Get the pieces from sliding windows
windows = []
for t in texts:
words = t.split()
word_ids = [vocab_indices[w] for w in words]
length = len(word_ids)
if length <= window_size:
windows.append(word_ids)
else:
for j in range(length - window_size + 1):
word_ids = word_ids[j : j + window_size]
windows.append(word_ids)
# Get the window-count that every word appeared (count 1 for the same window).
# Get window-count that every word-pair appeared (count 1 for the same window).
vocab_window_counter = Counter()
word_pair_window_counter = Counter()
for word_ids in windows:
word_ids = list(set(word_ids))
vocab_window_counter.update(Counter(word_ids))
word_pair_window_counter.update(
Counter(
[
f(i, j)
# (word_ids[i], word_ids[j])
for i in range(1, len(word_ids))
for j in range(i)
# adding inverse pair
for f in (lambda x, y: (word_ids[x], word_ids[y]), lambda x, y: (word_ids[y], word_ids[x]))
]
)
)
# Calculate NPMI
vocab_adj_row = []
vocab_adj_col = []
vocab_adj_weight = []
total_windows = len(windows)
for wid_pair in word_pair_window_counter.keys():
i, j = wid_pair
pair_count = word_pair_window_counter[wid_pair]
i_count = vocab_window_counter[i]
j_count = vocab_window_counter[j]
value = (
(log(1.0 * i_count * j_count / (total_windows**2)) / log(1.0 * pair_count / total_windows) - 1)
if algorithm == "npmi"
else (log((1.0 * pair_count / total_windows) / (1.0 * i_count * j_count / (total_windows**2))))
)
if value > edge_threshold:
vocab_adj_row.append(i)
vocab_adj_col.append(j)
vocab_adj_weight.append(value)
# Build vocabulary adjacency matrix
vocab_adj = sp.csr_matrix(
(vocab_adj_weight, (vocab_adj_row, vocab_adj_col)),
shape=(vocab_size, vocab_size),
dtype=np.float32,
)
vocab_adj.setdiag(1.0)
# Padding the first row and column, "[PAD]" is the first word in the vocabulary.
assert vocab_adj[0, :].sum() == 1
assert vocab_adj[:, 0].sum() == 1
vocab_adj[:, 0] = 0
vocab_adj[0, :] = 0
wgraph_id_to_tokenizer_id_map = {v: tokenizer.vocab[k] for k, v in vocab_indices.items()}
wgraph_id_to_tokenizer_id_map = dict(sorted(wgraph_id_to_tokenizer_id_map.items()))
return (
vocab_adj,
vocab_indices,
wgraph_id_to_tokenizer_id_map,
)
def _build_predefined_graph(
words_relations: List[Tuple[str, str, float]], tokenizer: PreTrainedTokenizerBase, remove_stopwords: bool = False
) -> Tuple[sp.csr_matrix, Dict[str, int], Dict[int, int]]:
"""
Build pre-defined wgraph from a list of word pairs and their pre-defined relations (edge value).
"""
# Tokenize the text samples. The tokenizer should be same as that in the combined Bert-like model.
# Remove stopwords and special terms
# Get vocabulary and the word frequency
words_to_remove = (
set({"[CLS]", "[SEP]"}).union(ENGLISH_STOP_WORDS) if remove_stopwords else set({"[CLS]", "[SEP]"})
)
vocab_counter = Counter({"[PAD]": 0})
word_pairs = {}
for w1, w2, v in words_relations:
w1_subwords = tokenizer.tokenize(w1)
w1_subwords = _delete_special_terms(w1_subwords, words_to_remove)
w2_subwords = tokenizer.tokenize(w2)
w2_subwords = _delete_special_terms(w2_subwords, words_to_remove)
vocab_counter.update(Counter(w1_subwords))
vocab_counter.update(Counter(w2_subwords))
for sw1 in w1_subwords:
for sw2 in w2_subwords:
if sw1 != sw2:
word_pairs.setdefault((sw1, sw2), v)
vocab_size = len(vocab_counter)
vocab = list(vocab_counter.keys())
assert vocab[0] == "[PAD]"
vocab_indices = {k: i for i, k in enumerate(vocab)}
# bulid adjacency matrix
vocab_adj_row = []
vocab_adj_col = []
vocab_adj_weight = []
for (w1, w2), v in word_pairs.items():
vocab_adj_row.append(vocab_indices[w1])
vocab_adj_col.append(vocab_indices[w2])
vocab_adj_weight.append(v)
# adding inverse
vocab_adj_row.append(vocab_indices[w2])
vocab_adj_col.append(vocab_indices[w1])
vocab_adj_weight.append(v)
# Build vocabulary adjacency matrix
vocab_adj = sp.csr_matrix(
(vocab_adj_weight, (vocab_adj_row, vocab_adj_col)),
shape=(vocab_size, vocab_size),
dtype=np.float32,
)
vocab_adj.setdiag(1.0)
# Padding the first row and column, "[PAD]" is the first word in the vocabulary.
assert vocab_adj[0, :].sum() == 1
assert vocab_adj[:, 0].sum() == 1
vocab_adj[:, 0] = 0
vocab_adj[0, :] = 0
wgraph_id_to_tokenizer_id_map = {v: tokenizer.vocab[k] for k, v in vocab_indices.items()}
wgraph_id_to_tokenizer_id_map = dict(sorted(wgraph_id_to_tokenizer_id_map.items()))
return (
vocab_adj,
vocab_indices,
wgraph_id_to_tokenizer_id_map,
)
# TODO: build knowledge graph from a list of RDF triples
class WordGraphBuilder:
"""
Word graph based on adjacency matrix, construct from text samples or pre-defined word-pair relations
You may (or not) first preprocess the text before build the graph,
e.g. Stopword removal, String cleaning, Stemming, Nomolization, Lemmatization
Params:
`rows`: List[str] of text samples, or pre-defined word-pair relations: List[Tuple[str, str, float]]
`tokenizer`: The same pretrained tokenizer that is used for the model late.
`window_size`: Available only for statistics generation (rows is text samples).
Size of the sliding window for collecting the pieces of text
and further calculate the NPMI value, default is 20.
`algorithm`: Available only for statistics generation (rows is text samples) -- "npmi" or "pmi", default is "npmi".
`edge_threshold`: Available only for statistics generation (rows is text samples). Graph edge value threshold, default is 0. Edge value is between -1 to 1.
`remove_stopwords`: Build word graph with the words that are not stopwords, default is False.
`min_freq_to_keep`: Available only for statistics generation (rows is text samples). Build word graph with the words that occurred at least n times in the corpus, default is 2.
Properties:
`adjacency_matrix`: scipy.sparse.csr_matrix, the word graph in sparse adjacency matrix form.
`vocab_indices`: indices of word graph vocabulary words.
`wgraph_id_to_tokenizer_id_map`: map from word graph vocabulary word id to tokenizer vocabulary word id.
"""
def __init__(self):
super().__init__()
def __call__(
self,
rows: list,
tokenizer: PreTrainedTokenizerBase,
window_size=20,
algorithm="npmi",
edge_threshold=0.0,
remove_stopwords=False,
min_freq_to_keep=2,
):
if type(rows[0]) == tuple:
(
adjacency_matrix,
_,
wgraph_id_to_tokenizer_id_map,
) = _build_predefined_graph(rows, tokenizer, remove_stopwords)
else:
(
adjacency_matrix,
_,
wgraph_id_to_tokenizer_id_map,
) = _build_pmi_graph(
rows, tokenizer, window_size, algorithm, edge_threshold, remove_stopwords, min_freq_to_keep
)
adjacency_matrix=_scipy_to_torch(_normalize_adj(adjacency_matrix)) if adjacency_matrix is not None else None
return adjacency_matrix, wgraph_id_to_tokenizer_id_map
class VgcnParameterList(nn.ParameterList):
def __init__(self, values=None, requires_grad=True) -> None:
super().__init__(values)
self.requires_grad = requires_grad
def _load_from_state_dict(
self, state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
):
keys = filter(lambda x: x.startswith(prefix), state_dict.keys())
for k in keys:
self.append(nn.Parameter(state_dict[k], requires_grad=self.requires_grad))
super()._load_from_state_dict(
state_dict, prefix, local_metadata, strict, missing_keys, unexpected_keys, error_msgs
)
for i in range(len(self)):
if self[i].layout is torch.sparse_coo and not self[i].is_coalesced():
self[i] = self[i].coalesce()
self[i].requires_grad = self.requires_grad
class VocabGraphConvolution(nn.Module):
"""Vocabulary GCN module.
Params:
`wgraphs`: List of vocabulary graph, normally adjacency matrix
`wgraph_id_to_tokenizer_id_maps`: wgraph.vocabulary to tokenizer.vocabulary id-mapping
`hid_dim`: The hidden dimension after `GCN=XAW` (GCN layer)
`out_dim`: The output dimension after `out=Relu(XAW)W` (GCN output)
`activation`: The activation function in `out=act(XAW)W`
`dropout_rate`: The dropout probabilitiy in `out=dropout(act(XAW))W`.
Inputs:
`X_dv`: the feature of mini batch document, can be TF-IDF (batch, vocab), or word embedding (batch, word_embedding_dim, vocab)
Outputs:
The graph embedding representation, dimension (batch, `out_dim`) or (batch, word_embedding_dim, `out_dim`)
"""
def __init__(
self,
hid_dim: int,
out_dim: int,
wgraphs: Optional[list] = None,
wgraph_id_to_tokenizer_id_maps: Optional[List[dict]] = None,
activation=None,
dropout_rate=0.1,
):
super().__init__()
self.hid_dim = hid_dim
self.out_dim = out_dim
self.fc_hg = nn.Linear(hid_dim, out_dim)
self.fc_hg._is_vgcn_linear = True
self.activation = get_activation(activation) if activation else None
self.dropout = nn.Dropout(dropout_rate) if dropout_rate > 0 else None
# TODO: add a Linear layer for vgcn fintune/pretrain task
# after init.set_wgraphs, _init_weights will set again the mode (transparent,normal,uniform)
# but if load wgraph parameters from checkpoint/pretrain, the mode weights will be updated from to checkpoint
# you can call again set_parameters to change the mode
self.set_wgraphs(wgraphs, wgraph_id_to_tokenizer_id_maps)
def set_parameters(self, mode="transparent"):
"""Set the parameters of the model (transparent, uniform, normal)."""
assert mode in ["transparent", "uniform", "normal"]
for n, p in self.named_parameters():
if n.startswith("W"):
nn.init.constant_(p, 1.0) if mode == "transparent" else nn.init.normal_(
p, mean=0.0, std=0.02
) if mode == "normal" else nn.init.kaiming_uniform_(p, a=math.sqrt(5))
self.fc_hg.weight.data.fill_(1.0) if mode == "transparent" else self.fc_hg.weight.data.normal_(
mean=0.0, std=0.02
) if mode == "normal" else nn.init.kaiming_uniform_(self.fc_hg.weight, a=math.sqrt(5))
self.fc_hg.bias.data.zero_()
def set_wgraphs(
self,
wgraphs: Optional[list] = None,
wgraph_id_to_tokenizer_id_maps: Optional[List[dict]] = None,
mode="transparent",
):
assert (
wgraphs is None
and wgraph_id_to_tokenizer_id_maps is None
or wgraphs is not None
and wgraph_id_to_tokenizer_id_maps is not None
)
self.wgraphs: VgcnParameterList = (
self._prepare_wgraphs(wgraphs) if wgraphs else VgcnParameterList(requires_grad=False)
)
self.gvoc_ordered_tokenizer_id_arrays, self.tokenizer_id_to_wgraph_id_arrays = VgcnParameterList(
requires_grad=False
), VgcnParameterList(requires_grad=False)
if wgraph_id_to_tokenizer_id_maps:
(
self.gvoc_ordered_tokenizer_id_arrays,
self.tokenizer_id_to_wgraph_id_arrays,
) = self._prepare_inverted_arrays(wgraph_id_to_tokenizer_id_maps)
self.W_vh_list = VgcnParameterList(requires_grad=True)
self.W_vh_list._is_vgcn_weights = True
for g in self.wgraphs:
self.W_vh_list.append(nn.Parameter(torch.randn(g.shape[0], self.hid_dim)))
# self.W_vh_list.append(nn.Parameter(torch.ones(g.shape[0], self.hid_dim)))
self.set_parameters(mode=mode)
def _prepare_wgraphs(self, wgraphs: list) -> VgcnParameterList:
# def _zero_padding_graph(adj_matrix: torch.Tensor):
# if adj_matrix.layout is not torch.sparse_coo:
# adj_matrix=adj_matrix.to_sparse_coo()
# indices=adj_matrix.indices()+1
# padded_adj= torch.sparse_coo_tensor(indices=indices, values=adj_matrix.values(), size=(adj_matrix.shape[0]+1,adj_matrix.shape[1]+1))
# return padded_adj.coalesce()
glist = VgcnParameterList(requires_grad=False)
for g in wgraphs:
assert g.layout is torch.sparse_coo
# g[0,:] and g[:,0] should be 0
assert 0 not in g.indices()
glist.append(nn.Parameter(g.coalesce(), requires_grad=False))
return glist
def _prepare_inverted_arrays(self, wgraph_id_to_tokenizer_id_maps: List[dict]):
wgraph_id_to_tokenizer_id_maps = [dict(sorted(m.items())) for m in wgraph_id_to_tokenizer_id_maps]
assert all([list(m.keys())[-1] == len(m) - 1 for m in wgraph_id_to_tokenizer_id_maps])
gvoc_ordered_tokenizer_id_arrays = VgcnParameterList(
[
nn.Parameter(torch.LongTensor(list(m.values())), requires_grad=False)
for m in wgraph_id_to_tokenizer_id_maps
],
requires_grad=False,
)
tokenizer_id_to_wgraph_id_arrays = VgcnParameterList(
[
nn.Parameter(torch.zeros(max(m.values()) + 1, dtype=torch.long), requires_grad=False)
for m in wgraph_id_to_tokenizer_id_maps
],
requires_grad=False,
)
for m, t in zip(wgraph_id_to_tokenizer_id_maps, tokenizer_id_to_wgraph_id_arrays):
for graph_id, tok_id in m.items():
t[tok_id] = graph_id
return gvoc_ordered_tokenizer_id_arrays, tokenizer_id_to_wgraph_id_arrays
def get_subgraphs(self, adj_matrix: torch.Tensor, gx_ids: torch.LongTensor):
device = gx_ids.device
batch_size = gx_ids.shape[0]
batch_masks = torch.any(
torch.any(
(adj_matrix.indices().view(-1) == gx_ids.unsqueeze(-1)).view(batch_size, gx_ids.shape[1], 2, -1), dim=1
),
dim=1,
)
nnz_len = len(adj_matrix.values())
batch_values = adj_matrix.values().unsqueeze(0).repeat(batch_size, 1)
batch_values = batch_values.view(-1)[batch_masks.view(-1)]
batch_positions = torch.arange(batch_size, device=device).unsqueeze(1).repeat(1, nnz_len)
indices = torch.cat([batch_positions.view(1, -1), adj_matrix.indices().repeat(1, batch_size)], dim=0)
indices = indices[batch_masks.view(-1).expand(3, -1)].view(3, -1)
batch_sub_adj_matrix = torch.sparse_coo_tensor(
indices=indices,
values=batch_values.view(-1),
size=(batch_size, adj_matrix.size(0), adj_matrix.size(1)),
dtype=adj_matrix.dtype,
device=device,
)
return batch_sub_adj_matrix.coalesce()
def forward(self, word_embeddings: nn.Embedding, input_ids: torch.Tensor): # , position_ids: torch.Tensor = None):
if not self.wgraphs:
raise ValueError(
"No wgraphs is provided. There are 3 ways to initalize wgraphs:"
" instantiate VGCN_BERT with wgraphs, or call model.vgcn_bert.set_wgraphs(),"
" or load from_pretrained/checkpoint (make sure there is wgraphs in checkpoint"
" or you should call set_wgraphs)."
)
device = input_ids.device
batch_size = input_ids.shape[0]
word_emb_dim = word_embeddings.weight.shape[1]
gx_ids_list = []
# positon_embeddings_in_gvocab_order_list=[]
for m in self.tokenizer_id_to_wgraph_id_arrays:
# tmp_ids is still in sentence order, but value is graph id, e.g. [0, 5, 2, 2, 0, 10,0]
# 0 means no correspond graph id (like padding in graph), so we need to replace it with 0
tmp_ids = input_ids.clone()
tmp_ids[tmp_ids > len(m) - 1] = 0
tmp_ids = m[tmp_ids]
# # position in graph is meaningless and computationally expensive
# if position_ids:
# position_ids_in_g=torch.zeros(g.shape[0], dtype=torch.LongTensor)
# # maybe gcn_swop_eye in original vgcn_bert preprocess is more efficient?
# for p_id, g_id in zip(position_ids, tmp_ids):
# position_ids_in_g[g_id]=p_id
# position_embeddings_in_g=self.position_embeddings(position_ids_in_g)
# position_embeddings_in_g*=position_ids_in_g>0
# positon_embeddings_in_gvocab_order_list.append(position_embeddings_in_g)
gx_ids_list.append(torch.unique(tmp_ids, dim=1))
# G_embedding=(act(V1*A1_sub*W1_vh)+act(V2*A2_sub*W2_vh))*W_hg
fused_H = torch.zeros((batch_size, word_emb_dim, self.hid_dim), device=device)
for gv_ids, g, gx_ids, W_vh in zip( # , position_in_gvocab_ev
self.gvoc_ordered_tokenizer_id_arrays,
self.wgraphs,
gx_ids_list,
self.W_vh_list,
# positon_embeddings_in_gvocab_order_list,
):
# batch_A1_sub*W1_vh, batch_A2_sub*W2_vh, ...
sub_wgraphs = self.get_subgraphs(g, gx_ids)
H_vh = torch.bmm(sub_wgraphs, W_vh.unsqueeze(0).expand(batch_size, *W_vh.shape))
# V1*batch_A1_sub*W1_vh, V2*batch_A2_sub*W2_vh, ...
gvocab_ev = word_embeddings(gv_ids).t()
# if position_ids:
# gvocab_ev += position_in_gvocab_ev
H_eh = gvocab_ev.matmul(H_vh)
# fc -> act -> dropout
if self.activation:
H_eh = self.activation(H_eh)
if self.dropout:
H_eh = self.dropout(H_eh)
fused_H += H_eh
# fused_H=LayerNorm(fused_H) # embedding assemble layer will do LayerNorm
out_ge = self.fc_hg(fused_H).transpose(1, 2)
# self.dropout(out_ge) # embedding assemble layer will do dropout
return out_ge
# UTILS AND BUILDING BLOCKS OF THE ARCHITECTURE #
def create_sinusoidal_embeddings(n_pos: int, dim: int, out: torch.Tensor):
if is_deepspeed_zero3_enabled():
import deepspeed
with deepspeed.zero.GatheredParameters(out, modifier_rank=0):
if torch.distributed.get_rank() == 0:
_create_sinusoidal_embeddings(n_pos=n_pos, dim=dim, out=out)
else:
_create_sinusoidal_embeddings(n_pos=n_pos, dim=dim, out=out)
def _create_sinusoidal_embeddings(n_pos: int, dim: int, out: torch.Tensor):
position_enc = np.array([[pos / np.power(10000, 2 * (j // 2) / dim) for j in range(dim)] for pos in range(n_pos)])
out.requires_grad = False
out[:, 0::2] = torch.FloatTensor(np.sin(position_enc[:, 0::2]))
out[:, 1::2] = torch.FloatTensor(np.cos(position_enc[:, 1::2]))
out.detach_()
class VGCNEmbeddings(nn.Module):
"""Construct the embeddings from word, VGCN graph, position and token_type embeddings."""
def __init__(
self,
config: PretrainedConfig,
wgraphs: Optional[list] = None,
wgraph_id_to_tokenizer_id_maps: Optional[List[dict]] = None,
):
super().__init__()
self.word_embeddings = nn.Embedding(config.vocab_size, config.dim, padding_idx=config.pad_token_id)
self.position_embeddings = nn.Embedding(config.max_position_embeddings, config.dim)
self.vgcn_graph_embds_dim = config.vgcn_graph_embds_dim
self.vgcn = VocabGraphConvolution(
hid_dim=config.vgcn_hidden_dim,
out_dim=config.vgcn_graph_embds_dim,
wgraphs=wgraphs,
wgraph_id_to_tokenizer_id_maps=wgraph_id_to_tokenizer_id_maps,
activation=config.vgcn_activation,
dropout_rate=config.vgcn_dropout,
)
if config.sinusoidal_pos_embds:
create_sinusoidal_embeddings(
n_pos=config.max_position_embeddings, dim=config.dim, out=self.position_embeddings.weight
)
self.LayerNorm = nn.LayerNorm(config.dim, eps=1e-12)
self.dropout = nn.Dropout(config.dropout)
self.register_buffer(
"position_ids", torch.arange(config.max_position_embeddings).expand((1, -1)), persistent=False
)
def forward(self, input_ids: torch.Tensor, input_embeds: Optional[torch.Tensor] = None) -> torch.Tensor:
"""
Parameters:
input_ids (torch.Tensor):
torch.tensor(bs, max_seq_length) The token ids to embed.
input_ids is mandatory in vgcn-bert.
Returns: torch.tensor(bs, max_seq_length, dim) The embedded tokens (plus position embeddings, no token_type
embeddings)
"""
# input_ids is mandatory in vgcn-bert
input_embeds = self.word_embeddings(input_ids) # (bs, max_seq_length, dim)
# device = input_embeds.device
# input_lengths = (
# (input_ids > 0).sum(-1)
# if input_ids is not None
# else torch.ones(input_embeds.size(0), device=device, dtype=torch.int64) * input_embeds.size(1)
# )
seq_length = input_embeds.size(1)
# Setting the position-ids to the registered buffer in constructor, it helps
# when tracing the model without passing position-ids, solves
# isues similar to issue #5664
if hasattr(self, "position_ids"):
position_ids = self.position_ids[:, :seq_length]
else:
position_ids = torch.arange(seq_length, dtype=torch.long, device=input_ids.device) # (max_seq_length)
position_ids = position_ids.unsqueeze(0).expand_as(input_ids) # (bs, max_seq_length)
position_embeddings = self.position_embeddings(position_ids) # (bs, max_seq_length, dim)
embeddings = input_embeds + position_embeddings # (bs, max_seq_length, dim)
if self.vgcn_graph_embds_dim > 0:
graph_embeds = self.vgcn(self.word_embeddings, input_ids) # , position_ids)
# vgcn_words_embeddings = input_embeds.clone()
# for i in range(self.vgcn_graph_embds_dim):
# tmp_pos = (input_lengths - 2 - self.vgcn_graph_embds_dim + 1 + i) + torch.arange(
# 0, input_embeds.shape[0]
# ).to(device) * input_embeds.shape[1]
# vgcn_words_embeddings.flatten(start_dim=0, end_dim=1)[tmp_pos, :] = graph_embeds[:, :, i]
embeddings = torch.cat([embeddings, graph_embeds], dim=1) # (bs, max_seq_length+graph_emb_dim_size, dim)
embeddings = self.LayerNorm(embeddings) # (bs, max_seq_length, dim)
embeddings = self.dropout(embeddings) # (bs, max_seq_length, dim)
return embeddings
class MultiHeadSelfAttention(nn.Module):
def __init__(self, config: PretrainedConfig):
super().__init__()
self.n_heads = config.n_heads
self.dim = config.dim
self.dropout = nn.Dropout(p=config.attention_dropout)
# Have an even number of multi heads that divide the dimensions
if self.dim % self.n_heads != 0:
# Raise value errors for even multi-head attention nodes
raise ValueError(f"self.n_heads: {self.n_heads} must divide self.dim: {self.dim} evenly")
self.q_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
self.k_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
self.v_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
self.out_lin = nn.Linear(in_features=config.dim, out_features=config.dim)
self.pruned_heads: Set[int] = set()
self.attention_head_size = self.dim // self.n_heads
def prune_heads(self, heads: List[int]):
if len(heads) == 0:
return
heads, index = find_pruneable_heads_and_indices(
heads, self.n_heads, self.attention_head_size, self.pruned_heads
)
# Prune linear layers
self.q_lin = prune_linear_layer(self.q_lin, index)
self.k_lin = prune_linear_layer(self.k_lin, index)
self.v_lin = prune_linear_layer(self.v_lin, index)
self.out_lin = prune_linear_layer(self.out_lin, index, dim=1)
# Update hyper params
self.n_heads = self.n_heads - len(heads)
self.dim = self.attention_head_size * self.n_heads
self.pruned_heads = self.pruned_heads.union(heads)
def forward(
self,
query: torch.Tensor,
key: torch.Tensor,
value: torch.Tensor,
mask: torch.Tensor,
head_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
) -> Tuple[torch.Tensor, ...]:
"""
Parameters:
query: torch.tensor(bs, seq_length, dim)
key: torch.tensor(bs, seq_length, dim)
value: torch.tensor(bs, seq_length, dim)
mask: torch.tensor(bs, seq_length)
Returns:
weights: torch.tensor(bs, n_heads, seq_length, seq_length) Attention weights context: torch.tensor(bs,
seq_length, dim) Contextualized layer. Optional: only if `output_attentions=True`
"""
bs, q_length, dim = query.size()
k_length = key.size(1)
# assert dim == self.dim, f'Dimensions do not match: {dim} input vs {self.dim} configured'
# assert key.size() == value.size()
dim_per_head = self.dim // self.n_heads
mask_reshp = (bs, 1, 1, k_length)
def shape(x: torch.Tensor) -> torch.Tensor:
"""separate heads"""
return x.view(bs, -1, self.n_heads, dim_per_head).transpose(1, 2)
def unshape(x: torch.Tensor) -> torch.Tensor:
"""group heads"""
return x.transpose(1, 2).contiguous().view(bs, -1, self.n_heads * dim_per_head)
q = shape(self.q_lin(query)) # (bs, n_heads, q_length, dim_per_head)
k = shape(self.k_lin(key)) # (bs, n_heads, k_length, dim_per_head)
v = shape(self.v_lin(value)) # (bs, n_heads, k_length, dim_per_head)
q = q / math.sqrt(dim_per_head) # (bs, n_heads, q_length, dim_per_head)
scores = torch.matmul(q, k.transpose(2, 3)) # (bs, n_heads, q_length, k_length)
mask = (mask == 0).view(mask_reshp).expand_as(scores) # (bs, n_heads, q_length, k_length)
scores = scores.masked_fill(
mask, torch.tensor(torch.finfo(scores.dtype).min)
) # (bs, n_heads, q_length, k_length)
weights = nn.functional.softmax(scores, dim=-1) # (bs, n_heads, q_length, k_length)
weights = self.dropout(weights) # (bs, n_heads, q_length, k_length)
# Mask heads if we want to
if head_mask is not None:
weights = weights * head_mask
context = torch.matmul(weights, v) # (bs, n_heads, q_length, dim_per_head)
context = unshape(context) # (bs, q_length, dim)
context = self.out_lin(context) # (bs, q_length, dim)
if output_attentions:
return (context, weights)
else:
return (context,)
class FFN(nn.Module):
def __init__(self, config: PretrainedConfig):
super().__init__()
self.dropout = nn.Dropout(p=config.dropout)
self.chunk_size_feed_forward = config.chunk_size_feed_forward
self.seq_len_dim = 1
self.lin1 = nn.Linear(in_features=config.dim, out_features=config.hidden_dim)
self.lin2 = nn.Linear(in_features=config.hidden_dim, out_features=config.dim)
self.activation = get_activation(config.activation)
def forward(self, input: torch.Tensor) -> torch.Tensor:
return apply_chunking_to_forward(self.ff_chunk, self.chunk_size_feed_forward, self.seq_len_dim, input)
def ff_chunk(self, input: torch.Tensor) -> torch.Tensor:
x = self.lin1(input)
x = self.activation(x)
x = self.lin2(x)
x = self.dropout(x)
return x
class TransformerBlock(nn.Module):
def __init__(self, config: PretrainedConfig):
super().__init__()
# Have an even number of Configure multi-heads
if config.dim % config.n_heads != 0:
raise ValueError(f"config.n_heads {config.n_heads} must divide config.dim {config.dim} evenly")
self.attention = MultiHeadSelfAttention(config)
self.sa_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
self.ffn = FFN(config)
self.output_layer_norm = nn.LayerNorm(normalized_shape=config.dim, eps=1e-12)
def forward(
self,
x: torch.Tensor,
attn_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
) -> Tuple[torch.Tensor, ...]:
"""
Parameters:
x: torch.tensor(bs, seq_length, dim)
attn_mask: torch.tensor(bs, seq_length)
Returns:
sa_weights: torch.tensor(bs, n_heads, seq_length, seq_length) The attention weights ffn_output:
torch.tensor(bs, seq_length, dim) The output of the transformer block contextualization.
"""
# Self-Attention
sa_output = self.attention(
query=x,
key=x,
value=x,
mask=attn_mask,
head_mask=head_mask,
output_attentions=output_attentions,
)
if output_attentions:
sa_output, sa_weights = sa_output # (bs, seq_length, dim), (bs, n_heads, seq_length, seq_length)
else: # To handle these `output_attentions` or `output_hidden_states` cases returning tuples
if type(sa_output) != tuple:
raise TypeError(f"sa_output must be a tuple but it is {type(sa_output)} type")
sa_output = sa_output[0]
sa_output = self.sa_layer_norm(sa_output + x) # (bs, seq_length, dim)
# Feed Forward Network
ffn_output = self.ffn(sa_output) # (bs, seq_length, dim)
ffn_output: torch.Tensor = self.output_layer_norm(ffn_output + sa_output) # (bs, seq_length, dim)
output = (ffn_output,)
if output_attentions:
output = (sa_weights,) + output
return output
class Transformer(nn.Module):
def __init__(self, config: PretrainedConfig):
super().__init__()
self.n_layers = config.n_layers
self.layer = nn.ModuleList([TransformerBlock(config) for _ in range(config.n_layers)])
def forward(
self,
x: torch.Tensor,
attn_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
output_attentions: bool = False,
output_hidden_states: bool = False,
return_dict: Optional[bool] = None,
) -> Union[BaseModelOutput, Tuple[torch.Tensor, ...]]: # docstyle-ignore
"""
Parameters:
x: torch.tensor(bs, seq_length, dim) Input sequence embedded.
attn_mask: torch.tensor(bs, seq_length) Attention mask on the sequence.
Returns:
hidden_state: torch.tensor(bs, seq_length, dim) Sequence of hidden states in the last (top)
layer all_hidden_states: Tuple[torch.tensor(bs, seq_length, dim)]
Tuple of length n_layers with the hidden states from each layer.
Optional: only if output_hidden_states=True
all_attentions: Tuple[torch.tensor(bs, n_heads, seq_length, seq_length)]
Tuple of length n_layers with the attention weights from each layer
Optional: only if output_attentions=True
"""
all_hidden_states = () if output_hidden_states else None
all_attentions = () if output_attentions else None
hidden_state = x
for i, layer_module in enumerate(self.layer):
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_state,)
layer_outputs = layer_module(
x=hidden_state, attn_mask=attn_mask, head_mask=head_mask[i], output_attentions=output_attentions
)
hidden_state = layer_outputs[-1]
if output_attentions:
if len(layer_outputs) != 2:
raise ValueError(f"The length of the layer_outputs should be 2, but it is {len(layer_outputs)}")
attentions = layer_outputs[0]
all_attentions = all_attentions + (attentions,)
else:
if len(layer_outputs) != 1:
raise ValueError(f"The length of the layer_outputs should be 1, but it is {len(layer_outputs)}")
# Add last layer
if output_hidden_states:
all_hidden_states = all_hidden_states + (hidden_state,)
if not return_dict:
return tuple(v for v in [hidden_state, all_hidden_states, all_attentions] if v is not None)
return BaseModelOutput(
last_hidden_state=hidden_state, hidden_states=all_hidden_states, attentions=all_attentions
)
# INTERFACE FOR ENCODER AND TASK SPECIFIC MODEL #
# Copied from transformers.models.distilbert.modeling_distilbert.DistilBertPreTrainedModel with DistilBert->VGCNBert,distilbert->vgcn_bert
class VGCNBertPreTrainedModel(PreTrainedModel):
"""
An abstract class to handle weights initialization and a simple interface for downloading and loading pretrained
models.
"""
config_class = VGCNBertConfig
load_tf_weights = None
base_model_prefix = "vgcn_bert"
def _init_weights(self, module: nn.Module):
"""Initialize the weights."""
if isinstance(module, nn.Linear):
# Slightly different from the TF version which uses truncated_normal for initialization
# cf https://github.com/pytorch/pytorch/pull/5617
if getattr(module, "_is_vgcn_linear", False):
if self.config.vgcn_weight_init_mode == "transparent":
module.weight.data.fill_(1.0)
elif self.config.vgcn_weight_init_mode == "normal":
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
elif self.config.vgcn_weight_init_mode == "uniform":
nn.init.kaiming_uniform_(module.weight, a=math.sqrt(5))
else:
raise ValueError(f"Unknown VGCN-BERT weight init mode: {self.config.vgcn_weight_init_mode}.")
if module.bias is not None:
module.bias.data.zero_()
else:
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.bias is not None:
module.bias.data.zero_()
elif isinstance(module, nn.Embedding):
module.weight.data.normal_(mean=0.0, std=self.config.initializer_range)
if module.padding_idx is not None:
module.weight.data[module.padding_idx].zero_()
elif isinstance(module, nn.LayerNorm):
module.bias.data.zero_()
module.weight.data.fill_(1.0)
elif isinstance(module, nn.ParameterList):
if getattr(module, "_is_vgcn_weights", False):
for p in module:
if self.config.vgcn_weight_init_mode == "transparent":
nn.init.constant_(p, 1.0)
elif self.config.vgcn_weight_init_mode == "normal":
nn.init.normal_(p, mean=0.0, std=self.config.initializer_range)
elif self.config.vgcn_weight_init_mode == "uniform":
nn.init.kaiming_uniform_(p, a=math.sqrt(5))
else:
raise ValueError(f"Unknown VGCN-BERT weight init mode: {self.config.vgcn_weight_init_mode}.")
VGCNBERT_START_DOCSTRING = r"""
This model inherits from [`PreTrainedModel`]. Check the superclass documentation for the generic methods the
library implements for all its model (such as downloading or saving, resizing the input embeddings, pruning heads
etc.)
This model is also a PyTorch [torch.nn.Module](https://pytorch.org/docs/stable/nn.html#torch.nn.Module) subclass.
Use it as a regular PyTorch Module and refer to the PyTorch documentation for all matter related to general usage
and behavior.
Parameters:
config ([`VGCNBertConfig`]): Model configuration class with all the parameters of the model.
Initializing with a config file does not load the weights associated with the model, only the
configuration. Check out the [`~PreTrainedModel.from_pretrained`] method to load the model weights.
"""
VGCNBERT_INPUTS_DOCSTRING = r"""
Args:
input_ids (`torch.LongTensor` of shape `({0})`):
Indices of input sequence tokens in the vocabulary.
Indices can be obtained using [`AutoTokenizer`]. See [`PreTrainedTokenizer.encode`] and
[`PreTrainedTokenizer.__call__`] for details.
[What are input IDs?](../glossary#input-ids)
attention_mask (`torch.FloatTensor` of shape `({0})`, *optional*):
Mask to avoid performing attention on padding token indices. Mask values selected in `[0, 1]`:
- 1 for tokens that are **not masked**,
- 0 for tokens that are **masked**.
[What are attention masks?](../glossary#attention-mask)
head_mask (`torch.FloatTensor` of shape `(num_heads,)` or `(num_layers, num_heads)`, *optional*):
Mask to nullify selected heads of the self-attention modules. Mask values selected in `[0, 1]`:
- 1 indicates the head is **not masked**,
- 0 indicates the head is **masked**.
inputs_embeds (`torch.FloatTensor` of shape `({0}, hidden_size)`, *optional*):
Optionally, instead of passing `input_ids` you can choose to directly pass an embedded representation. This
is useful if you want more control over how to convert `input_ids` indices into associated vectors than the
model's internal embedding lookup matrix.
output_attentions (`bool`, *optional*):
Whether or not to return the attentions tensors of all attention layers. See `attentions` under returned
tensors for more detail.
output_hidden_states (`bool`, *optional*):
Whether or not to return the hidden states of all layers. See `hidden_states` under returned tensors for
more detail.
return_dict (`bool`, *optional*):
Whether or not to return a [`~utils.ModelOutput`] instead of a plain tuple.
"""
@add_start_docstrings(
"The bare VGCN-BERT encoder/transformer outputting raw hidden-states without any specific head on top.",
VGCNBERT_START_DOCSTRING,
)
# Copied from transformers.models.distilbert.modeling_distilbert.DistilBertModel with DISTILBERT->VGCNBERT,DistilBert->VGCNBert
class VGCNBertModel(VGCNBertPreTrainedModel):
def __init__(
self,
config: PretrainedConfig,
wgraphs: Optional[list] = None,
wgraph_id_to_tokenizer_id_maps: Optional[List[dict]] = None,
):
super().__init__(config)
self.embeddings = VGCNEmbeddings(config, wgraphs, wgraph_id_to_tokenizer_id_maps) # Graph Embeddings
self.transformer = Transformer(config) # Encoder
self.wgraph_builder = WordGraphBuilder()
# Initialize weights and apply final processing
self.post_init()
def set_wgraphs(
self,
wgraphs: Optional[list] = None,
wgraph_id_to_tokenizer_id_maps: Optional[List[dict]] = None,
mode="transparent",
):
self.embeddings.vgcn.set_wgraphs(wgraphs, wgraph_id_to_tokenizer_id_maps, mode)
def get_position_embeddings(self) -> nn.Embedding:
"""
Returns the position embeddings
"""
return self.embeddings.position_embeddings
def resize_position_embeddings(self, new_num_position_embeddings: int):
"""
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
Arguments:
new_num_position_embeddings (`int`):
The number of new position embedding matrix. If position embeddings are learned, increasing the size
will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
size will add correct vectors at the end following the position encoding algorithm, whereas reducing
the size will remove vectors from the end.
"""
num_position_embeds_diff = new_num_position_embeddings - self.config.max_position_embeddings
# no resizing needs to be done if the length stays the same
if num_position_embeds_diff == 0:
return
logger.info(f"Setting `config.max_position_embeddings={new_num_position_embeddings}`...")
self.config.max_position_embeddings = new_num_position_embeddings
old_position_embeddings_weight = self.embeddings.position_embeddings.weight.clone()
self.embeddings.position_embeddings = nn.Embedding(self.config.max_position_embeddings, self.config.dim)
if self.config.sinusoidal_pos_embds:
create_sinusoidal_embeddings(
n_pos=self.config.max_position_embeddings, dim=self.config.dim, out=self.position_embeddings.weight
)
else:
with torch.no_grad():
if num_position_embeds_diff > 0:
self.embeddings.position_embeddings.weight[:-num_position_embeds_diff] = nn.Parameter(
old_position_embeddings_weight
)
else:
self.embeddings.position_embeddings.weight = nn.Parameter(
old_position_embeddings_weight[:num_position_embeds_diff]
)
# move position_embeddings to correct device
self.embeddings.position_embeddings.to(self.device)
def get_input_embeddings(self) -> nn.Embedding:
return self.embeddings.word_embeddings
def set_input_embeddings(self, new_embeddings: nn.Embedding):
self.embeddings.word_embeddings = new_embeddings
def _prune_heads(self, heads_to_prune: Dict[int, List[List[int]]]):
"""
Prunes heads of the model. heads_to_prune: dict of {layer_num: list of heads to prune in this layer} See base
class PreTrainedModel
"""
for layer, heads in heads_to_prune.items():
self.transformer.layer[layer].attention.prune_heads(heads)
@add_start_docstrings_to_model_forward(VGCNBERT_INPUTS_DOCSTRING.format("batch_size, num_choices"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=BaseModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[BaseModelOutput, Tuple[torch.Tensor, ...]]:
output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions
output_hidden_states = (
output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states
)
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
if input_ids is not None and inputs_embeds is not None:
raise ValueError("You cannot specify both input_ids and inputs_embeds at the same time")
elif input_ids is not None:
input_shape = input_ids.size()
elif inputs_embeds is not None:
input_shape = inputs_embeds.size()[:-1]
else:
raise ValueError("You have to specify either input_ids or inputs_embeds")
device = input_ids.device if input_ids is not None else inputs_embeds.device
if attention_mask is None:
attention_mask = torch.ones(input_shape, device=device) # (bs, seq_length)
# Prepare head mask if needed
head_mask = self.get_head_mask(head_mask, self.config.num_hidden_layers)
embeddings = self.embeddings(input_ids, inputs_embeds) # (bs, seq_length, dim)
if self.embeddings.vgcn_graph_embds_dim > 0:
attention_mask = torch.cat(
[attention_mask, torch.ones((input_shape[0], self.embeddings.vgcn_graph_embds_dim), device=device)],
dim=1,
)
return self.transformer(
x=embeddings,
attn_mask=attention_mask,
head_mask=head_mask,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
@add_start_docstrings(
"""VGCNBert Model with a `masked language modeling` head on top.""",
VGCNBERT_START_DOCSTRING,
)
# Copied from transformers.models.distilbert.modeling_distilbert.DistilBertForMaskedLM with DISTILBERT->VGCNBERT,DistilBert->VGCNBert,distilbert->vgcn_bert
class VGCNBertForMaskedLM(VGCNBertPreTrainedModel):
_keys_to_ignore_on_load_missing = ["vocab_projector.weight"]
def __init__(
self,
config: PretrainedConfig,
wgraphs: Optional[list] = None,
wgraph_id_to_tokenizer_id_maps: Optional[List[dict]] = None,
):
super().__init__(config)
self.activation = get_activation(config.activation)
self.vgcn_bert = VGCNBertModel(config, wgraphs, wgraph_id_to_tokenizer_id_maps)
self.vocab_transform = nn.Linear(config.dim, config.dim)
self.vocab_layer_norm = nn.LayerNorm(config.dim, eps=1e-12)
self.vocab_projector = nn.Linear(config.dim, config.vocab_size)
# Initialize weights and apply final processing
self.post_init()
self.mlm_loss_fct = nn.CrossEntropyLoss()
def get_position_embeddings(self) -> nn.Embedding:
"""
Returns the position embeddings
"""
return self.vgcn_bert.get_position_embeddings()
def resize_position_embeddings(self, new_num_position_embeddings: int):
"""
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
Arguments:
new_num_position_embeddings (`int`):
The number of new position embedding matrix. If position embeddings are learned, increasing the size
will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
size will add correct vectors at the end following the position encoding algorithm, whereas reducing
the size will remove vectors from the end.
"""
self.vgcn_bert.resize_position_embeddings(new_num_position_embeddings)
def get_output_embeddings(self) -> nn.Module:
return self.vocab_projector
def set_output_embeddings(self, new_embeddings: nn.Module):
self.vocab_projector = new_embeddings
@add_start_docstrings_to_model_forward(VGCNBERT_INPUTS_DOCSTRING.format("batch_size, num_choices"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=MaskedLMOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[MaskedLMOutput, Tuple[torch.Tensor, ...]]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the masked language modeling loss. Indices should be in `[-100, 0, ...,
config.vocab_size]` (see `input_ids` docstring) Tokens with indices set to `-100` are ignored (masked), the
loss is only computed for the tokens with labels in `[0, ..., config.vocab_size]`.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
dlbrt_output = self.vgcn_bert(
input_ids=input_ids,
attention_mask=attention_mask,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = dlbrt_output[0] # (bs, seq_length, dim)
prediction_logits = self.vocab_transform(hidden_states) # (bs, seq_length, dim)
prediction_logits = self.activation(prediction_logits) # (bs, seq_length, dim)
prediction_logits = self.vocab_layer_norm(prediction_logits) # (bs, seq_length, dim)
prediction_logits = self.vocab_projector(prediction_logits) # (bs, seq_length, vocab_size)
# remove graph embedding outputs
prediction_logits = prediction_logits[:, : input_ids.size(1), :]
mlm_loss = None
if labels is not None:
mlm_loss = self.mlm_loss_fct(prediction_logits.reshape(-1, prediction_logits.size(-1)), labels.view(-1))
if not return_dict:
output = (prediction_logits,) + dlbrt_output[1:]
return ((mlm_loss,) + output) if mlm_loss is not None else output
return MaskedLMOutput(
loss=mlm_loss,
logits=prediction_logits,
hidden_states=dlbrt_output.hidden_states,
attentions=dlbrt_output.attentions,
)
@add_start_docstrings(
"""
VGCNBert Model transformer with a sequence classification/regression head on top (a linear layer on top of the
pooled output) e.g. for GLUE tasks.
""",
VGCNBERT_START_DOCSTRING,
)
# Copied from transformers.models.distilbert.modeling_distilbert.DistilBertForSequenceClassification with DISTILBERT->VGCNBERT,DistilBert->VGCNBert,distilbert->vgcn_bert
class VGCNBertForSequenceClassification(VGCNBertPreTrainedModel):
def __init__(
self,
config: PretrainedConfig,
wgraphs: Optional[list] = None,
wgraph_id_to_tokenizer_id_maps: Optional[List[dict]] = None,
):
super().__init__(config)
self.num_labels = config.num_labels
self.config = config
self.vgcn_bert = VGCNBertModel(config, wgraphs, wgraph_id_to_tokenizer_id_maps)
self.pre_classifier = nn.Linear(config.dim, config.dim)
self.classifier = nn.Linear(config.dim, config.num_labels)
self.dropout = nn.Dropout(config.seq_classif_dropout)
# Initialize weights and apply final processing
self.post_init()
def get_position_embeddings(self) -> nn.Embedding:
"""
Returns the position embeddings
"""
return self.vgcn_bert.get_position_embeddings()
def resize_position_embeddings(self, new_num_position_embeddings: int):
"""
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
Arguments:
new_num_position_embeddings (`int`):
The number of new position embedding matrix. If position embeddings are learned, increasing the size
will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
size will add correct vectors at the end following the position encoding algorithm, whereas reducing
the size will remove vectors from the end.
"""
self.vgcn_bert.resize_position_embeddings(new_num_position_embeddings)
@add_start_docstrings_to_model_forward(VGCNBERT_INPUTS_DOCSTRING.format("batch_size, sequence_length"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=SequenceClassifierOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[SequenceClassifierOutput, Tuple[torch.Tensor, ...]]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the sequence classification/regression loss. Indices should be in `[0, ...,
config.num_labels - 1]`. If `config.num_labels == 1` a regression loss is computed (Mean-Square loss), If
`config.num_labels > 1` a classification loss is computed (Cross-Entropy).
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vgcn_bert_output = self.vgcn_bert(
input_ids=input_ids,
attention_mask=attention_mask,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_state = vgcn_bert_output[0] # (bs, seq_len, dim)
pooled_output = hidden_state[:, 0] # (bs, dim)
pooled_output = self.pre_classifier(pooled_output) # (bs, dim)
pooled_output = nn.ReLU()(pooled_output) # (bs, dim)
pooled_output = self.dropout(pooled_output) # (bs, dim)
logits = self.classifier(pooled_output) # (bs, num_labels)
loss = None
if labels is not None:
if self.config.problem_type is None:
if self.num_labels == 1:
self.config.problem_type = "regression"
elif self.num_labels > 1 and (labels.dtype == torch.long or labels.dtype == torch.int):
self.config.problem_type = "single_label_classification"
else:
self.config.problem_type = "multi_label_classification"
if self.config.problem_type == "regression":
loss_fct = MSELoss()
if self.num_labels == 1:
loss = loss_fct(logits.squeeze(), labels.squeeze())
else:
loss = loss_fct(logits, labels)
elif self.config.problem_type == "single_label_classification":
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.view(-1, self.num_labels), labels.view(-1))
elif self.config.problem_type == "multi_label_classification":
loss_fct = BCEWithLogitsLoss()
loss = loss_fct(logits, labels)
if not return_dict:
output = (logits,) + vgcn_bert_output[1:]
return ((loss,) + output) if loss is not None else output
return SequenceClassifierOutput(
loss=loss,
logits=logits,
hidden_states=vgcn_bert_output.hidden_states,
attentions=vgcn_bert_output.attentions,
)
@add_start_docstrings(
"""
VGCNBert Model with a span classification head on top for extractive question-answering tasks like SQuAD (a
linear layers on top of the hidden-states output to compute `span start logits` and `span end logits`).
""",
VGCNBERT_START_DOCSTRING,
)
# Copied from transformers.models.distilbert.modeling_distilbert.DistilBertForQuestionAnswering with DISTILBERT->VGCNBERT,DistilBert->VGCNBert,distilbert->vgcn_bert
class VGCNBertForQuestionAnswering(VGCNBertPreTrainedModel):
def __init__(
self,
config: PretrainedConfig,
wgraphs: Optional[list] = None,
wgraph_id_to_tokenizer_id_maps: Optional[List[dict]] = None,
):
super().__init__(config)
self.vgcn_bert = VGCNBertModel(config, wgraphs, wgraph_id_to_tokenizer_id_maps)
self.qa_outputs = nn.Linear(config.dim, config.num_labels)
if config.num_labels != 2:
raise ValueError(f"config.num_labels should be 2, but it is {config.num_labels}")
self.dropout = nn.Dropout(config.qa_dropout)
# Initialize weights and apply final processing
self.post_init()
def get_position_embeddings(self) -> nn.Embedding:
"""
Returns the position embeddings
"""
return self.vgcn_bert.get_position_embeddings()
def resize_position_embeddings(self, new_num_position_embeddings: int):
"""
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
Arguments:
new_num_position_embeddings (`int`):
The number of new position embedding matrix. If position embeddings are learned, increasing the size
will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
size will add correct vectors at the end following the position encoding algorithm, whereas reducing
the size will remove vectors from the end.
"""
self.vgcn_bert.resize_position_embeddings(new_num_position_embeddings)
@add_start_docstrings_to_model_forward(VGCNBERT_INPUTS_DOCSTRING.format("batch_size, num_choices"))
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=QuestionAnsweringModelOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
start_positions: Optional[torch.Tensor] = None,
end_positions: Optional[torch.Tensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[QuestionAnsweringModelOutput, Tuple[torch.Tensor, ...]]:
r"""
start_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the start of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
are not taken into account for computing the loss.
end_positions (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for position (index) of the end of the labelled span for computing the token classification loss.
Positions are clamped to the length of the sequence (`sequence_length`). Position outside of the sequence
are not taken into account for computing the loss.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
vgcn_bert_output = self.vgcn_bert(
input_ids=input_ids,
attention_mask=attention_mask,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_states = vgcn_bert_output[0] # (bs, max_query_len, dim)
hidden_states = self.dropout(hidden_states) # (bs, max_query_len, dim)
logits = self.qa_outputs(hidden_states) # (bs, max_query_len, 2)
# remove graph embedding outputs
logits = logits[:, : input_ids.size(1), :]
start_logits, end_logits = logits.split(1, dim=-1)
start_logits = start_logits.squeeze(-1).contiguous() # (bs, max_query_len)
end_logits = end_logits.squeeze(-1).contiguous() # (bs, max_query_len)
total_loss = None
if start_positions is not None and end_positions is not None:
# If we are on multi-GPU, split add a dimension
if len(start_positions.size()) > 1:
start_positions = start_positions.squeeze(-1)
if len(end_positions.size()) > 1:
end_positions = end_positions.squeeze(-1)
# sometimes the start/end positions are outside our model inputs, we ignore these terms
ignored_index = start_logits.size(1)
start_positions = start_positions.clamp(0, ignored_index)
end_positions = end_positions.clamp(0, ignored_index)
loss_fct = nn.CrossEntropyLoss(ignore_index=ignored_index)
start_loss = loss_fct(start_logits, start_positions)
end_loss = loss_fct(end_logits, end_positions)
total_loss = (start_loss + end_loss) / 2
if not return_dict:
output = (start_logits, end_logits) + vgcn_bert_output[1:]
return ((total_loss,) + output) if total_loss is not None else output
return QuestionAnsweringModelOutput(
loss=total_loss,
start_logits=start_logits,
end_logits=end_logits,
hidden_states=vgcn_bert_output.hidden_states,
attentions=vgcn_bert_output.attentions,
)
@add_start_docstrings(
"""
VGCNBert Model with a token classification head on top (a linear layer on top of the hidden-states output) e.g.
for Named-Entity-Recognition (NER) tasks.
""",
VGCNBERT_START_DOCSTRING,
)
# Copied from transformers.models.distilbert.modeling_distilbert.DistilBertForTokenClassification with DISTILBERT->VGCNBERT,DistilBert->VGCNBert,distilbert->vgcn_bert
class VGCNBertForTokenClassification(VGCNBertPreTrainedModel):
def __init__(
self,
config: PretrainedConfig,
wgraphs: Optional[list] = None,
wgraph_id_to_tokenizer_id_maps: Optional[List[dict]] = None,
):
super().__init__(config)
self.num_labels = config.num_labels
self.vgcn_bert = VGCNBertModel(config, wgraphs, wgraph_id_to_tokenizer_id_maps)
self.dropout = nn.Dropout(config.dropout)
self.classifier = nn.Linear(config.hidden_size, config.num_labels)
# Initialize weights and apply final processing
self.post_init()
def get_position_embeddings(self) -> nn.Embedding:
"""
Returns the position embeddings
"""
return self.vgcn_bert.get_position_embeddings()
def resize_position_embeddings(self, new_num_position_embeddings: int):
"""
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
Arguments:
new_num_position_embeddings (`int`):
The number of new position embedding matrix. If position embeddings are learned, increasing the size
will add newly initialized vectors at the end, whereas reducing the size will remove vectors from the
end. If position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the
size will add correct vectors at the end following the position encoding algorithm, whereas reducing
the size will remove vectors from the end.
"""
self.vgcn_bert.resize_position_embeddings(new_num_position_embeddings)
@add_start_docstrings_to_model_forward(VGCNBERT_INPUTS_DOCSTRING)
@add_code_sample_docstrings(
checkpoint=_CHECKPOINT_FOR_DOC,
output_type=TokenClassifierOutput,
config_class=_CONFIG_FOR_DOC,
)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[TokenClassifierOutput, Tuple[torch.Tensor, ...]]:
r"""
labels (`torch.LongTensor` of shape `(batch_size, sequence_length)`, *optional*):
Labels for computing the token classification loss. Indices should be in `[0, ..., config.num_labels - 1]`.
"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
outputs = self.vgcn_bert(
input_ids,
attention_mask=attention_mask,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
sequence_output = outputs[0]
sequence_output = self.dropout(sequence_output)
logits = self.classifier(sequence_output)
# remove graph embedding outputs
logits = logits[:, : input_ids.size(1), :]
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(logits.reshape(-1, self.num_labels), labels.view(-1))
if not return_dict:
output = (logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return TokenClassifierOutput(
loss=loss,
logits=logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
@add_start_docstrings(
"""
VGCNBert Model with a multiple choice classification head on top (a linear layer on top of the pooled output and
a softmax) e.g. for RocStories/SWAG tasks.
""",
VGCNBERT_START_DOCSTRING,
)
# Copied from transformers.models.distilbert.modeling_distilbert.DistilBertForMultipleChoice with DISTILBERT->VGCNBERT,DistilBert->VGCNBert,distilbert->vgcn_bert
class VGCNBertForMultipleChoice(VGCNBertPreTrainedModel):
def __init__(
self,
config: PretrainedConfig,
wgraphs: Optional[list] = None,
wgraph_id_to_tokenizer_id_maps: Optional[List[dict]] = None,
):
super().__init__(config)
self.vgcn_bert = VGCNBertModel(config, wgraphs, wgraph_id_to_tokenizer_id_maps)
self.pre_classifier = nn.Linear(config.dim, config.dim)
self.classifier = nn.Linear(config.dim, 1)
self.dropout = nn.Dropout(config.seq_classif_dropout)
# Initialize weights and apply final processing
self.post_init()
def get_position_embeddings(self) -> nn.Embedding:
"""
Returns the position embeddings
"""
return self.vgcn_bert.get_position_embeddings()
def resize_position_embeddings(self, new_num_position_embeddings: int):
"""
Resizes position embeddings of the model if `new_num_position_embeddings != config.max_position_embeddings`.
Arguments:
new_num_position_embeddings (`int`)
The number of new position embeddings. If position embeddings are learned, increasing the size will add
newly initialized vectors at the end, whereas reducing the size will remove vectors from the end. If
position embeddings are not learned (*e.g.* sinusoidal position embeddings), increasing the size will
add correct vectors at the end following the position encoding algorithm, whereas reducing the size
will remove vectors from the end.
"""
self.vgcn_bert.resize_position_embeddings(new_num_position_embeddings)
@add_start_docstrings_to_model_forward(
VGCNBERT_INPUTS_DOCSTRING.format("batch_size, num_choices, sequence_length")
)
@replace_return_docstrings(output_type=MultipleChoiceModelOutput, config_class=_CONFIG_FOR_DOC)
def forward(
self,
input_ids: Optional[torch.Tensor] = None,
attention_mask: Optional[torch.Tensor] = None,
head_mask: Optional[torch.Tensor] = None,
inputs_embeds: Optional[torch.Tensor] = None,
labels: Optional[torch.LongTensor] = None,
output_attentions: Optional[bool] = None,
output_hidden_states: Optional[bool] = None,
return_dict: Optional[bool] = None,
) -> Union[MultipleChoiceModelOutput, Tuple[torch.Tensor, ...]]:
r"""
labels (`torch.LongTensor` of shape `(batch_size,)`, *optional*):
Labels for computing the multiple choice classification loss. Indices should be in `[0, ...,
num_choices-1]` where `num_choices` is the size of the second dimension of the input tensors. (See
`input_ids` above)
Returns:
Examples:
```python
>>> from transformers import AutoTokenizer, VGCNBertForMultipleChoice
>>> import torch
>>> tokenizer = AutoTokenizer.from_pretrained("vgcn_bert-base-cased")
>>> model = VGCNBertForMultipleChoice.from_pretrained("vgcn_bert-base-cased")
>>> prompt = "In Italy, pizza served in formal settings, such as at a restaurant, is presented unsliced."
>>> choice0 = "It is eaten with a fork and a knife."
>>> choice1 = "It is eaten while held in the hand."
>>> labels = torch.tensor(0).unsqueeze(0) # choice0 is correct (according to Wikipedia ;)), batch size 1
>>> encoding = tokenizer([[prompt, choice0], [prompt, choice1]], return_tensors="pt", padding=True)
>>> outputs = model(**{k: v.unsqueeze(0) for k, v in encoding.items()}, labels=labels) # batch size is 1
>>> # the linear classifier still needs to be trained
>>> loss = outputs.loss
>>> logits = outputs.logits
```"""
return_dict = return_dict if return_dict is not None else self.config.use_return_dict
num_choices = input_ids.shape[1] if input_ids is not None else inputs_embeds.shape[1]
input_ids = input_ids.view(-1, input_ids.size(-1)) if input_ids is not None else None
attention_mask = attention_mask.view(-1, attention_mask.size(-1)) if attention_mask is not None else None
inputs_embeds = (
inputs_embeds.view(-1, inputs_embeds.size(-2), inputs_embeds.size(-1))
if inputs_embeds is not None
else None
)
outputs = self.vgcn_bert(
input_ids,
attention_mask=attention_mask,
head_mask=head_mask,
inputs_embeds=inputs_embeds,
output_attentions=output_attentions,
output_hidden_states=output_hidden_states,
return_dict=return_dict,
)
hidden_state = outputs[0] # (bs * num_choices, seq_len, dim)
pooled_output = hidden_state[:, 0] # (bs * num_choices, dim)
pooled_output = self.pre_classifier(pooled_output) # (bs * num_choices, dim)
pooled_output = nn.ReLU()(pooled_output) # (bs * num_choices, dim)
pooled_output = self.dropout(pooled_output) # (bs * num_choices, dim)
logits = self.classifier(pooled_output) # (bs * num_choices, 1)
reshaped_logits = logits.view(-1, num_choices) # (bs, num_choices)
loss = None
if labels is not None:
loss_fct = CrossEntropyLoss()
loss = loss_fct(reshaped_logits, labels)
if not return_dict:
output = (reshaped_logits,) + outputs[1:]
return ((loss,) + output) if loss is not None else output
return MultipleChoiceModelOutput(
loss=loss,
logits=reshaped_logits,
hidden_states=outputs.hidden_states,
attentions=outputs.attentions,
)
|