pytorch_dataset
MEDSPytorchDataset
Bases: Dataset
A PyTorch dataset that provides efficient PyTorch access to a MEDS dataset.
This dataset is designed to work with data from the MEDS (Medical Event Data Set) format, supporting various types of medical events, static patient information, and task-specific labels. It provides functionality for loading, processing, and collating data for use in PyTorch models in an efficient manner that takes advantage of the sparsity of EHR data to minimize memory usage and computational time.
Key design principles
- The class will store an
indexvariable that specifies what is the valid range of data to consider for any given subject in the dataset corresponding to an integer index passed to__getitem__. - Subject tensor data is loaded on an as-needed basis and is not cached, to minimize memory
usage during normal operation. (JNRT handles are memoized per
(shard, load_keys)onself._jnrt_cacheto avoid rebuilding the handle object on every__getitem__β this is a Python-level wrapper cache, not a cache of the underlying tensor bytes.) - As much work as possible should be relegated to separate dataset pre-processing (resulting in files stored on disk) rather than this class to streamline operation.
- The primary input to this class in terms of data is a pre-processed set of “schema files” and “nested ragged tensor” data files that can be used to identify the shape of the dataset and to efficiently load the relevant tensor data, respectively.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
|
MEDSTorchDataConfig
|
Configuration options for the dataset, realized through a dataclass instance. |
required |
split
|
str
|
The data split to use. This must match up to the splits stored in the root dataset’s
|
required |
Attributes:
| Name | Type | Description |
|---|---|---|
config |
MEDSTorchDataConfig
|
The configuration options for the dataset. |
split |
str
|
The data split to use. |
schema_dfs_by_shard |
dict[str, DataFrame]
|
A dictionary mapping shard names to the schema DataFrames for that shard. |
subj_locations |
dict[int, tuple[str, int]]
|
A dictionary mapping subject IDs to their locations in the schema DataFrames. |
index |
A list of tuples, where each tuple contains the subject ID and the end index for that subject. |
|
labels |
The task labels for the dataset, if any. This will be |
For examples of this class, see the global README.md. Here, we’ll include some examples of other aspects of the class, such as error validation and specific methods.
Examples:
>>> cfg = MEDSTorchDataConfig(tensorized_cohort_dir=tensorized_MEDS_dataset, max_seq_len=5)
>>> pyd = MEDSPytorchDataset(cfg, split="train")
>>> len(pyd)
4
>>> pyd.index
[(239684, 6), (1195293, 8), (68729, 3), (814703, 3)]
If you pass in a non-existent split, you’ll get an error as it won’t be able to find the schema files:
>>> pyd = MEDSPytorchDataset(cfg, split="nonexistent")
Traceback (most recent call last):
...
FileNotFoundError: No schema files found in /tmp/.../tokenization/schemas! If your data is not sharded
by split, this error may occur because this codebase does not handle non-split sharded data. See Issue
#79 for tracking this issue.
Source code in meds_torchdata/pytorch_dataset.py
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 | |
_all_schemas
property
This is a helper for easy access to the full set of schema dataframes for debugging.
has_task_index
property
has_task_labels
property
labels_df
property
Returns the task labels as a DataFrame, in the MEDS Label schema, or None if there is no task.
Examples:
>>> print(sample_pytorch_dataset.labels_df)
None
>>> sample_pytorch_dataset_with_task.labels_df
shape: (21, 3)
ββββββββββββββ¬ββββββββββββββββββββββ¬ββββββββββββββββ
β subject_id β prediction_time β boolean_value β
β --- β --- β --- β
β i64 β datetime[ΞΌs] β bool β
ββββββββββββββͺββββββββββββββββββββββͺββββββββββββββββ‘
β 239684 β 2010-05-11 18:00:00 β false β
β 239684 β 2010-05-11 18:30:00 β true β
β 239684 β 2010-05-11 19:00:00 β true β
β 1195293 β 2010-06-20 19:30:00 β false β
β 1195293 β 2010-06-20 20:00:00 β true β
β β¦ β β¦ β β¦ β
β 754281 β 2010-01-03 08:00:00 β true β
β 1500733 β 2010-06-03 15:00:00 β false β
β 1500733 β 2010-06-03 15:30:00 β false β
β 1500733 β 2010-06-03 16:00:00 β true β
β 1500733 β 2010-06-03 16:30:00 β true β
ββββββββββββββ΄ββββββββββββββββββββββ΄ββββββββββββββββ
>>> sample_pytorch_dataset_with_index.labels_df
shape: (21, 2)
ββββββββββββββ¬ββββββββββββββββββββββ
β subject_id β prediction_time β
β --- β --- β
β i64 β datetime[ΞΌs] β
ββββββββββββββͺββββββββββββββββββββββ‘
β 239684 β 2010-05-11 18:00:00 β
β 239684 β 2010-05-11 18:30:00 β
β 239684 β 2010-05-11 19:00:00 β
β 1195293 β 2010-06-20 19:30:00 β
β 1195293 β 2010-06-20 20:00:00 β
β β¦ β β¦ β
β 754281 β 2010-01-03 08:00:00 β
β 1500733 β 2010-06-03 15:00:00 β
β 1500733 β 2010-06-03 15:30:00 β
β 1500733 β 2010-06-03 16:00:00 β
β 1500733 β 2010-06-03 16:30:00 β
ββββββββββββββ΄ββββββββββββββββββββββ
schema_df
cached
property
Returns the “schema” of this dataframe, cataloging each sample that will be output by row.
This takes into account both task and non-task data, and is useful for aligning dataloader or model outputs to the source inputs.
Examples:
>>> sample_pytorch_dataset.schema_df
shape: (4, 2)
ββββββββββββββ¬ββββββββββββββββββ
β subject_id β end_event_index β
β --- β --- β
β i64 β u32 β
ββββββββββββββͺββββββββββββββββββ‘
β 239684 β 6 β
β 1195293 β 8 β
β 68729 β 3 β
β 814703 β 3 β
ββββββββββββββ΄ββββββββββββββββββ
>>> sample_pytorch_dataset_with_task.schema_df
shape: (13, 4)
ββββββββββββββ¬ββββββββββββββββββ¬ββββββββββββββββββββββ¬ββββββββββββββββ
β subject_id β end_event_index β prediction_time β boolean_value β
β --- β --- β --- β --- β
β i64 β u32 β datetime[ΞΌs] β bool β
ββββββββββββββͺββββββββββββββββββͺββββββββββββββββββββββͺββββββββββββββββ‘
β 239684 β 3 β 2010-05-11 18:00:00 β false β
β 239684 β 4 β 2010-05-11 18:30:00 β true β
β 239684 β 5 β 2010-05-11 19:00:00 β true β
β 1195293 β 3 β 2010-06-20 19:30:00 β false β
β 1195293 β 4 β 2010-06-20 20:00:00 β true β
β β¦ β β¦ β β¦ β β¦ β
β 68729 β 2 β 2010-05-26 04:00:00 β true β
β 68729 β 2 β 2010-05-26 04:30:00 β true β
β 814703 β 2 β 2010-02-05 06:00:00 β false β
β 814703 β 2 β 2010-02-05 06:30:00 β true β
β 814703 β 2 β 2010-02-05 07:00:00 β true β
ββββββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββββββββ΄ββββββββββββββββ
>>> sample_pytorch_dataset_with_index.schema_df
shape: (13, 3)
ββββββββββββββ¬ββββββββββββββββββ¬ββββββββββββββββββββββ
β subject_id β end_event_index β prediction_time β
β --- β --- β --- β
β i64 β u32 β datetime[ΞΌs] β
ββββββββββββββͺββββββββββββββββββͺββββββββββββββββββββββ‘
β 239684 β 3 β 2010-05-11 18:00:00 β
β 239684 β 4 β 2010-05-11 18:30:00 β
β 239684 β 5 β 2010-05-11 19:00:00 β
β 1195293 β 3 β 2010-06-20 19:30:00 β
β 1195293 β 4 β 2010-06-20 20:00:00 β
β β¦ β β¦ β β¦ β
β 68729 β 2 β 2010-05-26 04:00:00 β
β 68729 β 2 β 2010-05-26 04:30:00 β
β 814703 β 2 β 2010-02-05 06:00:00 β
β 814703 β 2 β 2010-02-05 06:30:00 β
β 814703 β 2 β 2010-02-05 07:00:00 β
ββββββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββββββββ
__getitem__(idx)
Retrieve a single data point from the dataset.
This method returns a dictionary corresponding to a single subject’s data at the specified index. The data is not tensorized in this method, as that work is typically done in the collate function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
idx
|
int
|
The index of the data point to retrieve. |
required |
Returns:
| Type | Description |
|---|---|
dict[str, Tensor]
|
A dictionary containing the static code, static numeric value, dynamic data, and task label (if |
dict[str, Tensor]
|
present) for the specified subject. |
Source code in meds_torchdata/pytorch_dataset.py
__len__()
Returns the length of the dataset.
Examples:
_effective_max_seq_len_for(subject_id)
Return the dynamic-window size a step-through sample can reserve for this subject.
This mirrors the max_seq_len -= n_static_seq_els adjustment inside
MEDSTorchDataConfig.process_dynamic_data for PREPEND mode β so that the
resulting [static; dynamic] sample after prepending still has length
<= config.max_seq_len. For every other static inclusion mode this returns
config.max_seq_len unchanged. In SM + PREPEND the reduction varies per subject
because n_static_seq_els == len(static_code[subject_id]).
Examples:
With the default sample_dataset_config (max_seq_len=10, SM batch mode,
static_inclusion_mode=INCLUDE), the effective window equals max_seq_len
unchanged for every subject:
>>> pyd = sample_pytorch_dataset
>>> pyd.config.max_seq_len
10
>>> pyd.config.batch_mode
<BatchMode.SM: 'SM'>
>>> pyd.config.static_inclusion_mode
<StaticInclusionMode.INCLUDE: 'include'>
>>> [pyd._effective_max_seq_len_for(s) for s in (239684, 1195293, 68729, 814703)]
[10, 10, 10, 10]
In SM + PREPEND the reduction is len(static_code) per subject β every
fixture subject has two static codes, so their effective window shrinks from
10 to 8:
>>> import dataclasses
>>> sm_prepend_cfg = dataclasses.replace(
... pyd.config, static_inclusion_mode="prepend"
... )
>>> sm_prepend_pyd = MEDSPytorchDataset(sm_prepend_cfg, split="train")
>>> [sm_prepend_pyd._effective_max_seq_len_for(s) for s in (239684, 1195293)]
[8, 8]
In SEM + PREPEND the reduction is a flat 1 (one event slot reserved for the
prepended static event):
>>> sem_prepend_cfg = dataclasses.replace(
... pyd.config, batch_mode="SEM", static_inclusion_mode="prepend"
... )
>>> sem_prepend_pyd = MEDSPytorchDataset(sem_prepend_cfg, split="train")
>>> [sem_prepend_pyd._effective_max_seq_len_for(s) for s in (239684, 1195293)]
[9, 9]
Source code in meds_torchdata/pytorch_dataset.py
_expand_index_for_step_through()
Expand self.index so that STEP_THROUGH sampling produces one entry per window.
For each subject in the pre-expansion index, this walks a sliding window of size
max_seq_len across the permitted sequence with either a user-supplied
step_through_stride or a user-supplied step_through_overlap, producing one
dataset element per window.
The walk is expressed in the same unit as max_seq_len: events in BatchMode.SEM,
measurements in BatchMode.SM. In SM mode this means the window ends can fall
mid-event β for example a subject with two events [3, 5] measurements and
max_seq_len=4 with step_through_stride=2 produces windows [0:4), [2:6), and
[4:8) β the second window ends in the middle of the second event. This is the
intentional Design B semantics: step-through walks the measurement-level sequence
regardless of event atomicity. See the class docstring for alternatives.
The per-subject measurement-level walk is powered by measurements_per_event, a new
preprocessing column that records the measurement count at each unique timestamp for
each subject. In SM mode we use np.searchsorted on the per-subject cumulative sum
to find the smallest event index whose prefix contains each target measurement end β
that’s the end stored in self.index (for load_subject_data) β while the
measurement-level end itself is recorded in self.step_through_meas_ends and passed
through MEDSTorchDataConfig.process_dynamic_data’s explicit_end kwarg at sample
time.
Validation at construction time:
- stride (or the derived effective_window - overlap) must be positive.
- stride <= effective_window per subject, so consecutive windows overlap by
effective_window - stride >= 0 elements and no data is skipped.
- For SM mode, the measurements_per_event column must exist on the schema parquet
(re-run preprocessing if it’s missing from an older cohort).
A warning with observed expansion stats is logged on startup; set
config.include_subject_window_counts_in_batch=True to surface per-sample window
counts in the collated batch so downstream code can reweight losses.
Examples:
Example 1 β SEM mode, event-level walk:
>>> import dataclasses
>>> cfg = dataclasses.replace(
... sample_dataset_config,
... max_seq_len=3,
... seq_sampling_strategy="step_through",
... step_through_stride=2,
... batch_mode="SEM",
... static_inclusion_mode="omit",
... include_subject_window_counts_in_batch=True,
... )
>>> pyd = MEDSPytorchDataset(cfg, split="train")
The four subjects in the fixture have event counts of 6, 8, 3, and 3. With
max_seq_len=3, step_through_stride=2, self.index has one entry per window β
each entry’s end is the window’s final event. self.step_through_meas_ends
stays None in SEM mode because the sampler’s TO_END semantics handle the
window end natively via event-level slicing.
>>> pyd.index
[(239684, 3), (239684, 5), (239684, 6), (1195293, 3), (1195293, 5), (1195293, 7),
(1195293, 8), (68729, 3), (814703, 3)]
>>> pyd.step_through_meas_ends is None
True
>>> pyd._windows_per_subject
{239684: 3, 1195293: 4, 68729: 1, 814703: 1}
Per-sample output is the window and carries the per-subject window count when
the config flag is set. Sample 0 is subject 239684’s first window β three events
starting at event 0 (note that the subject’s static event has been prepended
into the code vocabulary as event 5 during preprocessing):
>>> sample = pyd[0]
>>> sample["n_subject_windows"]
3
>>> sample["dynamic"].to_dense()["code"]
array([[ 5, 0, 0],
[ 1, 10, 11],
[10, 11, 0]])
Collated batches surface n_subject_windows as a [batch_size] tensor β use
1 / n_subject_windows as a per-sample loss weight to undo oversampling:
Example 2 β SM mode, measurement-level walk that crosses event boundaries:
SM mode interprets max_seq_len and stride as measurements, not events.
With max_seq_len=5, step_through_stride=3, subject 239684 (which has 6 events
flattening to a total of 11 measurements) produces three windows, each exactly
5 measurements wide: the first ends at measurement 5, the second at 8, the
third at the tail (11). The index stores the smallest event index whose prefix
contains each measurement-level end (used by load_subject_data), and
self.step_through_meas_ends stores the actual measurement-level ends that get
passed through process_dynamic_data.explicit_end at sample time:
>>> sm_cfg = dataclasses.replace(
... sample_dataset_config,
... max_seq_len=5,
... seq_sampling_strategy="step_through",
... step_through_stride=3,
... batch_mode="SM",
... static_inclusion_mode="omit",
... )
>>> sm_pyd = MEDSPytorchDataset(sm_cfg, split="train")
>>> [entry for entry in sm_pyd.index if entry[0] == 239684]
[(239684, 3), (239684, 4), (239684, 6)]
>>> [
... meas_end for (subj, _), meas_end in
... zip(sm_pyd.index, sm_pyd.step_through_meas_ends, strict=True)
... if subj == 239684
... ]
[5, 8, 11]
The critical Design B property β the second window (measurement end 8) begins in the middle of event 2 (events [0:1] contain 1+1=2 measurements, event 2 begins at measurement position 2 and contains 3 measurements, so measurement 3 is inside event 2). The window is exactly 5 measurements wide regardless of where event boundaries fall:
>>> sm_pyd[1]["dynamic"].to_dense()["code"]
array([11, 10, 11, 10, 11])
>>> len(sm_pyd[1]["dynamic"])
5
And the third window (measurement end 11) is the subject’s tail β also exactly 5 measurements wide:
>>> sm_pyd[2]["dynamic"].to_dense()["code"]
array([10, 11, 10, 11, 4])
>>> len(sm_pyd[2]["dynamic"])
5
Source code in meds_torchdata/pytorch_dataset.py
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 | |
_resolve_step_through_stride_for(subject_id, effective_window)
Return the step-through stride (same unit as max_seq_len) for a given subject.
When config.step_through_stride is set directly, that value is used as-is. When
config.step_through_overlap is set instead, the stride is computed relative to the
per-subject effective window so that consecutive windows share exactly the requested
overlap regardless of how PREPEND shrinks the window for that subject.
Examples:
>>> import dataclasses
>>> stride_cfg = dataclasses.replace(
... sample_dataset_config,
... max_seq_len=3,
... seq_sampling_strategy="step_through",
... step_through_stride=2,
... batch_mode="SEM",
... static_inclusion_mode="omit",
... )
>>> stride_pyd = MEDSPytorchDataset(stride_cfg, split="train")
>>> stride_pyd._resolve_step_through_stride_for(239684, effective_window=3)
2
With step_through_overlap the stride varies per subject to honor the
requested overlap count relative to that subject’s effective window:
>>> overlap_cfg = dataclasses.replace(stride_cfg, step_through_stride=None,
... step_through_overlap=1)
>>> overlap_pyd = MEDSPytorchDataset(overlap_cfg, split="train")
>>> overlap_pyd._resolve_step_through_stride_for(239684, effective_window=3)
2
>>> overlap_pyd._resolve_step_through_stride_for(239684, effective_window=5)
4
Source code in meds_torchdata/pytorch_dataset.py
_seeded_getitem(idx, seed=None)
Retrieve a single data point from the dataset with a specified random seed.
This is a wrapper around the core item-retrieval logic that allows for deterministic subsequence sampling via an optional random seed.
Source code in meds_torchdata/pytorch_dataset.py
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 | |
_step_through_ends_sm(subject_id, stride, effective_window)
Return measurement- and event-level window ends for an SM-mode step-through walk.
Walks the measurement-level window ends [effective_window, effective_window+stride,
..., total_meas] using the per-subject measurements_per_event list from the
schema. Each measurement-level end is converted to the smallest event index whose
prefix contains it via np.searchsorted on the cumulative-measurement array β that
becomes the end the loader reads from self.index, while the measurement-level
end is returned separately for self.step_through_meas_ends.
Examples:
Subject 239684 in the sample_dataset_config fixture has 6 events flattening
to 11 measurements with per-event counts [1, 3, 2, 2, 2, 1], so
cum_meas = [0, 1, 4, 6, 8, 10, 11]. With effective_window=5, stride=3, the
walk produces measurement ends [5, 8, 11], each of which maps via
searchsorted(cum_meas, meas_end, side="left") to the smallest event index
whose prefix contains it. Note that window 2 (meas end 8) maps to event 4
because cum_meas[4] == 8 exactly, while window 1 (meas end 5) maps to event
3 because cum_meas[2] = 4 < 5 <= cum_meas[3] = 6:
>>> import dataclasses
>>> sm_cfg = dataclasses.replace(
... sample_dataset_config,
... max_seq_len=5,
... seq_sampling_strategy="step_through",
... step_through_stride=3,
... batch_mode="SM",
... static_inclusion_mode="omit",
... )
>>> sm_pyd = MEDSPytorchDataset(sm_cfg, split="train")
>>> sm_pyd._step_through_ends_sm(239684, stride=3, effective_window=5)
([5, 8, 11], [3, 4, 6])
Short subject (total measurements <= effective_window) β single entry
covering the entire subject:
Source code in meds_torchdata/pytorch_dataset.py
_step_through_event_ends_sem(end_idx, stride, effective_window)
staticmethod
Return the list of event-level window ends for a SEM-mode step-through walk.
The first window ends at effective_window (so it contains effective_window
events); subsequent windows each shift forward by stride events; the final window
is anchored to end_idx so the last event is always covered regardless of stride.
Examples:
Typical overlapping walk: end_idx=8, stride=2, effective_window=3 produces
windows ending at events [3, 5, 7, 8] β the last one is tail-anchored to
end_idx so the final event is always covered:
Contiguous (stride == effective_window) walk:
Short subject (end_idx <= effective_window) β single window covering everything:
>>> MEDSPytorchDataset._step_through_event_ends_sem(3, stride=2, effective_window=3)
[3]
>>> MEDSPytorchDataset._step_through_event_ends_sem(2, stride=2, effective_window=3)
[2]
Stride-divides-gap β no duplicate tail anchor:
Source code in meds_torchdata/pytorch_dataset.py
collate(batch)
Combines a batch of data points into a single, tensorized batch.
The collated output is a fully tensorized and padded dictionary, ready for input into an
input_encoder. This method uses the JointNestedRaggedTensorDict API to collate and pad the data.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch
|
list[dict]
|
A list of dictionaries, each representing a single sample as returned by the getitem method. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
MEDSTorchBatch |
MEDSTorchBatch
|
A simple, dictionary-like object containing the collated batch data. See the |
MEDSTorchBatch
|
method documentation for more information. |
Examples:
>>> raw_batch = [sample_pytorch_dataset[2], sample_pytorch_dataset[3]]
>>> print(sample_pytorch_dataset.collate(raw_batch))
MEDSTorchBatch:
β Mode: Subject-Measurement (SM)
β Static data? β
β Labels? β
β
β Shape:
β β Batch size: 2
β β Sequence length: 5
β β
β β All dynamic data: (2, 5)
β β Static data: (2, 2)
β
β Data:
β β Dynamic:
β β β time_delta_days (torch.float32):
β β β β [[0.00e+00, 1.18e+04, ..., 0.00e+00, 9.79e-02],
β β β β [0.00e+00, 1.24e+04, ..., 0.00e+00, 4.64e-02]]
β β β code (torch.int64):
β β β β [[ 5, 3, ..., 11, 4],
β β β β [ 5, 2, ..., 11, 4]]
β β β numeric_value (torch.float32):
β β β β [[ 0.00, 0.00, ..., -0.34, 0.00],
β β β β [ 0.00, 0.00, ..., 0.85, 0.00]]
β β β numeric_value_mask (torch.bool):
β β β β [[False, False, ..., True, False],
β β β β [False, False, ..., True, False]]
β β
β β Static:
β β β static_code (torch.int64):
β β β β [[8, 9],
β β β β [8, 9]]
β β β static_numeric_value (torch.float32):
β β β β [[ 0.00, -0.54],
β β β β [ 0.00, -1.10]]
β β β static_numeric_value_mask (torch.bool):
β β β β [[False, True],
β β β β [False, True]]
>>> raw_batch = [sample_pytorch_dataset_with_task[0], sample_pytorch_dataset_with_task[1]]
>>> print(sample_pytorch_dataset_with_task.collate(raw_batch))
MEDSTorchBatch:
β Mode: Subject-Measurement (SM)
β Static data? β
β Labels? β
β
β Shape:
β β Batch size: 2
β β Sequence length: 8
β β
β β All dynamic data: (2, 8)
β β Static data: (2, 2)
β β Labels: torch.Size([2])
β
β Data:
β β Dynamic:
β β β time_delta_days (torch.float32):
β β β β [[0.00e+00, 1.07e+04, ..., 0.00e+00, 0.00e+00],
β β β β [0.00e+00, 1.07e+04, ..., 2.55e-02, 0.00e+00]]
β β β code (torch.int64):
β β β β [[ 5, 1, ..., 0, 0],
β β β β [ 5, 1, ..., 10, 11]]
β β β numeric_value (torch.float32):
β β β β [[ 0.00e+00, 0.00e+00, ..., 0.00e+00, 0.00e+00],
β β β β [ 0.00e+00, 0.00e+00, ..., 1.32e-03, -1.37e+00]]
β β β numeric_value_mask (torch.bool):
β β β β [[False, False, ..., True, True],
β β β β [False, False, ..., True, True]]
β β
β β Static:
β β β static_code (torch.int64):
β β β β [[7, 9],
β β β β [7, 9]]
β β β static_numeric_value (torch.float32):
β β β β [[0.00, 1.58],
β β β β [0.00, 1.58]]
β β β static_numeric_value_mask (torch.bool):
β β β β [[False, True],
β β β β [False, True]]
β β
β β Labels:
β β β boolean_value (torch.bool):
β β β β [False, True]
You can also change the padding side. This defaults to “right” (which is typical for modeling) but
you can set it to “left” for generative use cases. To show this, we’ll also set the sampling
strategy to SubsequenceSamplingStrategy.TO_END so that things are consistent.
>>> import dataclasses
>>> from meds_torchdata.types import SubsequenceSamplingStrategy
>>> sample_pytorch_dataset = MEDSPytorchDataset(
... dataclasses.replace(
... sample_pytorch_dataset.config,
... padding_side="left",
... seq_sampling_strategy=SubsequenceSamplingStrategy.TO_END,
... ),
... split="train",
... )
>>> raw_batch = [sample_pytorch_dataset[i] for i in range(len(sample_pytorch_dataset))]
>>> print(sample_pytorch_dataset.collate(raw_batch))
MEDSTorchBatch:
β Mode: Subject-Measurement (SM)
β Static data? β
β Labels? β
β
β Shape:
β β Batch size: 4
β β Sequence length: 10
β β
β β All dynamic data: (4, 10)
β β Static data: (4, 2)
β
β Data:
β β Dynamic:
β β β time_delta_days (torch.float32):
β β β β [[1.07e+04, 0.00e+00, ..., 0.00e+00, 2.08e-02],
β β β β [0.00e+00, 1.37e-02, ..., 0.00e+00, 5.91e-03],
β β β β [0.00e+00, 0.00e+00, ..., 0.00e+00, 9.79e-02],
β β β β [0.00e+00, 0.00e+00, ..., 0.00e+00, 4.64e-02]]
β β β code (torch.int64):
β β β β [[ 1, 10, ..., 11, 4],
β β β β [11, 10, ..., 11, 4],
β β β β [ 0, 0, ..., 11, 4],
β β β β [ 0, 0, ..., 11, 4]]
β β β numeric_value (torch.float32):
β β β β [[ 0.00, -0.57, ..., -1.53, 0.00],
β β β β [ 0.80, 0.34, ..., 1.00, 0.00],
β β β β [ 0.00, 0.00, ..., -0.34, 0.00],
β β β β [ 0.00, 0.00, ..., 0.85, 0.00]]
β β β numeric_value_mask (torch.bool):
β β β β [[False, True, ..., True, False],
β β β β [ True, True, ..., True, False],
β β β β [ True, True, ..., True, False],
β β β β [ True, True, ..., True, False]]
β β
β β Static:
β β β static_code (torch.int64):
β β β β [[7, 9],
β β β β [6, 9],
β β β β [8, 9],
β β β β [8, 9]]
β β β static_numeric_value (torch.float32):
β β β β [[ 0.00, 1.58],
β β β β [ 0.00, 0.07],
β β β β [ 0.00, -0.54],
β β β β [ 0.00, -1.10]]
β β β static_numeric_value_mask (torch.bool):
β β β β [[False, True],
β β β β [False, True],
β β β β [False, True],
β β β β [False, True]]
>>> sample_pytorch_dataset = MEDSPytorchDataset(
... dataclasses.replace(sample_pytorch_dataset.config, padding_side="right"),
... split="train",
... )
>>> raw_batch = [sample_pytorch_dataset[i] for i in range(len(sample_pytorch_dataset))]
>>> print(sample_pytorch_dataset.collate(raw_batch))
MEDSTorchBatch:
β Mode: Subject-Measurement (SM)
β Static data? β
β Labels? β
β
β Shape:
β β Batch size: 4
β β Sequence length: 10
β β
β β All dynamic data: (4, 10)
β β Static data: (4, 2)
β
β Data:
β β Dynamic:
β β β time_delta_days (torch.float32):
β β β β [[1.07e+04, 0.00e+00, ..., 0.00e+00, 2.08e-02],
β β β β [0.00e+00, 1.37e-02, ..., 0.00e+00, 5.91e-03],
β β β β [0.00e+00, 1.18e+04, ..., 0.00e+00, 0.00e+00],
β β β β [0.00e+00, 1.24e+04, ..., 0.00e+00, 0.00e+00]]
β β β code (torch.int64):
β β β β [[ 1, 10, ..., 11, 4],
β β β β [11, 10, ..., 11, 4],
β β β β [ 5, 3, ..., 0, 0],
β β β β [ 5, 2, ..., 0, 0]]
β β β numeric_value (torch.float32):
β β β β [[ 0.00, -0.57, ..., -1.53, 0.00],
β β β β [ 0.80, 0.34, ..., 1.00, 0.00],
β β β β [ 0.00, 0.00, ..., 0.00, 0.00],
β β β β [ 0.00, 0.00, ..., 0.00, 0.00]]
β β β numeric_value_mask (torch.bool):
β β β β [[False, True, ..., True, False],
β β β β [ True, True, ..., True, False],
β β β β [False, False, ..., True, True],
β β β β [False, False, ..., True, True]]
β β
β β Static:
β β β static_code (torch.int64):
β β β β [[7, 9],
β β β β [6, 9],
β β β β [8, 9],
β β β β [8, 9]]
β β β static_numeric_value (torch.float32):
β β β β [[ 0.00, 1.58],
β β β β [ 0.00, 0.07],
β β β β [ 0.00, -0.54],
β β β β [ 0.00, -1.10]]
β β β static_numeric_value_mask (torch.bool):
β β β β [[False, True],
β β β β [False, True],
β β β β [False, True],
β β β β [False, True]]
Static data can also be omitted if set in the config.
>>> sample_pytorch_dataset = MEDSPytorchDataset(
... dataclasses.replace(
... sample_pytorch_dataset.config,
... static_inclusion_mode=StaticInclusionMode.OMIT,
... seq_sampling_strategy=SubsequenceSamplingStrategy.RANDOM,
... ),
... split="train",
... )
>>> raw_batch = [sample_pytorch_dataset[2], sample_pytorch_dataset[3]]
>>> print(sample_pytorch_dataset.collate(raw_batch))
MEDSTorchBatch:
β Mode: Subject-Measurement (SM)
β Static data? β
β Labels? β
β
β Shape:
β β Batch size: 2
β β Sequence length: 5
β β
β β All dynamic data: (2, 5)
β
β Data:
β β Dynamic:
β β β time_delta_days (torch.float32):
β β β β [[0.00e+00, 1.18e+04, ..., 0.00e+00, 9.79e-02],
β β β β [0.00e+00, 1.24e+04, ..., 0.00e+00, 4.64e-02]]
β β β code (torch.int64):
β β β β [[ 5, 3, ..., 11, 4],
β β β β [ 5, 2, ..., 11, 4]]
β β β numeric_value (torch.float32):
β β β β [[ 0.00, 0.00, ..., -0.34, 0.00],
β β β β [ 0.00, 0.00, ..., 0.85, 0.00]]
β β β numeric_value_mask (torch.bool):
β β β β [[False, False, ..., True, False],
β β β β [False, False, ..., True, False]]
Static data can also be prepended to the dynamic data.
>>> sample_pytorch_dataset = MEDSPytorchDataset(
... dataclasses.replace(
... sample_pytorch_dataset.config,
... static_inclusion_mode=StaticInclusionMode.PREPEND,
... seq_sampling_strategy=SubsequenceSamplingStrategy.TO_END,
... ),
... split="train",
... )
>>> raw_batch = [sample_pytorch_dataset[2], sample_pytorch_dataset[3]]
>>> print(sample_pytorch_dataset.collate(raw_batch))
MEDSTorchBatch:
β Mode: Subject-Measurement (SM)
β Static data? β (prepended)
β Labels? β
β
β Shape:
β β Batch size: 2
β β Sequence length (static + dynamic): 7
β β
β β All [static; dynamic] data: (2, 7)
β
β Data:
β β [Static; Dynamic]:
β β β time_delta_days (torch.float32):
β β β β [[0.00, 0.00, ..., 0.00, 0.10],
β β β β [0.00, 0.00, ..., 0.00, 0.05]]
β β β code (torch.int64):
β β β β [[ 8, 9, ..., 11, 4],
β β β β [ 8, 9, ..., 11, 4]]
β β β numeric_value (torch.float32):
β β β β [[ 0.00, -0.54, ..., -0.34, 0.00],
β β β β [ 0.00, -1.10, ..., 0.85, 0.00]]
β β β numeric_value_mask (torch.bool):
β β β β [[False, True, ..., True, False],
β β β β [False, True, ..., True, False]]
β β β static_mask (torch.bool):
β β β β [[ True, True, ..., False, False],
β β β β [ True, True, ..., False, False]]
If the batch mode is SEM, the event mask will also be included and the output shape will differ:
>>> sample_pytorch_dataset = MEDSPytorchDataset(
... dataclasses.replace(
... sample_pytorch_dataset.config,
... batch_mode="SEM",
... static_inclusion_mode=StaticInclusionMode.OMIT,
... ),
... split="train",
... )
>>> raw_batch = [sample_pytorch_dataset[2], sample_pytorch_dataset[3]]
>>> print(sample_pytorch_dataset.collate(raw_batch))
MEDSTorchBatch:
β Mode: Subject-Event-Measurement (SEM)
β Static data? β
β Labels? β
β
β Shape:
β β Batch size: 2
β β Sequence length: 3
β β Event length: 3
β β
β β Per-event data: (2, 3)
β β Per-measurement data: (2, 3, 3)
β
β Data:
β β Event-level:
β β β time_delta_days (torch.float32):
β β β β [[0.00e+00, 1.18e+04, 9.79e-02],
β β β β [0.00e+00, 1.24e+04, 4.64e-02]]
β β β event_mask (torch.bool):
β β β β [[True, True, True],
β β β β [True, True, True]]
β β
β β Measurement-level:
β β β code (torch.int64):
β β β β [[[ 5, 0, 0],
β β β β [ 3, 10, 11],
β β β β [ 4, 0, 0]],
β β β β [[ 5, 0, 0],
β β β β [ 2, 10, 11],
β β β β [ 4, 0, 0]]]
β β β numeric_value (torch.float32):
β β β β [[[ 0.00, 0.00, 0.00],
β β β β [ 0.00, -1.45, -0.34],
β β β β [ 0.00, 0.00, 0.00]],
β β β β [[ 0.00, 0.00, 0.00],
β β β β [ 0.00, 3.00, 0.85],
β β β β [ 0.00, 0.00, 0.00]]]
β β β numeric_value_mask (torch.bool):
β β β β [[[False, True, True],
β β β β [False, True, True],
β β β β [False, True, True]],
β β β β [[False, True, True],
β β β β [False, True, True],
β β β β [False, True, True]]]
Padding side changes work in this mode as well.
>>> sample_pytorch_dataset = MEDSPytorchDataset(
... dataclasses.replace(sample_pytorch_dataset.config, padding_side="left"),
... split="train",
... )
>>> raw_batch = [sample_pytorch_dataset[2], sample_pytorch_dataset[3]]
>>> print(sample_pytorch_dataset.collate(raw_batch))
MEDSTorchBatch:
β Mode: Subject-Event-Measurement (SEM)
β Static data? β
β Labels? β
β
β Shape:
β β Batch size: 2
β β Sequence length: 3
β β Event length: 3
β β
β β Per-event data: (2, 3)
β β Per-measurement data: (2, 3, 3)
β
β Data:
β β Event-level:
β β β time_delta_days (torch.float32):
β β β β [[0.00e+00, 1.18e+04, 9.79e-02],
β β β β [0.00e+00, 1.24e+04, 4.64e-02]]
β β β event_mask (torch.bool):
β β β β [[True, True, True],
β β β β [True, True, True]]
β β
β β Measurement-level:
β β β code (torch.int64):
β β β β [[[ 0, 0, 5],
β β β β [ 3, 10, 11],
β β β β [ 0, 0, 4]],
β β β β [[ 0, 0, 5],
β β β β [ 2, 10, 11],
β β β β [ 0, 0, 4]]]
β β β numeric_value (torch.float32):
β β β β [[[ 0.00, 0.00, 0.00],
β β β β [ 0.00, -1.45, -0.34],
β β β β [ 0.00, 0.00, 0.00]],
β β β β [[ 0.00, 0.00, 0.00],
β β β β [ 0.00, 3.00, 0.85],
β β β β [ 0.00, 0.00, 0.00]]]
β β β numeric_value_mask (torch.bool):
β β β β [[[ True, True, False],
β β β β [False, True, True],
β β β β [ True, True, False]],
β β β β [[ True, True, False],
β β β β [False, True, True],
β β β β [ True, True, False]]]
In this mode, though redundant, the static mask will still be present if static data is prepended
>>> sample_pytorch_dataset = MEDSPytorchDataset(
... dataclasses.replace(
... sample_pytorch_dataset.config,
... batch_mode="SEM",
... padding_side="right",
... static_inclusion_mode=StaticInclusionMode.PREPEND,
... seq_sampling_strategy=SubsequenceSamplingStrategy.TO_END,
... ),
... split="train",
... )
>>> raw_batch = [sample_pytorch_dataset[2], sample_pytorch_dataset[3]]
>>> print(sample_pytorch_dataset.collate(raw_batch))
MEDSTorchBatch:
β Mode: Subject-Event-Measurement (SEM)
β Static data? β (prepended)
β Labels? β
β
β Shape:
β β Batch size: 2
β β Sequence length (static + dynamic): 4
β β Event length: 3
β β
β β Per-event data: (2, 4)
β β Per-measurement data: (2, 4, 3)
β
β Data:
β β Event-level:
β β β time_delta_days (torch.float32):
β β β β [[0.00e+00, 0.00e+00, 1.18e+04, 9.79e-02],
β β β β [0.00e+00, 0.00e+00, 1.24e+04, 4.64e-02]]
β β β event_mask (torch.bool):
β β β β [[True, True, True, True],
β β β β [True, True, True, True]]
β β β static_mask (torch.bool):
β β β β [[ True, False, False, False],
β β β β [ True, False, False, False]]
β β
β β Measurement-level:
β β β code (torch.int64):
β β β β [[[ 8, 9, 0],
β β β β [ 5, 0, 0],
β β β β [ 3, 10, 11],
β β β β [ 4, 0, 0]],
β β β β [[ 8, 9, 0],
β β β β [ 5, 0, 0],
β β β β [ 2, 10, 11],
β β β β [ 4, 0, 0]]]
β β β numeric_value (torch.float32):
β β β β [[[ 0.00, -0.54, 0.00],
β β β β [ 0.00, 0.00, 0.00],
β β β β [ 0.00, -1.45, -0.34],
β β β β [ 0.00, 0.00, 0.00]],
β β β β [[ 0.00, -1.10, 0.00],
β β β β [ 0.00, 0.00, 0.00],
β β β β [ 0.00, 3.00, 0.85],
β β β β [ 0.00, 0.00, 0.00]]]
β β β numeric_value_mask (torch.bool):
β β β β [[[False, True, True],
β β β β [False, True, True],
β β β β [False, True, True],
β β β β [False, True, True]],
β β β β [[False, True, True],
β β β β [False, True, True],
β β β β [False, True, True],
β β β β [False, True, True]]]
Omission-flag coverage: every (include_numeric_value, include_time_delta)
combination, in the trickiest structural context (SM + PREPEND). Keeping the
four cases in one snippet so the setup state is explicit and not borrowed from
earlier doctests.
Baseline β both flags on:
>>> base_cfg = dataclasses.replace(
... sample_pytorch_dataset.config,
... batch_mode="SM",
... padding_side="right",
... static_inclusion_mode=StaticInclusionMode.PREPEND,
... seq_sampling_strategy=SubsequenceSamplingStrategy.TO_END,
... include_numeric_value=True,
... include_time_delta=True,
... )
>>> pyd = MEDSPytorchDataset(base_cfg, split="train")
>>> raw_batch = [pyd[2], pyd[3]]
>>> batch = pyd.collate(raw_batch)
>>> (batch.numeric_value is None, batch.numeric_value_mask is None, batch.time_delta_days is None)
(False, False, False)
include_numeric_value=False β numeric_value and its mask vanish:
>>> pyd = MEDSPytorchDataset(
... dataclasses.replace(base_cfg, include_numeric_value=False), split="train"
... )
>>> raw_batch = [pyd[2], pyd[3]]
>>> batch = pyd.collate(raw_batch)
>>> (batch.numeric_value is None, batch.numeric_value_mask is None, batch.time_delta_days is None)
(True, True, False)
include_time_delta=False β the SM+PREPEND regression case. The static-mask
sizing used to read its sequence-length axis from time_delta_days, which
silently disappears when that flag goes off; the current implementation reads
the axis from code (always present), so the mask still has the right shape.
>>> pyd = MEDSPytorchDataset(
... dataclasses.replace(base_cfg, include_time_delta=False), split="train"
... )
>>> raw_batch = [pyd[2], pyd[3]]
>>> batch = pyd.collate(raw_batch)
>>> (batch.numeric_value is None, batch.time_delta_days is None,
... batch.static_mask.shape == batch.code.shape)
(False, True, True)
Both off together:
>>> pyd = MEDSPytorchDataset(
... dataclasses.replace(base_cfg, include_numeric_value=False, include_time_delta=False),
... split="train",
... )
>>> raw_batch = [pyd[2], pyd[3]]
>>> batch = pyd.collate(raw_batch)
>>> (batch.numeric_value is None, batch.time_delta_days is None,
... batch.static_mask.shape == batch.code.shape)
(True, True, True)
Source code in meds_torchdata/pytorch_dataset.py
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 | |
get_dataloader(**kwargs)
Constructs a PyTorch DataLoader for this dataset using the dataset’s custom collate function.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
Additional arguments to pass to the DataLoader constructor. |
{}
|
Returns:
| Type | Description |
|---|---|
DataLoader
|
torch.utils.data.DataLoader: A DataLoader object for this dataset. |
Examples:
>>> import dataclasses
>>> from meds_torchdata.types import SubsequenceSamplingStrategy
>>> sample_pytorch_dataset = MEDSPytorchDataset(
... dataclasses.replace(
... sample_pytorch_dataset.config,
... static_inclusion_mode=StaticInclusionMode.INCLUDE,
... seq_sampling_strategy=SubsequenceSamplingStrategy.TO_END,
... batch_mode="SM",
... ),
... split="train",
... )
>>> _ = torch.manual_seed(0)
>>> torch.use_deterministic_algorithms(True)
>>> DL = sample_pytorch_dataset.get_dataloader(batch_size=2, shuffle=False)
>>> print(next(iter(DL)))
MEDSTorchBatch:
β Mode: Subject-Measurement (SM)
β Static data? β
β Labels? β
β
β Shape:
β β Batch size: 2
β β Sequence length: 10
β β
β β All dynamic data: (2, 10)
β β Static data: (2, 2)
β
β Data:
β β Dynamic:
β β β time_delta_days (torch.float32):
β β β β [[1.07e+04, 0.00e+00, ..., 0.00e+00, 2.08e-02],
β β β β [0.00e+00, 1.37e-02, ..., 0.00e+00, 5.91e-03]]
β β β code (torch.int64):
β β β β [[ 1, 10, ..., 11, 4],
β β β β [11, 10, ..., 11, 4]]
β β β numeric_value (torch.float32):
β β β β [[ 0.00, -0.57, ..., -1.53, 0.00],
β β β β [ 0.80, 0.34, ..., 1.00, 0.00]]
β β β numeric_value_mask (torch.bool):
β β β β [[False, True, ..., True, False],
β β β β [ True, True, ..., True, False]]
β β
β β Static:
β β β static_code (torch.int64):
β β β β [[7, 9],
β β β β [6, 9]]
β β β static_numeric_value (torch.float32):
β β β β [[0.00, 1.58],
β β β β [0.00, 0.07]]
β β β static_numeric_value_mask (torch.bool):
β β β β [[False, True],
β β β β [False, True]]
Source code in meds_torchdata/pytorch_dataset.py
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 | |
get_task_seq_bounds_and_labels(label_df, schema_df)
classmethod
Returns the event-level allowed input sequence boundaries and labels for each task sample.
The output preserves the input-order of label_df for rows that survive. Rows whose
subject_id is absent from schema_df are dropped (inner-join semantics); this
matches the long-standing behavior of the function and is relied on by downstream
callers that pre-filter labels to a shard’s subject set.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
label_df
|
DataFrame
|
The DataFrame containing the task labels, in the MEDS Label DF schema. |
required |
schema_df
|
DataFrame
|
A DataFrame with subject ID and a list of event timestamps for each shard. |
required |
Returns:
| Type | Description |
|---|---|
DataFrame
|
A copy of the labels DataFrame, restricted to included subjects, with the appropriate end indices |
DataFrame
|
for each task sample. Labels will be present if the |
Examples:
>>> label_df = pl.DataFrame({
... "subject_id": [1, 2, 2, 4, 3, 3, 3],
... "prediction_time": [
... datetime(2020, 1, 1),
... datetime(2020, 1, 1), datetime(2020, 1, 2),
... datetime(2020, 1, 1),
... datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3),
... ],
... "boolean_value": [True, False, True, False, True, False, True],
... })
>>> schema_df = pl.DataFrame({
... "subject_id": [2, 6, 1, 3],
... "time": [
... # Subject 2: Prediction times are 2020-1-1,2020-1-2
... [
... datetime(2019, 12, 31),
... datetime(2019, 12, 31, 12),
... datetime(2019, 12, 31, 23, 59, 59),
... datetime(2020, 1, 1, 0, 0, 1),
... datetime(2020, 1, 2),
... datetime(2020, 1, 20),
... ],
... # Subject 6: No prediction times
... [datetime(2020, 1, 1), datetime(2020, 1, 2), datetime(2020, 1, 3)],
... # Subject 1: Prediction times are 2020-1-1
... [datetime(2019, 12, 1), datetime(2020, 1, 1), datetime(2020, 1, 2)],
... # Subject 3: Prediction times are 2020-1-1,2020-1-2,2020-1-3
... [datetime(2020, 1, 1), datetime(2021, 11, 2), datetime(2021, 11, 3)],
... ],
... })
>>> MEDSPytorchDataset.get_task_seq_bounds_and_labels(label_df, schema_df)
shape: (6, 4)
ββββββββββββββ¬ββββββββββββββββββ¬ββββββββββββββββββββββ¬ββββββββββββββββ
β subject_id β end_event_index β prediction_time β boolean_value β
β --- β --- β --- β --- β
β i64 β u32 β datetime[ΞΌs] β bool β
ββββββββββββββͺββββββββββββββββββͺββββββββββββββββββββββͺββββββββββββββββ‘
β 1 β 2 β 2020-01-01 00:00:00 β true β
β 2 β 3 β 2020-01-01 00:00:00 β false β
β 2 β 5 β 2020-01-02 00:00:00 β true β
β 3 β 1 β 2020-01-01 00:00:00 β true β
β 3 β 1 β 2020-01-02 00:00:00 β false β
β 3 β 1 β 2020-01-03 00:00:00 β true β
ββββββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββββββββ΄ββββββββββββββββ
>>> MEDSPytorchDataset.get_task_seq_bounds_and_labels(label_df.drop("boolean_value"), schema_df)
shape: (6, 3)
ββββββββββββββ¬ββββββββββββββββββ¬ββββββββββββββββββββββ
β subject_id β end_event_index β prediction_time β
β --- β --- β --- β
β i64 β u32 β datetime[ΞΌs] β
ββββββββββββββͺββββββββββββββββββͺββββββββββββββββββββββ‘
β 1 β 2 β 2020-01-01 00:00:00 β
β 2 β 3 β 2020-01-01 00:00:00 β
β 2 β 5 β 2020-01-02 00:00:00 β
β 3 β 1 β 2020-01-01 00:00:00 β
β 3 β 1 β 2020-01-02 00:00:00 β
β 3 β 1 β 2020-01-03 00:00:00 β
ββββββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββββββββ
Prediction times strictly before a subject’s first event collapse to end_idx = 0
β there are no events in the allowed input window. (A prediction time equal to
the first event’s time includes that event and yields end_idx = 1, since the
count is over events with time <= prediction_time.)
>>> early_labels = pl.DataFrame({
... "subject_id": [1, 3],
... "prediction_time": [datetime(2019, 1, 1), datetime(2019, 1, 1)],
... "boolean_value": [True, False],
... })
>>> MEDSPytorchDataset.get_task_seq_bounds_and_labels(early_labels, schema_df)
shape: (2, 4)
ββββββββββββββ¬ββββββββββββββββββ¬ββββββββββββββββββββββ¬ββββββββββββββββ
β subject_id β end_event_index β prediction_time β boolean_value β
β --- β --- β --- β --- β
β i64 β u32 β datetime[ΞΌs] β bool β
ββββββββββββββͺββββββββββββββββββͺββββββββββββββββββββββͺββββββββββββββββ‘
β 1 β 0 β 2019-01-01 00:00:00 β true β
β 3 β 0 β 2019-01-01 00:00:00 β false β
ββββββββββββββ΄ββββββββββββββββββ΄ββββββββββββββββββββββ΄ββββββββββββββββ
Source code in meds_torchdata/pytorch_dataset.py
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 | |
load_subject_data(subject_id, st, end)
Loads and returns the dynamic data slice for a given subject ID and permissible event range.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subject_id
|
int
|
The ID of the subject to load. |
required |
st
|
int
|
The (integral) index of the first permissible event (meaning unique timestamp) that can be read for this subject’s record. If None, no limit is applied. |
required |
end
|
int
|
The (integral) index of the last permissible event (meaning unique timestamp) that can be read for this subject’s record. If None, no limit is applied. |
required |
Returns:
| Type | Description |
|---|---|
JointNestedRaggedTensorDict
|
The subject’s dynamic data and static data. The static data is returned as a |
StaticData | None
|
named tuple with two fields: |
tuple[JointNestedRaggedTensorDict, StaticData | None]
|
|
tuple[JointNestedRaggedTensorDict, StaticData | None]
|
loaded from disk and the static-data slot is returned as |
Examples:
>>> from nested_ragged_tensors.ragged_numpy import pprint_dense
>>> dynamic_data, static_data = sample_pytorch_dataset.load_subject_data(68729, 0, 3)
>>> static_data.code
[8, 9]
>>> static_data.numeric_value
[nan, -0.5438239574432373]
>>> pprint_dense(dynamic_data.to_dense())
time_delta_days
[ nan 1.17661045e+04 9.78703722e-02]
.
---
.
dim1/mask
[[ True False False]
[ True True True]
[ True False False]]
.
code
[[ 5 0 0]
[ 3 10 11]
[ 4 0 0]]
.
numeric_value
[[ nan 0. 0. ]
[ nan -1.4474752 -0.34049404]
[ nan 0. 0. ]]
To see that these make sense, recall we can check the raw data. Obviously, the data have been normalized and tokenized, so we should not expect exact matches in the numeric values or code strings, but were we to inspect the code vocabularies, they would align:
>>> from meds_testing_helpers.dataset import MEDSDataset
>>> D = MEDSDataset(root_dir=simple_static_MEDS)
>>> raw_data = pl.from_arrow(D.data_shards["train/1"]).filter(pl.col("subject_id") == 68729)
>>> raw_data
shape: (7, 4)
ββββββββββββββ¬ββββββββββββββββββββββ¬βββββββββββββββββββββββ¬ββββββββββββββββ
β subject_id β time β code β numeric_value β
β --- β --- β --- β --- β
β i64 β datetime[ΞΌs] β str β f32 β
ββββββββββββββͺββββββββββββββββββββββͺβββββββββββββββββββββββͺββββββββββββββββ‘
β 68729 β null β EYE_COLOR//HAZEL β null β
β 68729 β null β HEIGHT β 160.395309 β
β 68729 β 1978-03-09 00:00:00 β DOB β null β
β 68729 β 2010-05-26 02:30:56 β ADMISSION//PULMONARY β null β
β 68729 β 2010-05-26 02:30:56 β HR β 86.0 β
β 68729 β 2010-05-26 02:30:56 β TEMP β 97.800003 β
β 68729 β 2010-05-26 04:51:52 β DISCHARGE β null β
ββββββββββββββ΄ββββββββββββββββββββββ΄βββββββββββββββββββββββ΄ββββββββββββββββ
>>> subj_codes = raw_data["code"].unique().to_list()
>>> code_metadata = (
... pl.read_parquet(tensorized_MEDS_dataset / "metadata/codes.parquet")
... .filter(pl.col("code").is_in(subj_codes))
... )
>>> mean_col = (pl.col("values/sum")/pl.col("values/n_occurrences")).alias("values/mean")
>>> std_col = (
... (pl.col("values/sum_sqd")/pl.col("values/n_occurrences") - mean_col**2)**0.5
... ).alias("values/std")
>>> code_metadata.select(
... "code", "code/vocab_index", mean_col, std_col
... ).sort("code/vocab_index")
shape: (7, 4)
ββββββββββββββββββββββββ¬βββββββββββββββββββ¬ββββββββββββββ¬βββββββββββββ
β code β code/vocab_index β values/mean β values/std β
β --- β --- β --- β --- β
β str β u8 β f32 β f32 β
ββββββββββββββββββββββββͺβββββββββββββββββββͺββββββββββββββͺβββββββββββββ‘
β ADMISSION//PULMONARY β 3 β NaN β NaN β
β DISCHARGE β 4 β NaN β NaN β
β DOB β 5 β NaN β NaN β
β EYE_COLOR//HAZEL β 8 β NaN β NaN β
β HEIGHT β 9 β 164.209732 β 7.014076 β
β HR β 10 β 113.375 β 18.912241 β
β TEMP β 11 β 98.458336 β 1.933464 β
ββββββββββββββββββββββββ΄βββββββββββββββββββ΄ββββββββββββββ΄βββββββββββββ
Note this is independent of the task data and the index; this only depends on the raw data on disk. So, we’ll see the exact same output if we call over the sample dataset with tasks because the raw MEDS data is the same.
>>> dynamic_data, static_data = sample_pytorch_dataset_with_task.load_subject_data(68729, 0, 3)
>>> static_data.code
[8, 9]
>>> static_data.numeric_value
[nan, -0.5438239574432373]
>>> pprint_dense(dynamic_data.to_dense())
time_delta_days
[ nan 1.17661045e+04 9.78703722e-02]
.
---
.
dim1/mask
[[ True False False]
[ True True True]
[ True False False]]
.
code
[[ 5 0 0]
[ 3 10 11]
[ 4 0 0]]
.
numeric_value
[[ nan 0. 0. ]
[ nan -1.4474752 -0.34049404]
[ nan 0. 0. ]]
In StaticInclusionMode.OMIT the static slot is returned as None rather than an
empty StaticData β the static columns are never loaded from disk in that mode, so
there is genuinely nothing to surface. sample_pytorch_dataset.config is locked
(see MEDSTorchDataConfig.lock()), so swap in a modified config by deriving a new
one with dataclasses.replace and constructing a fresh dataset:
>>> import dataclasses
>>> omit_cfg = dataclasses.replace(
... sample_pytorch_dataset.config, static_inclusion_mode=StaticInclusionMode.OMIT
... )
>>> omit_pyd = MEDSPytorchDataset(omit_cfg, split="train")
>>> _, static_data = omit_pyd.load_subject_data(68729, 0, 3)
>>> static_data is None
True
The JNRT handle is cached per (shard, frozenset(load_keys)) on the dataset
instance, so repeated calls that hit the same shard reuse one handle rather
than rebuilding the safetensors wrapper each time:
>>> cfg = MEDSTorchDataConfig(tensorized_cohort_dir=tensorized_MEDS_dataset, max_seq_len=5)
>>> fresh = MEDSPytorchDataset(cfg, split="train")
>>> fresh._jnrt_cache
{}
>>> _ = fresh.load_subject_data(239684, 0, 3)
>>> len(fresh._jnrt_cache)
1
>>> _ = fresh.load_subject_data(239684, 0, 3) # same shard, cache reused
>>> len(fresh._jnrt_cache)
1
Pickling the dataset (as DataLoader(num_workers>0) does when spawning workers)
drops the cache so each worker rebuilds its own handles β safetensors file
handles don’t round-trip cleanly through pickle and would break otherwise:
>>> import pickle
>>> roundtripped = pickle.loads(pickle.dumps(fresh))
>>> roundtripped._jnrt_cache
{}
>>> _ = roundtripped.load_subject_data(239684, 0, 3)
>>> len(roundtripped._jnrt_cache)
1
Source code in meds_torchdata/pytorch_dataset.py
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 | |