File size: 90,641 Bytes
189e0ad | 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 | import abc
import gc
from typing import Callable, Dict, List, Optional, Tuple
import os
import numpy as np
import pickle
import lightning.pytorch as pl
import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.distributions import (
Bernoulli,
ContinuousBernoulli,
Poisson,
)
from scvi.distributions import NegativeBinomial, ZeroInflatedNegativeBinomial
from torchmetrics import ExplainedVariance, MeanSquaredError, MetricCollection
from torchmetrics.classification import MulticlassF1Score
from self_supervision.models.base.base import MLP
from self_supervision.models.contrastive.byol import BYOL
from self_supervision.models.contrastive.bt import (
BarlowTwins,
Transform,
LARS,
adjust_learning_rate,
)
def _mask_gene_programs_numpy(
inputs: torch.Tensor, encoded_gene_program: np.ndarray, masking_rate: float
):
"""
Randomly choose masking_rate percent of the gene programs (rows) to mask.
Mask all the genes in the inputs tensor that are 1s in the chosen row of encoded_gene_program.
return a binary mask of the tensor and a fraction of how many genes are set to 0.
:param inputs: input data
:param encoded_gene_program: encoded gene programs
:param masking_rate: rate of gene programs to mask
:return: mask, frac: mask is a binary mask of the tensor and frac is a fraction of how many genes are set to 0.
"""
# Randomly choose masking_rate percent of the gene programs to mask
num_gene_programs = encoded_gene_program.shape[0]
num_gene_programs_to_mask = int(num_gene_programs * masking_rate)
gene_programs_to_mask = np.random.permutation(num_gene_programs)[
:num_gene_programs_to_mask
]
# Mask the input tensor and cast it to numpy on cpu
mask = np.ones_like(inputs.cpu().numpy())
for ix in gene_programs_to_mask:
mask[:, encoded_gene_program[ix, :] == 1] = 0
return mask, 1 - mask.sum() / mask.size
def _only_activate_gene_program_numpy(
inputs: torch.Tensor,
# write that encoded_gene_program is a dict of a tuple of torch.Tensor
# encoded_gene_program: Dict[Tuple[torch.Tensor, torch.Tensor]],
encoded_gene_program: Dict,
):
"""
For each row of the inputs tensor randomly choose one transcription factor (key of encoded_gene_program)
The first element of encoded_gene_program[key] is a vector (torch.Tensor) of indices of genes in the gene program.
The input mask should correspond to that mask, i.e., the mask is 1 where the genes are in the gene program.
The second element of encoded_gene_program[key] is a vector (torch.Tensor) of index of the corresponding gene program.
The output mask should be 1 that vector is 1.
:param inputs: input data
:param encoded_gene_program: encoded gene programs
:return: (input_mask, output_mask): input_mask is a binary mask of the tensor and output_mask is a binary mask of the tensor.
"""
# Randomly choose one transcription factor (key of encoded_gene_program) per row of the inputs tensor
num_gene_programs = len(encoded_gene_program)
gene_programs_to_activate = np.random.permutation(num_gene_programs)[
: inputs.shape[0]
]
# Mask the input tensor and cast it to numpy on cpu
input_mask = np.zeros_like(inputs.cpu().numpy())
output_mask = np.zeros_like(inputs.cpu().numpy())
for ix, key in enumerate(gene_programs_to_activate):
input_mask[ix, encoded_gene_program[key][0]] = 1
output_mask[ix, encoded_gene_program[key][1]] = 1
return input_mask, output_mask
def _mask_single_gene_programs(
inputs: torch.Tensor,
encoded_gene_program: np.ndarray,
):
"""
Randomly choose 1 gene program, mask everything apart from that gene program both in the input and output.
"""
# Randomly choose 1 gene program
num_gene_programs = encoded_gene_program.shape[0]
gene_program_to_mask = np.random.permutation(num_gene_programs)[:1]
# Mask the input tensor and cast it to numpy on cpu
input_mask = np.zeros_like(inputs.cpu().numpy())
output_mask = np.zeros_like(inputs.cpu().numpy())
input_mask[:, encoded_gene_program[gene_program_to_mask, :] == 1] = 1
output_mask[:, encoded_gene_program[gene_program_to_mask, :] == 1] = 1
return input_mask, output_mask
class BaseAutoEncoder(pl.LightningModule, abc.ABC):
"""
Base class for AutoEncoder models in PyTorch Lightning.
Args:
gene_dim (int): Dimension of the gene.
batch_size (int): Batch size.
reconst_loss (str, optional): Reconstruction loss function. Defaults to 'mse'.
learning_rate (float, optional): Learning rate. Defaults to 0.005.
weight_decay (float, optional): Weight decay. Defaults to 0.1.
optimizer (Callable[..., torch.optim.Optimizer], optional): Optimizer class. Defaults to torch.optim.AdamW.
lr_scheduler (Callable, optional): Learning rate scheduler. Defaults to None.
lr_scheduler_kwargs (Dict, optional): Additional arguments for the learning rate scheduler. Defaults to None.
gc_frequency (int, optional): Frequency of garbage collection. Defaults to 1.
automatic_optimization (bool, optional): Whether to use automatic optimization. Defaults to True.
supervised_subset (Optional[int], optional): Subset size for supervised training. Defaults to None.
"""
autoencoder: nn.Module # autoencoder mapping von gene_dim to gene_dim
def __init__(
self,
gene_dim: int,
batch_size: int,
reconst_loss: str = "mse",
learning_rate: float = 0.005,
weight_decay: float = 0.1,
optimizer: Callable[..., torch.optim.Optimizer] = torch.optim.AdamW,
lr_scheduler: Callable = None,
lr_scheduler_kwargs: Dict = None,
gc_frequency: int = 1,
automatic_optimization: bool = True,
supervised_subset: Optional[int] = None,
):
super(BaseAutoEncoder, self).__init__()
self.automatic_optimization = automatic_optimization
self.gene_dim = gene_dim
self.batch_size = batch_size
self.gc_freq = gc_frequency
self.lr = learning_rate
self.weight_decay = weight_decay
self.optim = optimizer
self.reconst_loss = reconst_loss
self.lr_scheduler = lr_scheduler
self.lr_scheduler_kwargs = lr_scheduler_kwargs
self.supervised_subset = supervised_subset
metrics = MetricCollection(
{
"explained_var_weighted": ExplainedVariance(
multioutput="variance_weighted"
),
"explained_var_uniform": ExplainedVariance(
multioutput="uniform_average"
),
"mse": MeanSquaredError(),
}
)
self.train_metrics = metrics.clone(prefix="train_")
self.val_metrics = metrics.clone(prefix="val_")
self.test_metrics = metrics.clone(prefix="test_")
def _calc_reconstruction_loss(
self, preds: torch.Tensor, targets: torch.Tensor, reduction: str = "mean"
):
"""
Calculate the reconstruction loss.
Args:
preds (torch.Tensor): Predicted values.
targets (torch.Tensor): Target values.
reduction (str, optional): Reduction method. Defaults to 'mean'.
Returns:
torch.Tensor: Reconstruction loss.
"""
if self.reconst_loss == "continuous_bernoulli":
loss = -ContinuousBernoulli(probs=preds).log_prob(targets)
if reduction == "mean":
loss = loss.mean()
elif reduction == "sum":
loss = loss.sum()
elif self.reconst_loss == "bce":
loss = F.binary_cross_entropy(preds, targets, reduction=reduction)
elif self.reconst_loss == "mae":
loss = F.l1_loss(preds, targets, reduction=reduction)
else:
loss = F.mse_loss(preds, targets, reduction=reduction)
return loss
@abc.abstractmethod
def _step(self, batch):
"""
Calculate predictions (int64 tensor) and loss.
Args:
batch: Input batch.
Returns:
tuple: Tuple containing predictions and loss.
"""
pass
def on_after_batch_transfer(self, batch, dataloader_idx):
"""
Perform operations on the batch after it has been transferred to the device.
Args:
batch: Input batch.
dataloader_idx: Index of the dataloader.
Returns:
batch: Processed batch.
"""
if isinstance(batch, dict): # Case for MultiomicsDataloader
return batch
else:
return batch[0]
def forward(self, batch):
"""
Forward pass of the autoencoder.
Args:
batch: Input batch.
Returns:
tuple: Tuple containing the latent representation and the reconstructed output.
"""
x_in = batch["X"]
x_latent = self.encoder(x_in)
x_reconst = self.decoder(x_latent)
return x_latent, x_reconst
def on_train_epoch_end(self) -> None:
"""
Perform operations at the end of each training epoch.
"""
gc.collect()
def on_validation_epoch_end(self) -> None:
"""
Perform operations at the end of each validation epoch.
"""
gc.collect()
def configure_optimizers(self):
"""
Configure the optimizer and learning rate scheduler.
Returns:
dict: Configuration for the optimizer and learning rate scheduler.
"""
optimizer_config = {
"optimizer": self.optim(
self.parameters(), lr=self.lr, weight_decay=self.weight_decay
)
}
if self.lr_scheduler is not None:
lr_scheduler_kwargs = (
{} if self.lr_scheduler_kwargs is None else self.lr_scheduler_kwargs
)
interval = lr_scheduler_kwargs.pop("interval", "epoch")
monitor = lr_scheduler_kwargs.pop("monitor", "val_loss_epoch")
frequency = lr_scheduler_kwargs.pop("frequency", 1)
scheduler = self.lr_scheduler(
optimizer_config["optimizer"], **lr_scheduler_kwargs
)
optimizer_config["lr_scheduler"] = {
"scheduler": scheduler,
"interval": interval,
"monitor": monitor,
"frequency": frequency,
}
return optimizer_config
class BaseClassifier(pl.LightningModule, abc.ABC):
"""
Base classifier module for a PyTorch Lightning model.
Args:
gene_dim (int): Dimension of the gene feature.
type_dim (int): Dimension of the cell type.
class_weights (np.ndarray): Array of class weights.
child_matrix (np.ndarray): Matrix representing the child relationship between cell types.
batch_size (int): Batch size.
hvg (bool): Flag indicating whether to use highly variable genes.
num_hvgs (int): Number of highly variable genes.
supervised_subset (Optional[int], optional): Subset of the data to use for supervised training. Defaults to None.
learning_rate (float, optional): Learning rate. Defaults to 0.005.
weight_decay (float, optional): Weight decay. Defaults to 0.1.
optimizer (Callable[..., torch.optim.Optimizer], optional): Optimizer function. Defaults to torch.optim.AdamW.
lr_scheduler (Callable, optional): Learning rate scheduler. Defaults to None.
lr_scheduler_kwargs (Dict, optional): Additional arguments for the learning rate scheduler. Defaults to None.
gc_frequency (int, optional): Frequency of garbage collection. Defaults to 1.
"""
classifier: Callable # classifier mapping von gene_dim to type_dim - outputs logits
def __init__(
self,
gene_dim: int,
type_dim: int,
class_weights: np.ndarray,
child_matrix: np.ndarray,
batch_size: int,
hvg: bool = False,
num_hvgs: int = 2000,
supervised_subset: Optional[int] = None,
learning_rate: float = 0.005,
weight_decay: float = 0.1,
optimizer: Callable[..., torch.optim.Optimizer] = torch.optim.AdamW,
lr_scheduler: Callable = None,
lr_scheduler_kwargs: Dict = None,
gc_frequency: int = 1,
):
super(BaseClassifier, self).__init__()
self.gene_dim = gene_dim
self.type_dim = type_dim
self.batch_size = batch_size
self.gc_freq = gc_frequency
self.num_hvgs = num_hvgs
self.supervised_subset = supervised_subset
self.lr = learning_rate
self.weight_decay = weight_decay
self.optim = optimizer
self.lr_scheduler = lr_scheduler
self.lr_scheduler_kwargs = lr_scheduler_kwargs
metrics = MetricCollection(
{
"f1_micro": MulticlassF1Score(num_classes=type_dim, average="micro"),
"f1_macro": MulticlassF1Score(num_classes=type_dim, average="macro"),
}
)
self.train_metrics = metrics.clone(prefix="train_")
self.val_metrics = metrics.clone(prefix="val_")
self.test_metrics = metrics.clone(prefix="test_")
self.register_buffer("class_weights", torch.tensor(class_weights.astype("f4")))
self.register_buffer("child_lookup", torch.tensor(child_matrix.astype("i8")))
if hvg:
root = os.path.dirname(
os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
)
self.hvg_indices = pickle.load(
open(
root
+ "/self_supervision/data/hvg_"
+ str(self.num_hvgs)
+ "_indices.pickle",
"rb",
)
)
else:
self.hvg_indices = None
@abc.abstractmethod
def _step(self, batch, training=True) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Abstract method for performing a step in the training, validation, or testing process.
Args:
batch: Input batch data.
training (bool, optional): Flag indicating whether the model is in training mode. Defaults to True.
Returns:
Tuple[torch.Tensor, torch.Tensor]: Tuple containing the predictions and the loss.
"""
pass
def hierarchy_correct(self, preds, targets) -> Tuple[torch.Tensor, torch.Tensor]:
"""
Corrects the predictions and targets based on the hierarchy of cell types.
Args:
preds (torch.Tensor): Predicted cell types.
targets (torch.Tensor): Target cell types.
Returns:
Tuple[torch.Tensor, torch.Tensor]: Tuple containing the corrected predictions and targets.
"""
pred_is_child_node_or_node = (
torch.sum(
self.child_lookup[targets, :] * F.one_hot(preds, self.type_dim), dim=1
)
> 0
)
return (
torch.where(pred_is_child_node_or_node, targets, preds), # corrected preds
torch.where(
pred_is_child_node_or_node, preds, targets
), # corrected targets
)
def on_after_batch_transfer(self, batch, dataloader_idx):
"""
Callback function called after transferring the batch to the device.
Args:
batch: Input batch data.
dataloader_idx: Index of the dataloader.
Returns:
batch: Transformed batch data.
"""
with torch.no_grad():
batch = batch[0]
batch["cell_type"] = torch.squeeze(batch["cell_type"])
return batch
def forward(self, x: torch.Tensor):
"""
Forward pass of the model.
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Output tensor.
"""
# If x is a tuple, which can happen in some testing due to lightning, then we need to extract the tensor
if isinstance(x, dict):
x = x["X"]
if isinstance(x, tuple):
x = x[0]["X"]
if self.hvg_indices:
x = x[:, self.hvg_indices]
return self.classifier(x)
def training_step(self, batch, batch_idx):
"""
Training step of the model.
Args:
batch: Input batch data.
batch_idx: Index of the batch.
Returns:
loss: Training loss.
"""
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return None, None
# Filter the batch based on the mask
batch = {key: value[mask] for key, value in batch.items()}
preds, loss = self._step(batch, training=True)
self.log("train_loss", loss)
f1_macro = self.train_metrics["f1_macro"](preds, batch["cell_type"])
f1_micro = self.train_metrics["f1_micro"](preds, batch["cell_type"])
self.log("train_f1_macro_step", f1_macro)
self.log("train_f1_micro_step", f1_micro)
if batch_idx % self.gc_freq == 0:
gc.collect()
return loss
def validation_step(self, batch, batch_idx):
"""
Validation step of the model.
Args:
batch: Input batch data.
batch_idx: Index of the batch.
"""
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return None, None
# Filter the batch based on the mask
batch = {key: value[mask] for key, value in batch.items()}
preds, loss = self._step(batch, training=False)
self.log("val_loss", loss)
self.val_metrics["f1_macro"].update(preds, batch["cell_type"])
self.val_metrics["f1_micro"].update(preds, batch["cell_type"])
if batch_idx % self.gc_freq == 0:
gc.collect()
def test_step(self, batch, batch_idx):
"""
Test step of the model.
Args:
batch: Input batch data.
batch_idx: Index of the batch.
"""
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return None, None
# Filter the batch based on the mask
batch = {key: value[mask] for key, value in batch.items()}
preds, loss = self._step(batch, training=False)
self.log("test_loss", loss)
self.test_metrics["f1_macro"].update(preds, batch["cell_type"])
self.test_metrics["f1_micro"].update(preds, batch["cell_type"])
if batch_idx % self.gc_freq == 0:
gc.collect()
def on_train_epoch_end(self) -> None:
self.log("train_f1_macro_epoch", self.train_metrics["f1_macro"].compute())
self.train_metrics["f1_macro"].reset()
self.log("train_f1_micro_epoch", self.train_metrics["f1_micro"].compute())
self.train_metrics["f1_micro"].reset()
gc.collect()
def on_validation_epoch_end(self) -> None:
f1_macro = self.val_metrics["f1_macro"].compute()
self.log("val_f1_macro", f1_macro)
self.log("hp_metric", f1_macro)
self.val_metrics["f1_macro"].reset()
self.log("val_f1_micro", self.val_metrics["f1_micro"].compute())
self.val_metrics["f1_micro"].reset()
gc.collect()
def on_test_epoch_end(self) -> None:
self.log("test_f1_macro", self.test_metrics["f1_macro"].compute())
self.test_metrics["f1_macro"].reset()
self.log("test_f1_micro", self.test_metrics["f1_micro"].compute())
self.test_metrics["f1_micro"].reset()
gc.collect()
def configure_optimizers(self):
optimizer_config = {
"optimizer": self.optim(
self.parameters(), lr=self.lr, weight_decay=self.weight_decay
)
}
if self.lr_scheduler is not None:
lr_scheduler_kwargs = (
{} if self.lr_scheduler_kwargs is None else self.lr_scheduler_kwargs
)
interval = lr_scheduler_kwargs.pop("interval", "epoch")
monitor = lr_scheduler_kwargs.pop("monitor", "val_loss_epoch")
frequency = lr_scheduler_kwargs.pop("frequency", 1)
scheduler = self.lr_scheduler(
optimizer_config["optimizer"], **lr_scheduler_kwargs
)
optimizer_config["lr_scheduler"] = {
"scheduler": scheduler,
"interval": interval,
"monitor": monitor,
"frequency": frequency,
}
return optimizer_config
class MLPVariationalAutoEncoder(BaseAutoEncoder):
def __init__(
self,
# fixed params
gene_dim: int,
units_encoder: List[int],
units_decoder: List[int],
# params from datamodule
batch_size: int,
hvg: bool = False,
num_hvgs: int = 2000,
# model specific params
supervised_subset: Optional[int] = None,
reconstruction_loss: str = "mse",
learning_rate: float = 0.005,
weight_decay: float = 0.1,
dropout: float = 0.1,
optimizer: Callable[..., torch.optim.Optimizer] = torch.optim.AdamW,
lr_scheduler: Callable = None,
lr_scheduler_kwargs: Dict = None,
output_activation: Callable[[], torch.nn.Module] = nn.Sigmoid,
activation: Callable[[], torch.nn.Module] = nn.SELU,
# params for masking
masking_rate: Optional[float] = None,
masking_strategy: Optional[str] = None, # 'random', 'gene_program'
encoded_gene_program: Optional[Dict] = None,
):
# check input
assert 0.0 <= dropout <= 1.0
assert reconstruction_loss in ["mse", "mae", "continuous_bernoulli", "bce"]
if reconstruction_loss in ["continuous_bernoulli", "bce"]:
assert output_activation == nn.Sigmoid
self.batch_size = batch_size
self.supervised_subset = supervised_subset
super(MLPVariationalAutoEncoder, self).__init__(
gene_dim=gene_dim,
batch_size=batch_size,
learning_rate=learning_rate,
weight_decay=weight_decay,
optimizer=optimizer,
lr_scheduler=lr_scheduler,
lr_scheduler_kwargs=lr_scheduler_kwargs,
supervised_subset=supervised_subset,
)
self.encoder = MLP(
in_channels=gene_dim,
hidden_channels=units_encoder,
activation_layer=activation,
inplace=False,
dropout=dropout,
)
# Define decoder network
self.decoder = nn.Sequential(
MLP(
in_channels=units_encoder[-1],
hidden_channels=units_decoder + [gene_dim],
# norm_layer=_get_norm_layer(batch_norm=batch_norm, layer_norm=layer_norm),
activation_layer=activation,
inplace=False,
dropout=dropout,
),
output_activation(),
)
self.mean_head = torch.nn.Linear(units_encoder[-1], units_encoder[-1], bias=True)
self.logvar_head = torch.nn.Linear(units_encoder[-1], units_encoder[-1], bias=True)
self.predict_bottleneck = False
metrics = MetricCollection(
{
"explained_var_weighted": ExplainedVariance(
multioutput="variance_weighted"
),
"explained_var_uniform": ExplainedVariance(
multioutput="uniform_average"
),
"mse": MeanSquaredError(),
}
)
self.train_metrics = metrics.clone(prefix="train_")
self.val_metrics = metrics.clone(prefix="val_")
self.test_metrics = metrics.clone(prefix="test_")
# masking
self.masking_rate = masking_rate
self.masking_strategy = masking_strategy
self.encoded_gene_program = encoded_gene_program
self.num_hvgs = num_hvgs
if hvg:
root = os.path.dirname(
os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
)
self.hvg_indices = pickle.load(
open(
root
+ "/self_supervision/data/hvg_"
+ str(self.num_hvgs)
+ "_indices.pickle",
"rb",
)
)
else:
self.hvg_indices = None
def reparameterize(self, mean: torch.Tensor, logvar: torch.Tensor) -> torch.Tensor:
std = torch.exp(0.5 * logvar)
eps = torch.randn_like(std)
return mean + eps * std
def _step(self, batch, training=True):
targets = batch["X"]
inputs = batch["X"]
if self.hvg_indices is not None:
inputs = inputs[:, self.hvg_indices]
targets = targets[:, self.hvg_indices]
if self.masking_rate and self.masking_strategy == "random":
mask = (
Bernoulli(probs=1.0 - self.masking_rate)
.sample(targets.size())
.to(targets.device)
)
# upscale inputs to compensate for masking and convert to same device
masked_inputs = 1.0 / (1.0 - self.masking_rate) * (inputs * mask)
x_latent = self.encoder(masked_inputs)
z_mean = self.mean_head(x_latent)
z_logvar = self.logvar_head(x_latent)
z = self.reparameterize(z_mean, z_logvar)
x_reconst = self.decoder(z)
# calculate masked loss on masked part only
inv_mask = torch.abs(torch.ones(mask.size()).to(targets.device) - mask)
rec_loss = (
inv_mask
* self._calc_reconstruction_loss(x_reconst, targets, reduction="none")
).mean()
kl_div = -0.5 * torch.mean(1 + z_logvar - z_mean.pow(2) - z_logvar.exp())
loss = rec_loss + kl_div
elif self.masking_rate and self.masking_strategy == "gene_program":
with torch.no_grad():
# self.encoded gene program is a numpy array of encoded gene programs
mask, frac = _mask_gene_programs_numpy(
inputs, self.encoded_gene_program, self.masking_rate
)
mask = torch.tensor(mask).to(inputs.device)
# log the fraction of genes masked
self.log("frac_genes_masked", frac)
# mask, frac = self.mask_gene_programs(inputs, self.gene_program_dict, self.masking_rate)
# upscale inputs to compensate for masking
masked_inputs = 1.0 / (1.0 - frac) * (inputs * mask.to(inputs.device))
x_latent = self.encoder(masked_inputs)
z_mean = self.mean_head(x_latent)
z_logvar = self.logvar_head(x_latent)
z = self.reparameterize(z_mean, z_logvar)
x_reconst = self.decoder(z)
# calculate masked loss
inv_mask = torch.abs(torch.ones(mask.size()).to(targets.device) - mask)
rec_loss = (
inv_mask.to(inputs.device)
* self._calc_reconstruction_loss(x_reconst, targets, reduction="none")
).mean()
kl_div = -0.5 * torch.mean(1 + z_logvar - z_mean.pow(2) - z_logvar.exp())
loss = rec_loss + kl_div
elif self.masking_rate and self.masking_strategy == "single_gene_program":
with torch.no_grad():
# self.encoded gene program is a numpy array of encoded gene programs
input_mask, output_mask = _mask_single_gene_programs(
inputs, self.encoded_gene_program
)
# log the fraction of genes masked
self.log("frac_genes_masked", frac)
# upscale inputs to compensate for masking
masked_inputs = (
1.0
/ (1.0 - frac)
* (inputs * torch.tensor(input_mask).to(inputs.device))
)
x_latent = self.encoder(masked_inputs)
z_mean = self.mean_head(x_latent)
z_logvar = self.logvar_head(x_latent)
z = self.reparameterize(z_mean, z_logvar)
x_reconst = self.decoder(z)
# calculate masked loss only on the output_mask part of the reconstruction
inv_output_mask = torch.abs(
torch.ones(output_mask.size()).to(targets.device) - output_mask
)
rec_loss = (
torch.tensor(inv_output_mask).to(inputs.device)
* self._calc_reconstruction_loss(x_reconst, targets, reduction="none")
).mean()
kl_div = -0.5 * torch.mean(1 + z_logvar - z_mean.pow(2) - z_logvar.exp())
loss = rec_loss + kl_div
elif self.masking_rate and self.masking_strategy == "gp_to_tf":
with torch.no_grad():
# self.encoded gene program is a Dict of encoded gene programs and the corresponding tf indices
input_mask, output_mask = _only_activate_gene_program_numpy(
inputs, self.encoded_gene_program
)
# log the fraction of genes masked
self.log("frac_genes_masked", frac)
# upscale inputs to compensate for masking
masked_inputs = (
1.0
/ (1.0 - frac)
* (inputs * torch.tensor(input_mask).to(inputs.device))
)
x_latent = self.encoder(masked_inputs)
z_mean = self.mean_head(x_latent)
z_logvar = self.logvar_head(x_latent)
z = self.reparameterize(z_mean, z_logvar)
x_reconst = self.decoder(z)
# calculate masked loss only on the output_mask part of the reconstruction
inv_output_mask = torch.abs(
torch.ones(output_mask.size()).to(targets.device) - output_mask
)
rec_loss = (
torch.tensor(inv_output_mask).to(inputs.device)
* self._calc_reconstruction_loss(x_reconst, targets, reduction="none")
).mean()
kl_div = -0.5 * torch.mean(1 + z_logvar - z_mean.pow(2) - z_logvar.exp())
loss = rec_loss + kl_div
# raise error if masking rate is not none but masking strategy is not implemented
elif self.masking_rate and self.masking_strategy not in [
"random",
"gene_program",
]:
raise ValueError(
f"Masking strategy {self.masking_strategy} not implemented."
)
# raise error if masking strategy is not none but masking rate is 0.0
elif self.masking_strategy and self.masking_rate == 0.0:
raise ValueError(
f"Masking rate is 0 ({self.masking_rate}),"
f" but masking strategy {self.masking_strategy} is not None."
)
else:
x_latent = self.encoder(inputs.to(targets.device))
z_mean = self.mean_head(x_latent)
z_logvar = self.logvar_head(x_latent)
z = self.reparameterize(z_mean, z_logvar)
x_reconst = self.decoder(z)
rec_loss = self._calc_reconstruction_loss(x_reconst, targets, reduction="mean")
kl_div = -0.5 * torch.mean(1 + z_logvar - z_mean.pow(2) - z_logvar.exp())
loss = rec_loss + kl_div
return x_reconst, loss
def predict_embedding(self, batch):
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
return self.encoder(batch["X"])
def forward(self, x_in):
x_latent = self.encoder(x_in)
z_mean = self.mean_head(x_latent)
z_logvar = self.logvar_head(x_latent)
z = self.reparameterize(z_mean, z_logvar)
x_reconst = self.decoder(z)
return x_latent, x_reconst
def training_step(self, batch, batch_idx):
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return # Skip the batch if no items match the condition
# Filter the batch based on the mask
batch = {key: value[mask] for key, value in batch.items()}
x_reconst, loss = self._step(batch)
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
self.log_dict(
self.train_metrics(x_reconst, batch["X"]), on_epoch=True, on_step=True
)
self.log("train_loss", loss, on_epoch=True, on_step=True)
if batch_idx % self.gc_freq == 0:
gc.collect()
return loss
def validation_step(self, batch, batch_idx):
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return # Skip the batch if no items match the condition
# Filter the batch based on the mask
batch = {key: value[mask] for key, value in batch.items()}
x_reconst, loss = self._step(batch, training=False)
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
self.log_dict(self.val_metrics(x_reconst, batch["X"]))
self.log("val_loss", loss)
if batch_idx % self.gc_freq == 0:
gc.collect()
def test_step(self, batch, batch_idx):
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
# Filter the batch based on the mask
batch = {key: value[mask] for key, value in batch.items()}
x_reconst, loss = self._step(batch, training=False)
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
metrics = self.test_metrics(x_reconst, batch["X"])
self.log_dict(metrics)
self.log("test_loss", loss)
if batch_idx % self.gc_freq == 0:
gc.collect()
return metrics
def predict_cell_types(self, x: torch.Tensor):
return F.softmax(self(x)[0], dim=1)
def predict_step(
self, batch, batch_idx, dataloader_idx=None, predict_embedding=False
):
if batch_idx % self.gc_freq == 0:
gc.collect()
# Apply dataset_id filtering only if supervised_subset is set
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return None # Skip the batch if no items match the condition
# Filter the batch based on the mask
batch = {key: value[mask] for key, value in batch.items()}
if predict_embedding:
return self.encoder(batch["X"]).detach()
else:
preds_corrected, loss = self._step(batch, training=False)
return preds_corrected[mask], batch["cell_type"][mask]
else:
if predict_embedding:
return self.encoder(batch["X"]).detach()
else:
x_reconst, loss = self._step(batch, training=False)
return x_reconst, batch["X"]
def get_input(self, batch):
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
return batch["X"]
class MLPAutoEncoder(BaseAutoEncoder):
def __init__(
self,
# fixed params
gene_dim: int,
units_encoder: List[int],
units_decoder: List[int],
# params from datamodule
batch_size: int,
hvg: bool = False,
num_hvgs: int = 2000,
# model specific params
supervised_subset: Optional[int] = None,
reconstruction_loss: str = "mse",
learning_rate: float = 0.005,
weight_decay: float = 0.1,
dropout: float = 0.1,
optimizer: Callable[..., torch.optim.Optimizer] = torch.optim.AdamW,
lr_scheduler: Callable = None,
lr_scheduler_kwargs: Dict = None,
output_activation: Callable[[], torch.nn.Module] = nn.Sigmoid,
activation: Callable[[], torch.nn.Module] = nn.SELU,
# params for masking
masking_rate: Optional[float] = None,
masking_strategy: Optional[str] = None, # 'random', 'gene_program'
encoded_gene_program: Optional[Dict] = None,
):
# check input
assert 0.0 <= dropout <= 1.0
assert reconstruction_loss in ["mse", "mae", "continuous_bernoulli", "bce"]
if reconstruction_loss in ["continuous_bernoulli", "bce"]:
assert output_activation == nn.Sigmoid
self.batch_size = batch_size
self.supervised_subset = supervised_subset
super(MLPAutoEncoder, self).__init__(
gene_dim=gene_dim,
batch_size=batch_size,
learning_rate=learning_rate,
weight_decay=weight_decay,
optimizer=optimizer,
lr_scheduler=lr_scheduler,
lr_scheduler_kwargs=lr_scheduler_kwargs,
supervised_subset=supervised_subset,
)
self.encoder = MLP(
in_channels=gene_dim,
hidden_channels=units_encoder,
activation_layer=activation,
inplace=False,
dropout=dropout,
)
# Define decoder network
self.decoder = nn.Sequential(
MLP(
in_channels=units_encoder[-1],
hidden_channels=units_decoder + [gene_dim],
# norm_layer=_get_norm_layer(batch_norm=batch_norm, layer_norm=layer_norm),
activation_layer=activation,
inplace=False,
dropout=dropout,
),
output_activation(),
)
self.predict_bottleneck = False
metrics = MetricCollection(
{
"explained_var_weighted": ExplainedVariance(
multioutput="variance_weighted"
),
"explained_var_uniform": ExplainedVariance(
multioutput="uniform_average"
),
"mse": MeanSquaredError(),
}
)
self.train_metrics = metrics.clone(prefix="train_")
self.val_metrics = metrics.clone(prefix="val_")
self.test_metrics = metrics.clone(prefix="test_")
# masking
self.masking_rate = masking_rate
self.masking_strategy = masking_strategy
self.encoded_gene_program = encoded_gene_program
self.num_hvgs = num_hvgs
if hvg:
root = os.path.dirname(
os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
)
self.hvg_indices = pickle.load(
open(
root
+ "/self_supervision/data/hvg_"
+ str(self.num_hvgs)
+ "_indices.pickle",
"rb",
)
)
else:
self.hvg_indices = None
def _step(self, batch, training=True):
targets = batch["X"]
inputs = batch["X"]
if self.hvg_indices is not None:
inputs = inputs[:, self.hvg_indices]
targets = targets[:, self.hvg_indices]
if self.masking_rate and self.masking_strategy == "random":
mask = (
Bernoulli(probs=1.0 - self.masking_rate)
.sample(targets.size())
.to(targets.device)
)
# upscale inputs to compensate for masking and convert to same device
masked_inputs = 1.0 / (1.0 - self.masking_rate) * (inputs * mask)
x_latent, x_reconst = self(masked_inputs)
# calculate masked loss on masked part only
inv_mask = torch.abs(torch.ones(mask.size()).to(targets.device) - mask)
loss = (
inv_mask
* self._calc_reconstruction_loss(x_reconst, targets, reduction="none")
).mean()
elif self.masking_rate and self.masking_strategy == "gene_program":
with torch.no_grad():
# self.encoded gene program is a numpy array of encoded gene programs
mask, frac = _mask_gene_programs_numpy(
inputs, self.encoded_gene_program, self.masking_rate
)
mask = torch.tensor(mask).to(inputs.device)
# log the fraction of genes masked
self.log("frac_genes_masked", frac)
# mask, frac = self.mask_gene_programs(inputs, self.gene_program_dict, self.masking_rate)
# upscale inputs to compensate for masking
masked_inputs = 1.0 / (1.0 - frac) * (inputs * mask.to(inputs.device))
x_latent, x_reconst = self(masked_inputs)
# calculate masked loss
inv_mask = torch.abs(torch.ones(mask.size()).to(targets.device) - mask)
loss = (
inv_mask.to(inputs.device)
* self._calc_reconstruction_loss(x_reconst, targets, reduction="none")
).mean()
elif self.masking_rate and self.masking_strategy == "single_gene_program":
with torch.no_grad():
# self.encoded gene program is a numpy array of encoded gene programs
input_mask, output_mask = _mask_single_gene_programs(
inputs, self.encoded_gene_program
)
# log the fraction of genes masked
self.log("frac_genes_masked", frac)
# upscale inputs to compensate for masking
masked_inputs = (
1.0
/ (1.0 - frac)
* (inputs * torch.tensor(input_mask).to(inputs.device))
)
x_latent, x_reconst = self(masked_inputs)
# calculate masked loss only on the output_mask part of the reconstruction
inv_output_mask = torch.abs(
torch.ones(output_mask.size()).to(targets.device) - output_mask
)
loss = (
torch.tensor(inv_output_mask).to(inputs.device)
* self._calc_reconstruction_loss(x_reconst, targets, reduction="none")
).mean()
elif self.masking_rate and self.masking_strategy == "gp_to_tf":
with torch.no_grad():
# self.encoded gene program is a Dict of encoded gene programs and the corresponding tf indices
input_mask, output_mask = _only_activate_gene_program_numpy(
inputs, self.encoded_gene_program
)
# log the fraction of genes masked
self.log("frac_genes_masked", frac)
# upscale inputs to compensate for masking
masked_inputs = (
1.0
/ (1.0 - frac)
* (inputs * torch.tensor(input_mask).to(inputs.device))
)
x_latent, x_reconst = self(masked_inputs)
# calculate masked loss only on the output_mask part of the reconstruction
inv_output_mask = torch.abs(
torch.ones(output_mask.size()).to(targets.device) - output_mask
)
loss = (
torch.tensor(inv_output_mask).to(inputs.device)
* self._calc_reconstruction_loss(x_reconst, targets, reduction="none")
).mean()
# raise error if masking rate is not none but masking strategy is not implemented
elif self.masking_rate and self.masking_strategy not in [
"random",
"gene_program",
]:
raise ValueError(
f"Masking strategy {self.masking_strategy} not implemented."
)
# raise error if masking strategy is not none but masking rate is 0.0
elif self.masking_strategy and self.masking_rate == 0.0:
raise ValueError(
f"Masking rate is 0 ({self.masking_rate}),"
f" but masking strategy {self.masking_strategy} is not None."
)
else:
x_latent, x_reconst = self(inputs.to(targets.device))
loss = self._calc_reconstruction_loss(x_reconst, targets, reduction="mean")
return x_reconst, loss
def predict_embedding(self, batch):
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
return self.encoder(batch["X"])
def forward(self, x_in):
x_latent = self.encoder(x_in)
x_reconst = self.decoder(x_latent)
return x_latent, x_reconst
def training_step(self, batch, batch_idx):
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return # Skip the batch if no items match the condition
# Filter the batch based on the mask
batch = {key: value[mask] for key, value in batch.items()}
x_reconst, loss = self._step(batch)
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
self.log_dict(
self.train_metrics(x_reconst, batch["X"]), on_epoch=True, on_step=True
)
self.log("train_loss", loss, on_epoch=True, on_step=True)
if batch_idx % self.gc_freq == 0:
gc.collect()
return loss
def validation_step(self, batch, batch_idx):
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return # Skip the batch if no items match the condition
# Filter the batch based on the mask
batch = {key: value[mask] for key, value in batch.items()}
x_reconst, loss = self._step(batch, training=False)
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
self.log_dict(self.val_metrics(x_reconst, batch["X"]))
self.log("val_loss", loss)
if batch_idx % self.gc_freq == 0:
gc.collect()
def test_step(self, batch, batch_idx):
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
# Filter the batch based on the mask
batch = {key: value[mask] for key, value in batch.items()}
x_reconst, loss = self._step(batch, training=False)
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
metrics = self.test_metrics(x_reconst, batch["X"])
self.log_dict(metrics)
self.log("test_loss", loss)
if batch_idx % self.gc_freq == 0:
gc.collect()
return metrics
def predict_cell_types(self, x: torch.Tensor):
return F.softmax(self(x)[0], dim=1)
def predict_step(
self, batch, batch_idx, dataloader_idx=None, predict_embedding=False
):
if batch_idx % self.gc_freq == 0:
gc.collect()
# Apply dataset_id filtering only if supervised_subset is set
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return None # Skip the batch if no items match the condition
# Filter the batch based on the mask
batch = {key: value[mask] for key, value in batch.items()}
if predict_embedding:
return self.encoder(batch["X"]).detach()
else:
preds_corrected, loss = self._step(batch, training=False)
return preds_corrected[mask], batch["cell_type"][mask]
else:
if predict_embedding:
return self.encoder(batch["X"]).detach()
else:
x_reconst, loss = self._step(batch, training=False)
return x_reconst, batch["X"]
def get_input(self, batch):
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
return batch["X"]
class MLPNegBin(BaseAutoEncoder):
"""
Multi-Layer Perceptron (MLP) Autoencoder with Negative Binomial (NegBin) loss.
Args:
gene_dim (int): Dimensionality of the gene input.
units_encoder (List[int]): List of integers specifying the number of hidden units in each encoder layer.
units_decoder (List[int]): List of integers specifying the number of hidden units in each decoder layer.
batch_size (int): Batch size.
hvg (bool): Flag indicating whether to use highly variable genes (HVGs) for training.
num_hvgs (int): Number of highly variable genes to use.
supervised_subset (Optional[int]): Subset of the data to use for supervised training. Default is None.
learning_rate (float): Learning rate for the optimizer. Default is 0.005.
weight_decay (float): Weight decay for the optimizer. Default is 0.1.
dropout (float): Dropout rate. Default is 0.1.
optimizer (Callable[..., torch.optim.Optimizer]): Optimizer class. Default is torch.optim.AdamW.
lr_scheduler (Callable): Learning rate scheduler. Default is None.
lr_scheduler_kwargs (Dict): Additional keyword arguments for the learning rate scheduler. Default is None.
activation (Callable[[], torch.nn.Module]): Activation function. Default is nn.SELU.
masking_rate (Optional[float]): Rate of masking for input data. Default is None.
masking_strategy (Optional[str]): Masking strategy for input data. Default is None.
encoded_gene_program (Optional[Dict]): Encoded gene program. Default is None.
Raises:
NotImplementedError: If masking is not implemented for MLPNegBin.
Attributes:
encoder (MLP): Encoder module.
decoder (nn.Sequential): Decoder module.
masking_rate (Optional[float]): Rate of masking for input data.
masking_strategy (Optional[str]): Masking strategy for input data.
encoded_gene_program (Optional[Dict]): Encoded gene program.
num_hvgs (int): Number of highly variable genes.
hvg_indices (Optional[List[int]]): Indices of highly variable genes.
"""
def __init__(
self,
gene_dim: int,
units_encoder: List[int],
units_decoder: List[int],
batch_size: int,
hvg: bool = False,
num_hvgs: int = 2000,
supervised_subset: Optional[int] = None,
gene_likelihood: str = "nb", # 'zinb', 'nb', 'poisson'
learning_rate: float = 0.005,
weight_decay: float = 0.1,
dropout: float = 0.1,
optimizer: Callable[..., torch.optim.Optimizer] = torch.optim.AdamW,
lr_scheduler: Callable = None,
lr_scheduler_kwargs: Dict = None,
activation: Callable[[], torch.nn.Module] = nn.SELU,
# params for masking
masking_rate: Optional[float] = None,
masking_strategy: Optional[str] = None, # 'random', 'gene_program'
encoded_gene_program: Optional[Dict] = None,
):
super(MLPNegBin, self).__init__(
gene_dim=gene_dim,
batch_size=batch_size,
learning_rate=learning_rate,
weight_decay=weight_decay,
optimizer=optimizer,
lr_scheduler=lr_scheduler,
lr_scheduler_kwargs=lr_scheduler_kwargs,
supervised_subset=supervised_subset,
)
self.masking_rate = masking_rate
self.masking_strategy = masking_strategy
self.encoded_gene_program = encoded_gene_program
self.num_hvgs = num_hvgs
self.hvg_indices = self.load_hvg_indices(hvg, num_hvgs)
self.gene_likelihood = gene_likelihood
self.gene_dim = gene_dim
self.encoder = MLP(
in_channels=gene_dim,
hidden_channels=units_encoder,
activation_layer=activation,
inplace=False,
dropout=dropout,
)
# Decoder for gene counts
output_dim = self._get_decoder_output_dim()
self.decoder = nn.Sequential(
MLP(
in_channels=units_encoder[-1],
hidden_channels=units_decoder + [output_dim],
activation_layer=activation,
final_activation=torch.nn.Softplus
if self.gene_likelihood in ["nb", "zinb"]
else None,
inplace=False,
dropout=dropout,
)
)
# Dispersion parameters
if gene_likelihood in ["nb", "zinb"]:
self.px_r = nn.Parameter(torch.randn(self.gene_dim))
metrics = MetricCollection(
{
"explained_var_weighted": ExplainedVariance(
multioutput="variance_weighted"
),
"explained_var_uniform": ExplainedVariance(
multioutput="uniform_average"
),
"mse": MeanSquaredError(),
}
)
self.train_metrics = metrics.clone(prefix="train_")
self.val_metrics = metrics.clone(prefix="val_")
self.test_metrics = metrics.clone(prefix="test_")
self.masking_rate = masking_rate
self.masking_strategy = masking_strategy
self.encoded_gene_program = encoded_gene_program
def _get_decoder_output_dim(self):
if self.gene_likelihood == "zinb":
# Mean, dispersion, dropout logits
return 3 * self.gene_dim
elif self.gene_likelihood == "nb":
# Mean, dispersion
return 2 * self.gene_dim
elif self.gene_likelihood == "poisson":
# Mean only
return self.gene_dim
else:
raise ValueError(f"Invalid gene_likelihood: {self.gene_likelihood}")
def load_hvg_indices(self, hvg: bool, num_hvgs: int):
"""
Load the indices of highly variable genes.
Args:
hvg (bool): Flag indicating whether to use highly variable genes.
num_hvgs (int): Number of highly variable genes.
Returns:
Optional[List[int]]: List of indices of highly variable genes, or None if hvg is False.
"""
if hvg:
root = os.path.dirname(
os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
)
return pickle.load(
open(
root
+ "/self_supervision/data/hvg_"
+ str(num_hvgs)
+ "_indices.pickle",
"rb",
)
)
return None
def forward(self, x_in):
"""
Forward pass of the MLPNegBin model.
Args:
x_in (torch.Tensor): Input tensor.
Returns:
Tuple[torch.Tensor, torch.Tensor, torch.Tensor]: Tuple containing the latent representation, mean, and inverse dispersion.
"""
x_latent = self.encoder(x_in)
output = self.decoder(x_latent)
if self.gene_likelihood in ["nb", "zinb"]:
theta = self.px_r.exp()
# Extract parameters for gene expression likelihood distribution
if self.gene_likelihood == "zinb":
mu = output[:, : self.gene_dim]
pi = output[:, 2 * self.gene_dim :]
return x_latent, mu, theta, pi
elif self.gene_likelihood == "nb":
mu = output[:, : self.gene_dim]
return x_latent, mu, theta
elif self.gene_likelihood == "poisson":
mu = output
return x_latent, mu
def _calc_reconstruction_loss(self, x, output, reduction="mean"):
"""
Calculates the reconstruction loss for the autoencoder.
Args:
x (torch.Tensor): The input data.
output (tuple): The output of the autoencoder.
reduction (str, optional): Reduction method. Defaults to 'mean'.
Returns:
torch.Tensor: The reconstruction loss.
"""
if self.gene_likelihood == "zinb":
mu, theta, pi = output
px = ZeroInflatedNegativeBinomial(mu=mu, theta=theta, zi_logits=pi)
elif self.gene_likelihood == "nb":
mu, theta = output
px = NegativeBinomial(mu=mu, theta=theta)
elif self.gene_likelihood == "poisson":
mu = output
px = Poisson(mu)
if reduction == "mean":
return -px.log_prob(x).sum(-1).mean()
elif reduction == "none":
return -px.log_prob(x)
def _calc_reconstruction(self, output):
"""
Calculates the reconstructed transcriptome from the output of the autoencoder.
Args:
output (tuple): The output of the autoencoder.
Returns:
torch.Tensor: The reconstructed transcriptome.
"""
if self.gene_likelihood == "zinb":
mu, theta, pi = output
px = ZeroInflatedNegativeBinomial(mu=mu, theta=theta, zi_logits=pi)
elif self.gene_likelihood == "nb":
mu, theta = output
px = NegativeBinomial(mu=mu, theta=theta)
elif self.gene_likelihood == "poisson":
mu = output
px = Poisson(mu)
return px.mean
def _step(self, batch, training=True):
"""
Perform a single training/validation step.
Args:
batch (Dict[str, torch.Tensor]): Batch of input data.
training (bool): Flag indicating whether the model is in training mode. Default is True.
Returns:
Tuple[torch.Tensor, torch.Tensor]: Tuple containing the latent representation and loss.
"""
targets = batch["X"]
inputs = batch["X"]
if self.hvg_indices is not None:
inputs = inputs[:, self.hvg_indices]
targets = targets[:, self.hvg_indices]
if self.masking_rate and self.masking_strategy == "random":
mask = (
Bernoulli(probs=1.0 - self.masking_rate)
.sample(targets.size())
.to(targets.device)
)
# upscale inputs to compensate for masking and convert to same device
masked_inputs = 1.0 / (1.0 - self.masking_rate) * (inputs * mask)
# calculate masked loss on masked part only
inv_mask = torch.abs(torch.ones(mask.size()).to(targets.device) - mask)
if self.gene_likelihood == "zinb":
x_latent, mu, theta, pi = self(masked_inputs)
loss = (
(
inv_mask
* self._calc_reconstruction_loss(
targets, (mu, theta, pi), reduction="none"
)
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction((mu, theta, pi))
elif self.gene_likelihood == "nb":
x_latent, mu, theta = self(masked_inputs)
loss = (
(
inv_mask
* self._calc_reconstruction_loss(
targets, (mu, theta), reduction="none"
)
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction((mu, theta))
elif self.gene_likelihood == "poisson":
x_latent, mu = self(masked_inputs)
loss = (
(
inv_mask
* self._calc_reconstruction_loss(targets, mu, reduction="none")
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction(mu)
elif self.masking_rate and self.masking_strategy == "gene_program":
with torch.no_grad():
# self.encoded gene program is a numpy array of encoded gene programs
mask, frac = _mask_gene_programs_numpy(
inputs, self.encoded_gene_program, self.masking_rate
)
# log the fraction of genes masked
self.log("frac_genes_masked", frac)
# upscale inputs to compensate for masking
masked_inputs = (
1.0 / (1.0 - frac) * (inputs * torch.tensor(mask).to(inputs.device))
)
# calculate masked loss
inv_mask = torch.abs(torch.ones(mask.size()).to(targets.device) - mask)
if self.gene_likelihood == "zinb":
x_latent, mu, theta, pi = self(masked_inputs)
loss = (
(
inv_mask.to(inputs.device)
* self._calc_reconstruction_loss(
targets, (mu, theta, pi), reduction="none"
)
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction((mu, theta, pi))
elif self.gene_likelihood == "nb":
x_latent, mu, theta = self(masked_inputs)
loss = (
(
inv_mask.to(inputs.device)
* self._calc_reconstruction_loss(
targets, (mu, theta), reduction="none"
)
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction((mu, theta))
elif self.gene_likelihood == "poisson":
x_latent, mu = self(masked_inputs)
loss = (
(
inv_mask.to(inputs.device)
* self._calc_reconstruction_loss(targets, mu, reduction="none")
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction(mu)
elif self.masking_rate and self.masking_strategy == "single_gene_program":
with torch.no_grad():
# self.encoded gene program is a numpy array of encoded gene programs
input_mask, output_mask = _mask_single_gene_programs(
inputs, self.encoded_gene_program
)
# log the fraction of genes masked
self.log("frac_genes_masked", frac)
# upscale inputs to compensate for masking
masked_inputs = (
1.0
/ (1.0 - frac)
* (inputs * torch.tensor(input_mask).to(inputs.device))
)
# calculate masked loss only on the output_mask part of the reconstruction
inv_output_mask = torch.abs(
torch.ones(output_mask.size()).to(targets.device) - output_mask
)
if self.gene_likelihood == "zinb":
x_latent, mu, theta, pi = self(masked_inputs)
loss = (
(
torch.tensor(inv_output_mask).to(inputs.device)
* self._calc_reconstruction_loss(
targets, (mu, theta, pi), reduction="none"
)
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction((mu, theta, pi))
elif self.gene_likelihood == "nb":
x_latent, mu, theta = self(masked_inputs)
loss = (
(
torch.tensor(inv_output_mask).to(inputs.device)
* self._calc_reconstruction_loss(
targets, (mu, theta), reduction="none"
)
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction((mu, theta))
elif self.gene_likelihood == "poisson":
x_latent, mu = self(masked_inputs)
loss = (
(
torch.tensor(inv_output_mask).to(inputs.device)
* self._calc_reconstruction_loss(targets, mu, reduction="none")
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction(mu)
elif self.masking_rate and self.masking_strategy == "gp_to_tf":
with torch.no_grad():
# self.encoded gene program is a Dict of encoded gene programs and the corresponding tf indices
input_mask, output_mask = _only_activate_gene_program_numpy(
inputs, self.encoded_gene_program
)
# log the fraction of genes masked
self.log("frac_genes_masked", frac)
# upscale inputs to compensate for masking
masked_inputs = (
1.0
/ (1.0 - frac)
* (inputs * torch.tensor(input_mask).to(inputs.device))
)
# calculate masked loss only on the output_mask part of the reconstruction
inv_output_mask = torch.abs(
torch.ones(output_mask.size()).to(targets.device) - output_mask
)
if self.gene_likelihood == "zinb":
x_latent, mu, theta, pi = self(masked_inputs)
loss = (
(
torch.tensor(inv_output_mask).to(inputs.device)
* self._calc_reconstruction_loss(
targets, (mu, theta, pi), reduction="none"
)
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction((mu, theta, pi))
elif self.gene_likelihood == "nb":
x_latent, mu, theta = self(masked_inputs)
loss = (
(
torch.tensor(inv_output_mask).to(inputs.device)
* self._calc_reconstruction_loss(
targets, (mu, theta), reduction="none"
)
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction((mu, theta))
elif self.gene_likelihood == "poisson":
x_latent, mu = self(masked_inputs)
loss = (
(
torch.tensor(inv_output_mask).to(inputs.device)
* self._calc_reconstruction_loss(targets, mu, reduction="none")
)
.sum(-1)
.mean()
)
x_reconst = self._calc_reconstruction(mu)
# raise error if masking rate is not none but masking strategy is not implemented
elif self.masking_rate and self.masking_strategy not in [
"random",
"gene_program",
]:
raise ValueError(
f"Masking strategy {self.masking_strategy} not implemented."
)
# raise error if masking strategy is not none but masking rate is 0.0
elif self.masking_strategy and self.masking_rate == 0.0:
raise ValueError(
f"Masking rate is 0 ({self.masking_rate}),"
f" but masking strategy {self.masking_strategy} is not None."
)
else:
# x_latent, mu, theta = self(inputs.to(targets.device))
out = self(inputs.to(targets.device))
if self.gene_likelihood == "zinb":
x_latent, mu, theta, pi = out
loss = self._calc_reconstruction_loss(targets, (mu, theta, pi))
x_reconst = self._calc_reconstruction((mu, theta, pi))
elif self.gene_likelihood == "nb":
x_latent, mu, theta = out
loss = self._calc_reconstruction_loss(targets, (mu, theta))
x_reconst = self._calc_reconstruction((mu, theta))
elif self.gene_likelihood == "poisson":
x_latent, mu = out
loss = self._calc_reconstruction_loss(targets, mu)
x_reconst = self._calc_reconstruction(mu)
else:
raise ValueError(f"Invalid gene_likelihood: {self.gene_likelihood}")
return x_latent, loss, x_reconst
def predict_embedding(self, batch):
"""
Predict the embedding for a given batch.
Args:
batch (Dict[str, torch.Tensor]): Batch of input data.
Returns:
torch.Tensor: Embedding tensor.
"""
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
return self.encoder(batch["X"])
def training_step(self, batch, batch_idx):
"""
Training step.
Args:
batch (Dict[str, torch.Tensor]): Batch of input data.
batch_idx (int): Index of the current batch.
Returns:
torch.Tensor: Loss value.
"""
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return
batch = {key: value[mask] for key, value in batch.items()}
x_latent, loss, _ = self._step(batch)
self.log("train_loss", loss, on_epoch=True, on_step=True)
if batch_idx % self.gc_freq == 0:
gc.collect()
return loss
def validation_step(self, batch, batch_idx):
"""
Validation step.
Args:
batch (Dict[str, torch.Tensor]): Batch of input data.
batch_idx (int): Index of the current batch.
"""
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return
batch = {key: value[mask] for key, value in batch.items()}
x_latent, loss, _ = self._step(batch, training=False)
self.log("val_loss", loss)
if batch_idx % self.gc_freq == 0:
gc.collect()
def test_step(self, batch, batch_idx):
"""
Test step.
Args:
batch (Dict[str, torch.Tensor]): Batch of input data.
batch_idx (int): Index of the current batch.
"""
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
batch = {key: value[mask] for key, value in batch.items()}
x_latent, loss, x_reconst = self._step(batch, training=False)
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
metrics = self.test_metrics(x_reconst, batch["X"])
self.log_dict(metrics)
self.log("test_loss", loss)
if batch_idx % self.gc_freq == 0:
gc.collect()
return metrics
class MLPClassifier(BaseClassifier):
"""
Multi-Layer Perceptron (MLP) classifier for cell type classification.
Args:
gene_dim (int): Dimension of the gene input.
type_dim (int): Dimension of the cell type output.
class_weights (np.ndarray): Array of class weights for loss calculation.
child_matrix (np.ndarray): Matrix representing the hierarchical relationship between cell types.
units (List[int]): List of hidden unit sizes for the MLP.
batch_size (int): Batch size for training and inference.
hvg (bool): Flag indicating whether to use highly variable genes.
num_hvgs (int): Number of highly variable genes to use.
supervised_subset (Optional[int], optional): Subset of the data to use for supervised training. Defaults to None.
dropout (float, optional): Dropout rate. Defaults to 0.0.
learning_rate (float, optional): Learning rate for optimizer. Defaults to 0.005.
weight_decay (float, optional): Weight decay for optimizer. Defaults to 0.1.
optimizer (Callable[..., torch.optim.Optimizer], optional): Optimizer class. Defaults to torch.optim.AdamW.
lr_scheduler (Callable, optional): Learning rate scheduler. Defaults to None.
lr_scheduler_kwargs (Dict, optional): Additional keyword arguments for the learning rate scheduler. Defaults to None.
"""
def __init__(
self,
gene_dim: int,
type_dim: int,
class_weights: np.ndarray,
child_matrix: np.ndarray,
units: List[int],
batch_size: int,
hvg: bool = False,
num_hvgs: int = 2000,
supervised_subset: Optional[int] = None,
dropout: float = 0.0,
learning_rate: float = 0.005,
weight_decay: float = 0.1,
optimizer: Callable[..., torch.optim.Optimizer] = torch.optim.AdamW,
lr_scheduler: Callable = None,
lr_scheduler_kwargs: Dict = None,
):
super(MLPClassifier, self).__init__(
gene_dim=gene_dim,
type_dim=type_dim,
class_weights=class_weights,
child_matrix=child_matrix,
batch_size=batch_size,
hvg=hvg,
num_hvgs=num_hvgs,
supervised_subset=supervised_subset,
learning_rate=learning_rate,
weight_decay=weight_decay,
optimizer=optimizer,
lr_scheduler=lr_scheduler,
lr_scheduler_kwargs=lr_scheduler_kwargs,
)
self.classifier = MLP(
in_channels=gene_dim,
hidden_channels=units + [type_dim],
dropout=dropout,
inplace=False,
)
def _step(self, batch, training=True):
"""
Perform a forward pass and calculate the loss for a batch.
Args:
batch (dict): Dictionary containing the input data batch.
training (bool, optional): Flag indicating whether the model is in training mode. Defaults to True.
Returns:
torch.Tensor: Corrected predictions for the batch.
torch.Tensor: Loss value for the batch.
"""
logits = self(batch["X"])
with torch.no_grad():
preds = torch.argmax(logits, dim=1)
preds_corrected, targets_corrected = self.hierarchy_correct(
preds, batch["cell_type"]
)
if training:
loss = F.cross_entropy(
logits, batch["cell_type"], weight=self.class_weights
)
else:
loss = F.cross_entropy(logits, targets_corrected)
return preds_corrected, loss
def predict_step(
self, batch, batch_idx, dataloader_idx=None, predict_embedding=False
):
"""
Perform a prediction step for a batch.
Args:
batch (tuple or dict): Input data batch.
batch_idx (int): Index of the batch.
dataloader_idx (int, optional): Index of the dataloader. Defaults to None.
predict_embedding (bool, optional): Flag indicating whether to predict the embedding. Defaults to False.
Returns:
torch.Tensor or None: Predicted values for the batch.
torch.Tensor or None: Target values for the batch.
"""
if isinstance(batch, tuple):
batch = batch[0]
if batch_idx % self.gc_freq == 0:
gc.collect()
# Apply dataset_id filtering only if supervised_subset is set
if self.supervised_subset is not None:
mask = batch["dataset_id"] == self.supervised_subset
if not any(mask):
return None, None # Skip the batch if no items match the condition
filtered_batch = {key: value[mask] for key, value in batch.items()}
if predict_embedding:
return self.encoder(filtered_batch["X"]).detach(), filtered_batch[
"cell_type"
]
else:
preds_corrected, loss = self._step(filtered_batch, training=False)
return preds_corrected, filtered_batch["cell_type"]
else:
if predict_embedding:
return self.encoder(batch["X"]).detach(), filtered_batch["cell_type"]
else:
preds_corrected, loss = self._step(batch, training=False)
return preds_corrected, batch["cell_type"]
def forward_embedding(self, x: torch.Tensor) -> torch.Tensor:
"""
Forward pass to compute the embedding from the MLP.
The computed embedding is the output before the last Linear layer of the MLP.
Args:
x (torch.Tensor): Input tensor.
Returns:
torch.Tensor: Computed embedding tensor.
"""
for i, layer in enumerate(self.classifier):
x = layer(x)
if i == len(self.classifier) - 2:
break
return x
def predict_embedding(self, batch, batch_idx, dataloader_idx=None) -> torch.Tensor:
"""
Function to predict the embedding from the given batch.
Args:
batch (dict): Input data batch.
batch_idx (int): Index of the batch.
dataloader_idx (int, optional): Index of the dataloader. Defaults to None.
Returns:
torch.Tensor: Predicted embedding tensor.
"""
x = batch["X"]
return self.forward_embedding(x)
class MLPBYOL(BaseAutoEncoder):
def __init__(
self,
# fixed params
gene_dim: int,
units_encoder: List[int],
# params from datamodule
batch_size: int,
# contrastive learning params
backbone: str, # MLP, TabNet
augment_type: str, # Gaussian, Uniform
augment_intensity: float,
use_momentum: bool,
# model specific params
hvg: bool = False,
num_hvgs: int = 2000,
lr: float = 0.005,
weight_decay: float = 0.1,
dropout: float = 0.1,
optimizer: Callable[..., torch.optim.Optimizer] = torch.optim.AdamW,
lr_scheduler: Callable = None,
lr_scheduler_kwargs: Dict = None,
activation: Callable[[], torch.nn.Module] = nn.SELU,
):
# check input
assert 0.0 <= dropout <= 1.0
self.batch_size = batch_size
super(MLPBYOL, self).__init__(
gene_dim=gene_dim,
batch_size=batch_size,
learning_rate=lr,
weight_decay=weight_decay,
optimizer=optimizer,
lr_scheduler=lr_scheduler,
lr_scheduler_kwargs=lr_scheduler_kwargs,
)
# assign inner model, that will be trained using the BYOL / SimSiam framework
self.backbone = backbone
self.gene_dim = gene_dim
self.units_encoder = units_encoder
self.activation = activation
self.dropout = dropout
self.inner_model = self._get_inner_model()
self.num_hvgs = num_hvgs
self.byol = BYOL(
net=self.inner_model,
image_size=self.gene_dim,
augment_type=augment_type,
augment_intensity=augment_intensity,
batch_size=self.batch_size,
use_momentum=use_momentum,
)
if hvg:
root = os.path.dirname(
os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
)
self.hvg_indices = pickle.load(
open(
root
+ "/self_supervision/data/hvg_"
+ str(self.num_hvgs)
+ "_indices.pickle",
"rb",
)
)
else:
self.hvg_indices = None
def _get_inner_model(self):
if self.backbone == "MLP":
self.inner_model = MLP(
in_channels=self.gene_dim,
hidden_channels=self.units_encoder,
activation_layer=self.activation,
inplace=False,
dropout=self.dropout,
)
elif self.backbone == "TabNet":
raise NotImplementedError
else:
raise NotImplementedError
return self.inner_model
def _step(self, batch):
loss = self.forward(batch)
return loss
def predict_embedding(self, batch, batch_idx):
if batch_idx % self.gc_freq == 0:
gc.collect()
return self.encoder(batch["X"])
def forward(self, batch):
if self.hvg_indices is not None:
batch["X"] = batch["X"][:, self.hvg_indices]
return self.byol(batch["X"])
def training_step(self, batch, batch_idx):
loss = self._step(batch)
self.log("train_loss", loss, on_epoch=True)
if batch_idx % self.gc_freq == 0:
gc.collect()
return loss
def validation_step(self, batch, batch_idx):
loss = self._step(batch)
self.log("val_loss", loss)
if batch_idx % self.gc_freq == 0:
gc.collect()
def test_step(self, batch, batch_idx):
loss = self._step(batch)
self.log("test_loss", loss)
if batch_idx % self.gc_freq == 0:
gc.collect()
def predict_step(self, batch, batch_idx, dataloader_idx: Optional[int] = None):
x_reconst, loss = self(batch)
if batch_idx % self.gc_freq == 0:
gc.collect()
return x_reconst, batch
# helper
class DictAsAttributes:
def __init__(self, dictionary):
self.__dict__.update(dictionary)
class MLPBarlowTwins(BaseAutoEncoder):
def __init__(
self,
# fixed params
gene_dim: int,
units_encoder: List[int],
# params from datamodule
CHECKPOINT_PATH: str,
augment_intensity: float,
train_set_size: int,
batch_size: int,
hvg: bool = False,
num_hvgs: int = 2000,
# contrastive learning params
backbone: str = 'MLP', # MLP, TabNet
learning_rate_weights: float = 0.2,
learning_rate_biases: float = 0.0048,
lambd: float = 0.0051,
lr: float = 0.005, # dummy here
weight_decay: float = 1e-6,
dropout: float = 0.0,
optimizer: Callable[..., torch.optim.Optimizer] = torch.optim.AdamW,
lr_scheduler: Callable = None, # dummy here
lr_scheduler_kwargs: Dict = None, # dummy here
activation: Callable[[], torch.nn.Module] = nn.SELU,
):
# check input
assert 0.0 <= dropout <= 1.0
super(MLPBarlowTwins, self).__init__(
gene_dim=gene_dim,
batch_size=batch_size,
learning_rate=lr,
weight_decay=weight_decay,
optimizer=optimizer,
lr_scheduler=lr_scheduler,
lr_scheduler_kwargs=lr_scheduler_kwargs,
automatic_optimization=False,
)
self.save_hyperparameters(ignore=["gene_dim"])
self.best_val_loss = np.inf
self.best_train_loss = np.inf
self.num_hvgs = num_hvgs
self.train_set_size = train_set_size
self.batch_size = batch_size
self.weight_decay = weight_decay
self.learning_rate_weights = learning_rate_weights
self.learning_rate_biases = learning_rate_biases
self.lambd = lambd
self.loader_length = self.train_set_size // self.batch_size
self.step = 0 # for optimizer
# assign inner model, that will be trained using the BYOL / SimSiam framework
self.backbone = backbone
self.gene_dim = gene_dim
self.units_encoder = units_encoder
self.activation = activation
self.dropout = dropout
self.batch_size = batch_size
self.hvg = hvg
self.transform = Transform(p=augment_intensity)
self.CHECKPOINT_PATH = CHECKPOINT_PATH
if hvg:
root = os.path.dirname(
os.path.dirname(
os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
)
)
self.hvg_indices = pickle.load(
open(
root
+ "/self_supervision/data/hvg_"
+ str(self.num_hvgs)
+ "_indices.pickle",
"rb",
)
)
else:
self.hvg_indices = None
inner_model = self._get_inner_model()
# Initialize the model-specific parameters
self.dropout = dropout
self.activation = activation
self.units_encoder = units_encoder
self.barlow_twins = self._get_barlow_twins_model(inner_model)
def _get_barlow_twins_model(self, inner_model):
args = (
self._prepare_barlow_twins_args()
) # Prepare the Barlow Twins arguments (use the relevant params)
self.barlow_twins = BarlowTwins(backbone=inner_model, args=args)
return self.barlow_twins
def _get_inner_model(self):
if self.backbone == "MLP":
self.inner_model = MLP(
in_channels=self.gene_dim,
hidden_channels=self.units_encoder,
activation_layer=self.activation,
inplace=False,
dropout=self.dropout,
)
else:
raise NotImplementedError
return self.inner_model
def _prepare_barlow_twins_args(self):
# Prepare Barlow Twins arguments based on the required parameters
args = {
# 'data': ..., # Path to your dataset directory (from class B)
# 'workers': 8, # number of data loader workers
"epochs": 1000, # number of total epochs to run
"batch_size": self.batch_size, # mini-batch size
"learning_rate_weights": self.learning_rate_weights, # base learning rate for weights
"learning_rate_biases": self.learning_rate_biases,
# base learning rate for biases and batch norm parameters
"weight-decay": self.weight_decay, # weight decay
"lambd": self.lambd, # weight on off-diagonal terms
"projector": "256-256-512-512", # projector MLP
# 'print_freq': 100, # print frequency
# 'checkpoint_dir': './checkpoint/' # path to checkpoint directory
}
self.args = DictAsAttributes(args)
return self.args
def _step(self, batch):
# For Multiomics, batch['X'] has additional dim to squeeze
if batch["X"].dim() == 3:
batch["X"] = batch["X"].squeeze(1)
if self.hvg_indices is not None:
x_in = batch["X"][:, self.hvg_indices]
else:
x_in = batch["X"]
# Modify the forward pass to use the Barlow Twins model (from class B)
loss = self(x_in)
return loss
def predict_embedding(self, batch, batch_idx):
if batch_idx % self.gc_freq == 0:
gc.collect()
return self.encoder(batch["X"])
def forward(self, batch):
# Apply two different augmentations to the same image
y1, y2 = self.transform(batch)
# Compute the Barlow Twins loss
loss = self.barlow_twins(y1, y2)
return loss
def training_step(self, batch, batch_idx):
# Increment the step counter
self.step += 1
# Initialize the optimizer
param_weights = []
param_biases = []
for param in self.barlow_twins.parameters():
if param.ndim == 1:
param_biases.append(param)
else:
param_weights.append(param)
parameters = [{"params": param_weights}, {"params": param_biases}]
opt = LARS(
parameters,
lr=0,
weight_decay=self.weight_decay,
weight_decay_filter=True,
lars_adaptation_filter=True,
)
# Adjust the learning rate
adjust_learning_rate(self.args, opt, self.loader_length, self.step)
# Zero the gradient before loss computation
opt.zero_grad()
# Calculate the loss
loss = self._step(batch)
# Manual backward pass and optimizer step
self.manual_backward(loss)
opt.step()
self.log("train_loss", loss, on_epoch=True)
if batch_idx % self.gc_freq == 0:
gc.collect()
if loss < self.best_train_loss:
self.best_train_loss = loss
self.barlow_twins.save_model(
path=self.CHECKPOINT_PATH + "/best_checkpoint_train.ckpt"
)
self.barlow_twins.save_model(
path=self.CHECKPOINT_PATH + "/last_checkpoint.ckpt"
)
return loss
def validation_step(self, batch, batch_idx):
loss = self._step(batch)
self.log("val_loss", loss)
if batch_idx % self.gc_freq == 0:
gc.collect()
if loss < self.best_val_loss:
self.best_val_loss = loss
self.barlow_twins.save_model(
path=self.CHECKPOINT_PATH + "/best_checkpoint_val.ckpt"
)
def test_step(self, batch, batch_idx):
loss = self._step(batch)
self.log("test_loss", loss)
if batch_idx % self.gc_freq == 0:
gc.collect()
def predict_step(self, batch, batch_idx, dataloader_idx: Optional[int] = None):
x_reconst, loss = self(batch)
if batch_idx % self.gc_freq == 0:
gc.collect()
return x_reconst, batch
|