config
Contains configuration objects for building a PyTorch dataset from a MEDS dataset.
This module contains configuration objects for building a PyTorch dataset from a MEDS dataset. These include enumeration objects for categorical options and a general DataClass configuration object for dataset options.
MEDSTorchDataConfig
dataclass
A data class for storing configuration options for building a PyTorch dataset from a MEDS dataset.
Attributes:
| Name | Type | Description |
|---|---|---|
tensorized_cohort_dir |
str
|
Path to the root of a tokenized-and-tensorized MEDS cohort
produced by |
max_seq_len |
int
|
The maximum length (in the batch mode’s natural unit — events in SEM
mode, measurements in SM mode) of sequences yielded from the dataset. Samplers
that produce fixed-width windows will use this as the width; |
seq_sampling_strategy |
SubsequenceSamplingStrategy
|
The subsequence sampling strategy — one of
|
padding_side |
PaddingSide
|
Which side of short sequences to pad when collating into a batch
( |
static_inclusion_mode |
StaticInclusionMode
|
How to surface per-subject static measurements in the
collated batch — |
task_labels_dir |
str | None
|
Optional path to a directory of MEDS Label parquet files. When set,
the dataset yields one sample per (subject, prediction_time) label with the
sampling strategy fixed to |
batch_mode |
BatchMode
|
Whether the collated batch keeps the event/measurement structure
( |
include_window_last_observed_in_schema |
bool
|
When True, the |
step_through_stride |
int | None
|
Absolute number of sequence elements (events in SEM mode,
measurements in SM mode) to advance between consecutive |
step_through_overlap |
int | None
|
Alternative to |
include_subject_window_counts_in_batch |
bool
|
When True, |
include_numeric_value |
bool
|
When False, |
include_time_delta |
bool
|
When False, |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
If the task_labels_dir or the tensorized_cohort_dir is not a valid directory. |
ValueError
|
If the subsequence sampling strategy or static inclusion mode is not valid. |
ValueError
|
If the task_labels_dir is specified but the subsequence sampling strategy is not TO_END. |
ValueError
|
If |
Examples:
>>> import tempfile
>>> with tempfile.TemporaryDirectory() as tmpdir: # No error
... cfg = MEDSTorchDataConfig(
... tensorized_cohort_dir=tmpdir,
... max_seq_len=10,
... )
>>> with tempfile.TemporaryDirectory() as tmpdir:
... cohort_root = Path(tmpdir) / "tensorized"
... cohort_root.mkdir()
... task_labels_dir = Path(tmpdir) / "task_labels"
... task_labels_dir.mkdir()
... cfg = MEDSTorchDataConfig(
... tensorized_cohort_dir=cohort_root,
... max_seq_len=10,
... task_labels_dir=task_labels_dir,
... seq_sampling_strategy="to_end",
... )
If the cohort directory doesn’t exist, an error is raised.
>>> with tempfile.TemporaryDirectory() as tmpdir: # Error as cohort dir doesn't exist
... MEDSTorchDataConfig(
... tensorized_cohort_dir=Path(tmpdir) / "non_existent",
... max_seq_len=10,
... )
Traceback (most recent call last):
...
FileNotFoundError: tensorized_cohort_dir must be a valid directory. Got ...
If the task labels directory doesn’t exist, an error is raised.
>>> with tempfile.TemporaryDirectory() as tmpdir: # Error as task labels dir doesn't exist
... MEDSTorchDataConfig(
... tensorized_cohort_dir=tmpdir,
... max_seq_len=10,
... task_labels_dir=Path(tmpdir) / "non_existent",
... )
Traceback (most recent call last):
...
FileNotFoundError: If specified, task_labels_dir must be a valid directory. Got ...
If the subsequence sampling strategy is not TO_END when a task is specified an error is raised.
>>> with tempfile.TemporaryDirectory() as tmpdir:
... cohort_root = Path(tmpdir) / "tensorized"
... cohort_root.mkdir()
... task_labels_dir = Path(tmpdir) / "task_labels"
... task_labels_dir.mkdir()
... MEDSTorchDataConfig(
... tensorized_cohort_dir=cohort_root,
... max_seq_len=10,
... task_labels_dir=task_labels_dir,
... seq_sampling_strategy="random",
... )
Traceback (most recent call last):
...
ValueError: Not sampling data till the end of the sequence when predicting for a specific task is not
permitted! This is because there is no use-case we know of where you would want to do this. If you
disagree, please let us know via a GitHub issue.
If the subsequence sampling strategy or static inclusion mode is not valid, an error is raised.
>>> MEDSTorchDataConfig(tensorized_cohort_dir=".", max_seq_len=3, seq_sampling_strategy="foobar")
Traceback (most recent call last):
...
ValueError: Invalid subsequence sampling strategy: foobar
>>> MEDSTorchDataConfig(tensorized_cohort_dir=".", max_seq_len=3, static_inclusion_mode="foobar")
Traceback (most recent call last):
...
ValueError: Invalid static inclusion mode: foobar
STEP_THROUGH sampling requires exactly one of step_through_stride (elements to
advance between consecutive windows) or step_through_overlap (elements consecutive
windows should share). Both are in the same unit as max_seq_len — events in SEM
mode, measurements in SM mode. Leaving both unset, or setting both, raises:
>>> MEDSTorchDataConfig(
... tensorized_cohort_dir=".", max_seq_len=3, seq_sampling_strategy="step_through"
... )
Traceback (most recent call last):
...
ValueError: Exactly one of step_through_stride or step_through_overlap must be set when
seq_sampling_strategy is STEP_THROUGH; got step_through_stride=None,
step_through_overlap=None.
>>> MEDSTorchDataConfig(
... tensorized_cohort_dir=".", max_seq_len=3, seq_sampling_strategy="step_through",
... step_through_stride=2, step_through_overlap=1,
... )
Traceback (most recent call last):
...
ValueError: Exactly one of step_through_stride or step_through_overlap must be set when
seq_sampling_strategy is STEP_THROUGH; got step_through_stride=2,
step_through_overlap=1.
step_through_stride must be a positive integer. Zero / negative / non-int values
are rejected, and bool is explicitly rejected because it is a subclass of int
in Python (so isinstance(True, int) would otherwise silently accept it as stride 1):
>>> MEDSTorchDataConfig(
... tensorized_cohort_dir=".", max_seq_len=3, seq_sampling_strategy="step_through",
... step_through_stride=0,
... )
Traceback (most recent call last):
...
ValueError: step_through_stride must be a positive integer when seq_sampling_strategy is
STEP_THROUGH; got 0.
>>> MEDSTorchDataConfig(
... tensorized_cohort_dir=".", max_seq_len=3, seq_sampling_strategy="step_through",
... step_through_stride=True,
... )
Traceback (most recent call last):
...
ValueError: step_through_stride must be a positive integer when seq_sampling_strategy is
STEP_THROUGH; got True.
step_through_overlap must be a non-negative integer (0 = contiguous
non-overlapping windows). bool is again explicitly rejected:
>>> MEDSTorchDataConfig(
... tensorized_cohort_dir=".", max_seq_len=3, seq_sampling_strategy="step_through",
... step_through_overlap=-1,
... )
Traceback (most recent call last):
...
ValueError: step_through_overlap must be a non-negative integer when seq_sampling_strategy
is STEP_THROUGH; got -1.
>>> MEDSTorchDataConfig(
... tensorized_cohort_dir=".", max_seq_len=3, seq_sampling_strategy="step_through",
... step_through_overlap=True,
... )
Traceback (most recent call last):
...
ValueError: step_through_overlap must be a non-negative integer when seq_sampling_strategy
is STEP_THROUGH; got True.
Conversely, setting step_through_stride or step_through_overlap with any other
strategy is also rejected, because the fields have no effect outside STEP_THROUGH and
silently accepting them would mask configuration mistakes:
>>> MEDSTorchDataConfig(
... tensorized_cohort_dir=".", max_seq_len=3, seq_sampling_strategy="random",
... step_through_stride=2,
... )
Traceback (most recent call last):
...
ValueError: step_through_stride may only be set when seq_sampling_strategy is STEP_THROUGH;
got strategy random with stride 2.
>>> MEDSTorchDataConfig(
... tensorized_cohort_dir=".", max_seq_len=3, seq_sampling_strategy="random",
... step_through_overlap=0,
... )
Traceback (most recent call last):
...
ValueError: step_through_overlap may only be set when seq_sampling_strategy is STEP_THROUGH;
got strategy random with overlap 0.
Source code in meds_torchdata/config.py
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 | |
code_metadata_fp
property
includes_static
property
Whether this config surfaces per-subject static data in the produced batches.
True iff static_inclusion_mode is not OMIT. Consolidates the “does this config
need the static_code / static_numeric_value columns?” check so the schema-parquet
column selection at init time and the load_subject_data fast-path cannot drift.
Examples:
>>> with tempfile.TemporaryDirectory() as tmpdir:
... cfg = MEDSTorchDataConfig(Path(tmpdir), max_seq_len=10, static_inclusion_mode="omit")
... print(cfg.includes_static)
False
>>> with tempfile.TemporaryDirectory() as tmpdir:
... cfg = MEDSTorchDataConfig(Path(tmpdir), max_seq_len=10, static_inclusion_mode="include")
... print(cfg.includes_static)
True
>>> with tempfile.TemporaryDirectory() as tmpdir:
... cfg = MEDSTorchDataConfig(Path(tmpdir), max_seq_len=10, static_inclusion_mode="prepend")
... print(cfg.includes_static)
True
schema_dir
property
schema_fps
property
Yield shard names and schema paths for existent schema files.
Examples:
>>> with tempfile.TemporaryDirectory() as tmpdir:
... tensorized_root = Path(tmpdir)
... schema_dir = tensorized_root / "tokenization" / "schemas"
... schema_dir.mkdir(parents=True)
... (schema_dir / "shard_A.parquet").touch()
... (schema_dir / "shard_B.json").touch()
... (schema_dir / "shard_C/").mkdir()
... (schema_dir / "shard_C" / "0.parquet").touch()
... (schema_dir / "shard_C" / "1.parquet").touch()
... (schema_dir / "shard_D/").mkdir()
... cfg = MEDSTorchDataConfig(tensorized_root, max_seq_len=10)
... for shard, fp in cfg.schema_fps:
... print(shard, str(fp.relative_to(tensorized_root)))
shard_A tokenization/schemas/shard_A.parquet
shard_C/0 tokenization/schemas/shard_C/0.parquet
shard_C/1 tokenization/schemas/shard_C/1.parquet
task_labels_fps
property
Returns the list of task label files for this configuration, or None if no task is specified.
Returned files must exist; if no such files exist, will return an empty list.
Examples:
>>> with tempfile.TemporaryDirectory() as tmpdir:
... tensorized_root = Path(tmpdir) / "tensorized"
... tensorized_root.mkdir()
... cfg_no_task = MEDSTorchDataConfig(tensorized_root, 2)
... print(f"No task dir: {cfg_no_task.task_labels_fps}")
... task_labels_dir = Path(tmpdir) / "task_labels"
... task_labels_dir.mkdir()
... (task_labels_dir / "labels_1.parquet").touch()
... (task_labels_dir / "nested").mkdir()
... (task_labels_dir / "nested/labels_2.parquet").touch()
... cfg_task = MEDSTorchDataConfig(
... tensorized_root, 2, task_labels_dir=task_labels_dir, seq_sampling_strategy="to_end"
... )
... print(f"Task dir: {cfg_task.task_labels_fps}")
No task dir: None
Task dir: [PosixPath('/tmp/.../task_labels/labels_1.parquet'),
PosixPath('/tmp/.../task_labels/nested/labels_2.parquet')]
vocab_size
cached
property
Reads the code indices from the metadata file and returns the size of the vocabulary.
The vocabulary size is the maximum index in the code metadata file plus one. This is a cached property to avoid reading the file multiple times.
Examples:
>>> df = pl.DataFrame({"code/vocab_index": [0, 1, 3]})
>>> with tempfile.TemporaryDirectory() as tmpdir:
... tensorized_root = Path(tmpdir)
... metadata_fp = tensorized_root / "metadata" / "codes.parquet"
... metadata_fp.parent.mkdir(parents=True)
... df.write_parquet(metadata_fp)
... cfg = MEDSTorchDataConfig(tensorized_root, max_seq_len=10)
... print(cfg.vocab_size)
4
add_to_config_store(group=None)
classmethod
Adds this class to the Hydra config store such that instantiation will create it natively.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
group
|
str | None
|
The group name to register this class under. |
None
|
Examples:
>>> MEDSTorchDataConfig.add_to_config_store()
>>> cs = ConfigStore.instance()
>>> cs.repo["MEDSTorchDataConfig.yaml"]
ConfigNode(name='MEDSTorchDataConfig.yaml',
node={'tensorized_cohort_dir': '???',
'max_seq_len': '???',
'seq_sampling_strategy': <SubsequenceSamplingStrategy.RANDOM: 'random'>,
'padding_side': <PaddingSide.RIGHT: 'right'>,
'static_inclusion_mode': <StaticInclusionMode.INCLUDE: 'include'>,
'task_labels_dir': None,
'batch_mode': <BatchMode.SM: 'SM'>,
'include_window_last_observed_in_schema': False,
'step_through_stride': None,
'step_through_overlap': None,
'include_subject_window_counts_in_batch': False,
'include_numeric_value': True,
'include_time_delta': True,
'_target_': 'meds_torchdata.config.MEDSTorchDataConfig'},
group=None,
package=None,
provider=None)
With the _target_ key set to the class name, this allows for instantiation of the class via Hydra:
>>> from omegaconf import DictConfig
>>> from hydra import compose, initialize
>>> with initialize(version_base=None, config_path=".", job_name="test"):
... cfg = compose(
... config_name="MEDSTorchDataConfig.yaml",
... overrides=[f"tensorized_cohort_dir={tensorized_MEDS_dataset!s}", "max_seq_len=10"]
... )
>>> cfg
{'tensorized_cohort_dir': '/tmp/tmp...',
'max_seq_len': 10,
'seq_sampling_strategy': <SubsequenceSamplingStrategy.RANDOM: 'random'>,
'padding_side': <PaddingSide.RIGHT: 'right'>,
'static_inclusion_mode': <StaticInclusionMode.INCLUDE: 'include'>,
'task_labels_dir': None,
'batch_mode': <BatchMode.SM: 'SM'>,
'include_window_last_observed_in_schema': False,
'step_through_stride': None,
'step_through_overlap': None,
'include_subject_window_counts_in_batch': False,
'include_numeric_value': True,
'include_time_delta': True,
'_target_': 'meds_torchdata.config.MEDSTorchDataConfig'}
>>> from hydra.utils import instantiate
>>> instantiate(cfg)
MEDSTorchDataConfig(tensorized_cohort_dir=PosixPath('/tmp/tmp...'),
max_seq_len=10,
seq_sampling_strategy=<SubsequenceSamplingStrategy.RANDOM: 'random'>,
padding_side=<PaddingSide.RIGHT: 'right'>,
static_inclusion_mode=<StaticInclusionMode.INCLUDE: 'include'>,
task_labels_dir=None,
batch_mode=<BatchMode.SM: 'SM'>,
include_window_last_observed_in_schema=False,
step_through_stride=None,
step_through_overlap=None,
include_subject_window_counts_in_batch=False,
include_numeric_value=True,
include_time_delta=True)
Note that Hydra’s CLI parameters with structured configs recognize that the StrEnum classes are
enums, but fails to recognize that they accept lowercased names as the names of the class members are
all upper-case. This means that you need to use upper case names for enum variables if you overwrite a
parameter in the CLI for this config once it is added to the config store.
>>> with initialize(version_base=None, config_path=".", job_name="test"):
... cfg = compose(
... config_name="MEDSTorchDataConfig.yaml",
... overrides=[
... f"tensorized_cohort_dir={tensorized_MEDS_dataset!s}",
... "max_seq_len=10",
... "seq_sampling_strategy=to_end",
... ]
... )
Traceback (most recent call last):
...
hydra.errors.ConfigCompositionException: Error merging override seq_sampling_strategy=to_end
>>> with initialize(version_base=None, config_path=".", job_name="test"):
... cfg = compose(
... config_name="MEDSTorchDataConfig.yaml",
... overrides=[
... f"tensorized_cohort_dir={tensorized_MEDS_dataset!s}",
... "max_seq_len=10",
... "seq_sampling_strategy=TO_END",
... ]
... )
>>> instantiate(cfg)
MEDSTorchDataConfig(tensorized_cohort_dir=PosixPath('/tmp/tmp...'),
max_seq_len=10,
seq_sampling_strategy=<SubsequenceSamplingStrategy.TO_END: 'to_end'>,
padding_side=<PaddingSide.RIGHT: 'right'>,
static_inclusion_mode=<StaticInclusionMode.INCLUDE: 'include'>,
task_labels_dir=None,
batch_mode=<BatchMode.SM: 'SM'>,
include_window_last_observed_in_schema=False,
step_through_stride=None,
step_through_overlap=None,
include_subject_window_counts_in_batch=False,
include_numeric_value=True,
include_time_delta=True)
You can also add the config to a group
>>> MEDSTorchDataConfig.add_to_config_store("my_group/my_subgroup")
>>> cs = ConfigStore.instance()
>>> cs.repo["my_group"]["my_subgroup"]["MEDSTorchDataConfig.yaml"]
ConfigNode(name='MEDSTorchDataConfig.yaml',
node={'tensorized_cohort_dir': '???',
'max_seq_len': '???',
'seq_sampling_strategy': <SubsequenceSamplingStrategy.RANDOM: 'random'>,
'padding_side': <PaddingSide.RIGHT: 'right'>,
'static_inclusion_mode': <StaticInclusionMode.INCLUDE: 'include'>,
'task_labels_dir': None,
'batch_mode': <BatchMode.SM: 'SM'>,
'include_window_last_observed_in_schema': False,
'step_through_stride': None,
'step_through_overlap': None,
'include_subject_window_counts_in_batch': False,
'include_numeric_value': True,
'include_time_delta': True,
'_target_': 'meds_torchdata.config.MEDSTorchDataConfig'},
group='my_group/my_subgroup',
package=None,
provider=None)
Source code in meds_torchdata/config.py
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 | |
lock()
Lock this config against further mutation.
Called automatically by MEDSPytorchDataset.__init__ so the dataset can rely on
its config being stable across its lifetime — schema columns loaded, index
construction, JNRT cache keys, worker pickles. Idempotent; locking an already-locked
config is a no-op.
To mutate a locked config, either call unlock() first (with the caveat that the
change will not propagate into an already-attached dataset or its workers) or use
dataclasses.replace(cfg, field=value) to derive a new config.
Examples:
>>> from meds_torchdata import MEDSPytorchDataset, MEDSTorchDataConfig
>>> cfg = MEDSTorchDataConfig(tensorized_cohort_dir=tensorized_MEDS_dataset, max_seq_len=5)
>>> cfg.max_seq_len = 10 # mutable pre-lock
>>> cfg.max_seq_len
10
>>> cfg.lock()
>>> cfg.max_seq_len = 20
Traceback (most recent call last):
...
RuntimeError: Cannot mutate `max_seq_len` on a locked MEDSTorchDataConfig...
MEDSPytorchDataset.__init__ calls lock() on its input, so direct construction
produces the same locked state:
>>> cfg = MEDSTorchDataConfig(tensorized_cohort_dir=tensorized_MEDS_dataset, max_seq_len=5)
>>> pyd = MEDSPytorchDataset(cfg, split="train")
>>> cfg.max_seq_len = 20
Traceback (most recent call last):
...
RuntimeError: Cannot mutate `max_seq_len` on a locked MEDSTorchDataConfig...
The locked state round-trips through pickle — when DataLoader(num_workers>0)
pickles the dataset (and its config) into a worker process, the worker inherits
the lock. No stealthy mutation channel via pickle.
>>> import pickle
>>> restored = pickle.loads(pickle.dumps(cfg))
>>> restored.max_seq_len = 20
Traceback (most recent call last):
...
RuntimeError: Cannot mutate `max_seq_len` on a locked MEDSTorchDataConfig...
If MEDSPytorchDataset.__init__ raises partway through (e.g., the caller asks
for a split that has no schema files), the lock is not applied — the caller is
free to fix up the cfg and retry without unlock()-ing first:
>>> cfg = MEDSTorchDataConfig(tensorized_cohort_dir=tensorized_MEDS_dataset, max_seq_len=5)
>>> try:
... MEDSPytorchDataset(cfg, split="nonexistent_split")
... except FileNotFoundError:
... pass
>>> cfg.max_seq_len = 42 # no error, cfg is still mutable
>>> cfg.max_seq_len
42
The error message differentiates by whether the attempted key is a real
config field. Typos / non-declared attributes get a dedicated message that
doesn’t recommend dataclasses.replace (which would reject the bad key):
>>> cfg = MEDSTorchDataConfig(tensorized_cohort_dir=tensorized_MEDS_dataset, max_seq_len=5)
>>> cfg.lock()
>>> cfg.maks_seq_len = 10
Traceback (most recent call last):
...
RuntimeError: Cannot set `maks_seq_len` on a locked MEDSTorchDataConfig:
`maks_seq_len` is not a declared field...
Source code in meds_torchdata/config.py
process_dynamic_data(data, n_static_seq_els=None, rng=None, explicit_end=None)
This processes the dynamic data for a subject, including subsampling and flattening.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
|
JointNestedRaggedTensorDict
|
The dynamic data for the subject. |
required |
n_static_seq_els
|
int | None
|
The number of static measurements for the given patient. This is only used
if the static inclusion mode is |
None
|
rng
|
Generator | int | None
|
The random seed to use for subsequence sampling. If |
None
|
explicit_end
|
int | None
|
An optional measurement-level end index for the window. When set,
the visible sequence is truncated to |
None
|
Returns:
| Type | Description |
|---|---|
JointNestedRaggedTensorDict
|
The processed dynamic data, still in a |
Examples:
>>> from nested_ragged_tensors.ragged_numpy import pprint_dense
>>> data = JointNestedRaggedTensorDict({
... "time_delta": [1, 2, 3, 4, 5, 6, 7],
... "code": [[10, 11], [20, 21], [30], [40], [50, 51, 52], [60], [70, 71, 72, 73]],
... })
If the config says to sample until the end, we’ll just grab the last three elements.
>>> cfg = MEDSTorchDataConfig(
... ".", max_seq_len=3, seq_sampling_strategy="to_end", batch_mode="SEM"
... )
>>> pprint_dense(cfg.process_dynamic_data(data).to_dense())
time_delta
[5 6 7]
.
---
.
dim1/mask
[[ True True True False]
[ True False False False]
[ True True True True]]
.
code
[[50 51 52 0]
[60 0 0 0]
[70 71 72 73]]
We can also pass the number of sequence elements that should be reserved for static sequence
elements to functionally reduce the effective max sequence length we select among the dynamic
data. This is only used in StaticInclusionMode.PREPEND mode, and is ignored otherwise (without
an error being raised!). Note that the reserved sequence element only affects the first
(sequential) dimension of the nested ragged tensor.
>>> pprint_dense(cfg.process_dynamic_data(data, n_static_seq_els=1).to_dense())
time_delta
[5 6 7]
.
---
.
dim1/mask
[[ True True True False]
[ True False False False]
[ True True True True]]
.
code
[[50 51 52 0]
[60 0 0 0]
[70 71 72 73]]
>>> cfg = MEDSTorchDataConfig(
... ".", max_seq_len=3, seq_sampling_strategy="to_end", batch_mode="SEM",
... static_inclusion_mode="prepend"
... )
>>> pprint_dense(cfg.process_dynamic_data(data, n_static_seq_els=1).to_dense())
time_delta
[6 7]
.
---
.
dim1/mask
[[ True False False False]
[ True True True True]]
.
code
[[60 0 0 0]
[70 71 72 73]]
If we flatten the tensors, then we get only 1D tensors for both, and the time elements that are
added to account for the longer length are imputed to zero. Note we’ve increased the max_seq_len
to 5 to show some non-imputed time-deltas.
>>> cfg = MEDSTorchDataConfig(".", max_seq_len=5, seq_sampling_strategy="to_end")
>>> pprint_dense(cfg.process_dynamic_data(data).to_dense())
code
[60 70 71 72 73]
.
time_delta
[6 7 0 0 0]
>>> cfg = MEDSTorchDataConfig(
... ".", max_seq_len=5, seq_sampling_strategy="to_end",
... static_inclusion_mode="prepend"
... )
>>> pprint_dense(cfg.process_dynamic_data(data, n_static_seq_els=3).to_dense())
code
[72 73]
.
time_delta
[0 0]
If we sample from the start, we’ll just grab the first three elements.
>>> cfg = MEDSTorchDataConfig(
... ".", max_seq_len=3, seq_sampling_strategy="from_start", batch_mode="SEM"
... )
>>> pprint_dense(cfg.process_dynamic_data(data).to_dense())
time_delta
[1 2 3]
.
---
.
dim1/mask
[[ True True]
[ True True]
[ True False]]
.
code
[[10 11]
[20 21]
[30 0]]
Again, if we flatten the tensors, we get only 1D tensors for both.
>>> cfg = MEDSTorchDataConfig(".", max_seq_len=3, seq_sampling_strategy="from_start")
>>> pprint_dense(cfg.process_dynamic_data(data).to_dense())
code
[10 11 20]
.
time_delta
[1 0 2]
Random sampling is non-deterministic, but can be fixed by a seed.
>>> cfg = MEDSTorchDataConfig(".", max_seq_len=3, seq_sampling_strategy="random")
>>> pprint_dense(cfg.process_dynamic_data(data, rng=1).to_dense())
code
[40 50 51]
.
time_delta
[4 5 0]
>>> pprint_dense(cfg.process_dynamic_data(data, rng=1).to_dense())
code
[40 50 51]
.
time_delta
[4 5 0]
>>> pprint_dense(cfg.process_dynamic_data(data, rng=3).to_dense())
code
[60 70 71]
.
time_delta
[6 7 0]
balanced_random lets the sliding window overhang the left or right edge of the
sequence, giving every event a uniform max_seq_len / (seq_len + max_seq_len - 1)
chance of being included. When the window overhangs a boundary, the returned slice
is shorter than max_seq_len — the collator pads to the longest element in the
batch downstream. Here seq_len is 14 (in SM mode the measurement tensor is
flattened first), max_seq_len is 3, so the start offset is drawn uniformly from
{-2, -1, ..., 13}.
>>> cfg = MEDSTorchDataConfig(".", max_seq_len=3, seq_sampling_strategy="balanced_random")
>>> pprint_dense(cfg.process_dynamic_data(data, rng=23).to_dense())
code
[10]
.
time_delta
[1]
>>> pprint_dense(cfg.process_dynamic_data(data, rng=30).to_dense())
code
[10 11]
.
time_delta
[1 0]
>>> pprint_dense(cfg.process_dynamic_data(data, rng=7).to_dense())
code
[73]
.
time_delta
[0]
>>> pprint_dense(cfg.process_dynamic_data(data, rng=9).to_dense())
code
[30 40 50]
.
time_delta
[3 4 5]
If we pass in an invalid number of static sequence elements to reserve, we get an error.
>>> cfg = MEDSTorchDataConfig(
... ".", max_seq_len=3, seq_sampling_strategy="random", static_inclusion_mode="prepend"
... )
>>> cfg.process_dynamic_data(data, n_static_seq_els=0)
Traceback (most recent call last):
...
ValueError: When self.static_inclusion_mode=prepend, n_static_seq_els must be a positive integer.
Got 0
Source code in meds_torchdata/config.py
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 | |
unlock()
Unlock a previously-locked config.
Emits a UserWarning when called on a currently-locked config — the typical
source of the lock is a MEDSPytorchDataset that has already captured the config’s
state, so post-unlock mutations will not propagate into that dataset’s
main-process view or its worker-process copies (which live on separate cfg
snapshots under persistent_workers=True, the default when num_workers > 0).
Users who explicitly want the escape hatch get it; they get a loud pointer at the
idiomatic alternative (dataclasses.replace + fresh MEDSPytorchDataset) too.
Which fields can be mutated safely after unlock? None of them in a
num_workers > 0 DataLoader — workers pickle their own snapshot at spawn and
never see main-process mutations. In a single-process setting (num_workers=0,
direct dataset[i] access), the fields read fresh per hot-path call — and thus
safe to flip — are padding_side, include_numeric_value, include_time_delta,
include_subject_window_counts_in_batch, and max_seq_len when
seq_sampling_strategy != STEP_THROUGH. Every other field (sampling strategy,
batch mode, static mode, task labels dir, step-through params, window-last-observed,
tensorized cohort dir) is baked into dataset init state and flipping it
post-handoff leaves the dataset in an inconsistent state. For those, use
dataclasses.replace(cfg, field=value) + construct a fresh dataset instead.
Examples:
>>> import warnings
>>> cfg = MEDSTorchDataConfig(tensorized_cohort_dir=tensorized_MEDS_dataset, max_seq_len=5)
>>> cfg.lock()
>>> with warnings.catch_warnings(record=True) as caught:
... warnings.simplefilter("always")
... cfg.unlock()
... print(len(caught), caught[0].category.__name__)
1 UserWarning
>>> cfg.max_seq_len = 99 # mutable again
>>> cfg.max_seq_len
99
Calling unlock() on an already-unlocked config is a silent no-op:
>>> with warnings.catch_warnings(record=True) as caught:
... warnings.simplefilter("always")
... cfg.unlock()
... print(len(caught))
0