eic_forecasting
DummyModel
Dummy model that generates two fixed sequences.
Source code in meds_torch/models/eic_forecasting.py
EicForecastingModule
Bases: BaseModule, TimeableMixin, BaseGenerativeModel
EIC token based GPT Forecasting Model.
This model has three main capabilities: 1. Autoregressive training (learning to predict next tokens) 2. Data generation (creating synthetic medical event sequences) 3. Zero-shot prediction (using generated sequences for prediction)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg |
DictConfig
|
Configuration object containing: - vocab_size: Size of the vocabulary - max_seq_len: Maximum sequence length - zero_shot_labeler: Optional function for zero-shot prediction - code_metadata_fp: Path to code metadata file |
required |
Examples:
>>> import tempfile
>>> from clinical_zeroshot_labeler.labeler import WindowStatus
>>> # Create test setup using helper function
>>> trajectory_labeler, metadata_df, batch, _ = create_dummy_sequence_labeler()
>>> # Write metadata to temporary file and create config
>>> temp_file = tempfile.NamedTemporaryFile(suffix='.parquet')
>>> metadata_df.write_parquet(temp_file.name)
>>> cfg = create_model_config(temp_file.name)
>>> # Test workflow 1: Autoregressive training
>>> model = EicForecastingModule(cfg)
>>> loss = model.training_step(batch)
>>> assert loss.isfinite().all()
>>> # Test workflow 2: Data generation without labeling
>>> cfg.generate_id = 1
>>> model = EicForecastingModule(cfg)
>>> output = model.forward(batch)
>>> assert GENERATE_PREFIX + '1' in output
>>> generated_df = output[GENERATE_PREFIX + '1']
>>> # Check generated data structure
>>> assert 'time' in generated_df.columns
>>> assert 'code' in generated_df.columns
>>> assert 'numeric_value' in generated_df.columns
>>> assert 'subject_id' in generated_df.columns
>>> assert 'prediction_time' in generated_df.columns
>>> # Verify time token generation (code/vocab_index 4 in metadata)
>>> generated_df.shape[0]
20
>>> # Test workflow 3: Generation with zero-shot labeling
>>> cfg.generate_id = 1
>>> model = EicForecastingModule(cfg)
>>> model.trajectory_labeler = trajectory_labeler
>>> output = model.forward(batch)
>>> # Check labeling output
>>> assert MODEL_PRED_PROBA_KEY in output
>>> assert MODEL_PRED_STATUS_KEY in output
>>> assert output[MODEL_PRED_PROBA_KEY].shape == (2,) # Binary prediction per sequence
>>> assert output[MODEL_PRED_STATUS_KEY].shape == (2,) # Status per sequence
>>> # Verify status progression works
>>> status_vals = output[MODEL_PRED_STATUS_KEY]
>>> assert (status_vals == WindowStatus.SATISFIED.value).any(), status_vals # Some sequences complete
Source code in meds_torch/models/eic_forecasting.py
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 | |
generate_batch(input_batch, **kwargs)
Generate evaluation metrics for the model.
Source code in meds_torch/models/eic_forecasting.py
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 | |
get_code_to_numeric_value_map(metadata_df, get_raw_values=True)
classmethod
Convert the metadata DataFrame to a dictionary mapping code to numeric value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata_df |
Polars DataFrame containing code metadata (includes ‘code’ and ‘code/vocab_index’ columns) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Mapping code to time in years |
Example:
metadata_df = pl.DataFrame({ … “code”: [“A”, “A//_Q_1”, “A//_Q_2”, “A//_Q_3”, “A//_Q_4”, “B”], … “code/vocab_index”: [0, 1, 2, 3, 4, 5], … ‘values/min’: [0, 0, 0, 0, 0, None], … ‘values/max’: [4, 4, 4, 4, 4, None], … ‘values/sum’: [None, .5, 1.5, 2.5, 3.5, None], … ‘values/n_occurrences’: [None, 1, 1, 1, 1, None], … “values/quantiles”: [ … {‘values/quantile/0.25’: 1, ‘values/quantile/0.5’: 2, ‘values/quantile/0.75’: 3}, … {‘values/quantile/0.25’: 1, ‘values/quantile/0.5’: 2, ‘values/quantile/0.75’: 3}, … {‘values/quantile/0.25’: 1, ‘values/quantile/0.5’: 2, ‘values/quantile/0.75’: 3}, … {‘values/quantile/0.25’: 1, ‘values/quantile/0.5’: 2, ‘values/quantile/0.75’: 3}, … {‘values/quantile/0.25’: 1, ‘values/quantile/0.5’: 2, ‘values/quantile/0.75’: 3}, … {‘values/quantile/0.25’: None, ‘values/quantile/0.5’: None, … ‘values/quantile/0.75’: None}, … ], … }) EicForecastingModule.get_code_to_numeric_value_map(metadata_df, get_raw_values=True).tolist() [nan, 0.5, 1.5, 2.5, 3.5, nan, nan] EicForecastingModule.get_code_to_numeric_value_map(metadata_df, get_raw_values=False).tolist() [nan, 0.125, 0.375, 0.625, 0.875, nan, nan]
Source code in meds_torch/models/eic_forecasting.py
get_code_to_time_map(metadata_df)
classmethod
Convert the metadata DataFrame to a dictionary mapping code to time.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata_df |
Polars DataFrame containing code metadata (includes ‘code’ and ‘code/vocab_index’ columns) |
required |
Returns:
| Name | Type | Description |
|---|---|---|
dict |
dict
|
Mapping code to time in years |
Example:
metadata_df = pl.DataFrame({ … “code”: [“A”, “B”, “C”, “TIME//DELTA//TOKEN//_Q_17”], … “code/vocab_index”: [0, 1, 2, 3], … “values/sum”: [None, None, None, 1], … “values/n_occurrences”: [None, None, None, 1], … }) EicForecastingModule.get_code_to_time_map(metadata_df) tensor([0., 0., 0., 1., 0.])
Source code in meds_torch/models/eic_forecasting.py
to_trajectory_batch(code, mask, metadata_df, prediction_time_offset_years, code_to_time_map=None, code_to_numeric_value_map=None)
classmethod
Convert the model output to MEDS format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
code |
Tensor
|
Tensor of shape (batch_size, sequence_length) containing event codes |
required |
mask |
Tensor
|
Tensor of shape (batch_size, sequence_length) indicates valid measurements/codes |
required |
metadata_df |
Polars DataFrame containing code metadata (includes ‘code’ column) |
required | |
prediction_time_offset_days |
Tensor of shape (batch_size,) containing the time difference in days between each input sequence’s end time and its target prediction time. Used to calculate absolute timestamps since the TrajectoryBatch stores times relative to the prediction time. |
required |
Returns:
| Type | Description |
|---|---|
TrajectoryBatch
|
pl.DataFrame: MEDS format DataFrame with columns: - time_index: Time in years starting from 0 - code: The medical code - value: Always 1.0 (presence indicator) - sample_id: ID of the generated sample |
Time will start from 0, and is measured in years.
Example:
from datetime import datetime metadata_df = pl.DataFrame({ … “code”: [“A”, “A//_Q_1”, “A//_Q_2”, “A//_Q_3”, “A//_Q_4”, “TIME//DELTA//TOKEN//_Q_17”], … “code/vocab_index”: [0, 1, 2, 3, 4, 5], … ‘values/min’: [0, 0, 0, 0, 0, None], … ‘values/max’: [4, 4, 4, 4, 4, None], … ‘values/sum’: [None, .5, 1.5, 2.5, 3.5, 1], … ‘values/n_occurrences’: [None, 1, 1, 1, 1, 1], … “values/quantiles”: [ … {‘values/quantile/0.25’: 1, ‘values/quantile/0.5’: 2, ‘values/quantile/0.75’: 3}, … {‘values/quantile/0.25’: 1, ‘values/quantile/0.5’: 2, ‘values/quantile/0.75’: 3}, … {‘values/quantile/0.25’: 1, ‘values/quantile/0.5’: 2, ‘values/quantile/0.75’: 3}, … {‘values/quantile/0.25’: 1, ‘values/quantile/0.5’: 2, ‘values/quantile/0.75’: 3}, … {‘values/quantile/0.25’: 1, ‘values/quantile/0.5’: 2, ‘values/quantile/0.75’: 3}, … {‘values/quantile/0.25’: None, ‘values/quantile/0.5’: None, … ‘values/quantile/0.75’: None}, … ], … }) code = torch.tensor([[0, 2, 5, 5], [2, 3, 4, 5], [5, 5, 0, 1]]) mask = torch.tensor([[1, 1, 1, 1], [1, 1, 1, 0], [1, 1, 1, 0]]) prediction_time_offset_years = torch.tensor([0.0, 1.0, 2.0]) from pprint import pprint, pformat subject_ids = [1,2,3] prediction_times = [1,2,3] EicForecastingModule.to_trajectory_batch(code, mask, metadata_df, prediction_time_offset_years … ).to_meds(subject_ids, prediction_times).columns [‘subject_id’, ‘prediction_time’, ‘time’, ‘code’, ‘code/vocab_index’, ‘numeric_value’]
Source code in meds_torch/models/eic_forecasting.py
update_generation_state(tokens, cumulative_time, trajectory_labeler=None)
Updates trajectory_labeler state, and returns state information.
Examples:
>>> import tempfile
>>> from clinical_zeroshot_labeler.labeler import WindowStatus
>>> # Create test setup using helper function
>>> _, metadata_df, _, _ = create_dummy_sequence_labeler()
>>> # Write metadata to temporary file and create config
>>> temp_file = tempfile.NamedTemporaryFile(suffix='.parquet')
>>> metadata_df.write_parquet(temp_file.name)
>>> cfg = create_model_config(temp_file.name)
>>> model = EicForecastingModule(cfg)
>>> model._init_time_and_value_quantiles()
>>> B = 2 # batch_size
>>> device = 'cpu'
>>> # Setup basic test case
>>> cumulative = torch.tensor([0.0, 0.0], device=device)
>>> tokens = torch.randint(0, 5, (B,3), device=device)
>>> # Test trajectory labeler progression
>>> labeler = DummyTrajectoryLabeler(B)
>>> time, status, is_finished, ended = model.update_generation_state(
... tokens=tokens,
... cumulative_time=cumulative,
... trajectory_labeler=labeler,
... )
>>> assert time.shape == (B,)
>>> assert status.shape == (B,)
>>> assert not is_finished
>>> assert not ended.any()
>>> # Test second step shows active status
>>> time, status, is_finished, ended = model.update_generation_state(
... tokens=tokens,
... cumulative_time=time,
... trajectory_labeler=labeler,
... )
>>> assert (status == WindowStatus.ACTIVE.value).all()
>>> assert not is_finished
>>> assert not ended.any()
>>> # Test third step shows satisfied status and finished
>>> time, status, is_finished, ended = model.update_generation_state(
... tokens=tokens,
... cumulative_time=time,
... trajectory_labeler=labeler,
... )
>>> assert (status == WindowStatus.SATISFIED.value).all()
>>> assert is_finished
>>> assert ended.all()
>>> # Test without trajectory labeler
>>> time, status, is_finished, ended = model.update_generation_state(
... tokens=tokens,
... cumulative_time=time,
... trajectory_labeler=None,
... )
>>> assert time.shape == (B,)
>>> assert status is None
>>> assert not is_finished
>>> assert not ended.any()
Source code in meds_torch/models/eic_forecasting.py
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 | |
NextTokenPredictionMetric
Bases: Metric
A metric class for calculating AUC and top-n accuracy for next token prediction in language models.
This metric computes the Area Under the Receiver Operating Characteristic Curve (AUROC) and top-n accuracy for each position in the sequence, considering only the next token prediction.
Attributes:
| Name | Type | Description |
|---|---|---|
vocab_size |
int
|
The size of the vocabulary. |
top_n |
tuple
|
The values of n for which to calculate top-n accuracy. |
auroc |
MulticlassAUROC
|
The AUROC metric for multiclass classification. |
top_n_accuracy |
dict
|
A dictionary of MulticlassAccuracy metrics for each n in top_n. |
Source code in meds_torch/models/eic_forecasting.py
__init__(vocab_size, top_k_acc, next_token_auc, dist_sync_on_step=False)
Initialize the NextTokenPredictionMetric.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
vocab_size |
int
|
The size of the vocabulary. |
required |
top_n |
tuple
|
The values of n for which to calculate top-n accuracy. Default is (1, 5, 10). |
required |
dist_sync_on_step |
bool
|
Synchronize metric state across processes at each step. Default is False. |
False
|
Source code in meds_torch/models/eic_forecasting.py
compute()
Compute the AUROC and top-n accuracy based on accumulated statistics.
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the computed AUROC and top-n accuracy for each n in top_n. |
Source code in meds_torch/models/eic_forecasting.py
update(logits, targets, mask)
Update the metric state with batch statistics.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits |
Tensor
|
Predicted logits from the model, shape (batch_size, seq_length, vocab_size). |
required |
targets |
Tensor
|
Ground truth labels, shape (batch_size, seq_length). |
required |
mask |
Tensor
|
Mask to ignore padded elements, shape (batch_size, seq_length). |
required |
The method shifts the targets to align with the next token prediction and updates AUROC and top-n accuracy.
Source code in meds_torch/models/eic_forecasting.py
create_dummy_sequence_labeler(batch_size=2)
Create a dummy sequence labeler with a simple ACES task configuration.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
batch_size |
int
|
Number of sequences to process in parallel |
2
|
Returns:
| Type | Description |
|---|---|
|
Tuple containing: - Dummy labeler instance - Metadata DataFrame - Sample input batch - ACES task configuration string |
Examples:
>>> labeler, metadata_df, batch, task_config = create_dummy_sequence_labeler()
>>> import torch
>>> assert isinstance(batch['code'], torch.Tensor)
>>> assert batch['code'].shape == (2, 3) # batch_size=2, seq_len=3
>>> assert 'mask' in batch
>>> # Test indices are within vocab range
>>> max_idx = batch['code'].max()
>>> assert max_idx < len(metadata_df)
Source code in meds_torch/models/eic_forecasting.py
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 | |
create_model_config(metadata_df_path)
Create a model configuration for testing.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
metadata_df_path |
str
|
Path to metadata DataFrame parquet file |
required |
Returns:
| Type | Description |
|---|---|
|
Instantiated model configuration |
Examples:
>>> import tempfile, polars as pl
>>> with tempfile.NamedTemporaryFile(suffix='.parquet') as temp_file:
... df = pl.DataFrame({"code": ["A"], "code/vocab_index": [0]})
... df.write_parquet(temp_file.name)
... cfg = create_model_config(temp_file.name)
>>> assert cfg.vocab_size == 2 # Original size + pad token