cehrbert 1.4.2__tar.gz → 1.4.3__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (211) hide show
  1. {cehrbert-1.4.2 → cehrbert-1.4.3}/PKG-INFO +2 -2
  2. {cehrbert-1.4.2 → cehrbert-1.4.3}/pyproject.toml +1 -1
  3. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/hf_data_generator/hf_dataset.py +6 -4
  4. cehrbert-1.4.3/src/cehrbert/data_generators/hf_data_generator/hf_dataset_collator.py +396 -0
  5. cehrbert-1.4.3/src/cehrbert/data_generators/hf_data_generator/sample_packing_sampler.py +138 -0
  6. cehrbert-1.4.3/src/cehrbert/linear_prob/compute_cehrbert_features.py +307 -0
  7. cehrbert-1.4.3/src/cehrbert/linear_prob/train_with_cehrbert_features.py +87 -0
  8. cehrbert-1.4.3/src/cehrbert/models/hf_models/config.py +66 -0
  9. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/hf_models/hf_cehrbert.py +130 -37
  10. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/runners/hf_cehrbert_finetune_runner.py +149 -189
  11. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/runners/hf_cehrbert_pretrain_runner.py +155 -80
  12. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/runners/hf_runner_argument_dataclass.py +25 -0
  13. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/runners/runner_util.py +5 -5
  14. cehrbert-1.4.3/src/cehrbert/runners/sample_packing_trainer.py +158 -0
  15. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert.egg-info/PKG-INFO +2 -2
  16. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert.egg-info/SOURCES.txt +6 -0
  17. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert.egg-info/requires.txt +1 -1
  18. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/integration_tests/runners/hf_cehrbert_pretrain_runner_meds_test.py +6 -0
  19. cehrbert-1.4.3/tests/integration_tests/runners/hf_cehrbert_pretrain_runner_sample_packing_test.py +99 -0
  20. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/integration_tests/runners/hf_cehrbert_pretrain_runner_streaming_test.py +6 -0
  21. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/integration_tests/runners/hf_cehrbert_pretrain_runner_test.py +10 -0
  22. cehrbert-1.4.3/tests/unit_tests/utils/__init__.py +0 -0
  23. cehrbert-1.4.2/src/cehrbert/data_generators/hf_data_generator/hf_dataset_collator.py +0 -231
  24. cehrbert-1.4.2/src/cehrbert/models/hf_models/config.py +0 -230
  25. {cehrbert-1.4.2 → cehrbert-1.4.3}/.github/workflows/python-build.yml +0 -0
  26. {cehrbert-1.4.2 → cehrbert-1.4.3}/.github/workflows/tests.yml +0 -0
  27. {cehrbert-1.4.2 → cehrbert-1.4.3}/.gitignore +0 -0
  28. {cehrbert-1.4.2 → cehrbert-1.4.3}/.pre-commit-config.yaml +0 -0
  29. {cehrbert-1.4.2 → cehrbert-1.4.3}/LICENSE +0 -0
  30. {cehrbert-1.4.2 → cehrbert-1.4.3}/README.md +0 -0
  31. {cehrbert-1.4.2 → cehrbert-1.4.3}/db_properties.ini +0 -0
  32. {cehrbert-1.4.2 → cehrbert-1.4.3}/deepspeed_configs/zero1.json +0 -0
  33. {cehrbert-1.4.2 → cehrbert-1.4.3}/deepspeed_configs/zero2.json +0 -0
  34. {cehrbert-1.4.2 → cehrbert-1.4.3}/deepspeed_configs/zero3.json +0 -0
  35. {cehrbert-1.4.2 → cehrbert-1.4.3}/full_grid_search_config.ini +0 -0
  36. {cehrbert-1.4.2 → cehrbert-1.4.3}/images/cehr_bert_architecture.png +0 -0
  37. {cehrbert-1.4.2 → cehrbert-1.4.3}/images/tokenization_att_generation.png +0 -0
  38. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_configs/hf_cehrbert_finetuning_runner_config.yaml +0 -0
  39. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_configs/hf_cehrbert_pretrain_runner_config.yaml +0 -0
  40. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_configs/hf_cehrbert_pretrain_runner_meds_config.yaml +0 -0
  41. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/.done +0 -0
  42. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/code/data +0 -0
  43. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/code/dictionary +0 -0
  44. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/code/zdict +0 -0
  45. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/doses_per_24_hrs/data +0 -0
  46. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/doses_per_24_hrs/zdict +0 -0
  47. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/drg_mortality/data +0 -0
  48. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/drg_mortality/zdict +0 -0
  49. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/drg_severity/data +0 -0
  50. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/drg_severity/zdict +0 -0
  51. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/emar_id/data +0 -0
  52. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/emar_id/dictionary +0 -0
  53. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/emar_id/zdict +0 -0
  54. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/emar_seq/data +0 -0
  55. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/emar_seq/zdict +0 -0
  56. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/frequency/data +0 -0
  57. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/frequency/dictionary +0 -0
  58. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/frequency/zdict +0 -0
  59. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/hadm_id/data +0 -0
  60. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/hadm_id/zdict +0 -0
  61. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/icustay_id/data +0 -0
  62. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/icustay_id/zdict +0 -0
  63. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/insurance/data +0 -0
  64. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/insurance/dictionary +0 -0
  65. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/insurance/zdict +0 -0
  66. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/language/data +0 -0
  67. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/language/dictionary +0 -0
  68. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/language/zdict +0 -0
  69. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/link_order_id/data +0 -0
  70. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/link_order_id/zdict +0 -0
  71. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/marital_status/data +0 -0
  72. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/marital_status/dictionary +0 -0
  73. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/marital_status/zdict +0 -0
  74. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/meds_reader.length +0 -0
  75. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/meds_reader.null_map/data +0 -0
  76. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/meds_reader.null_map/zdict +0 -0
  77. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/meds_reader.properties +0 -0
  78. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/meds_reader.version +0 -0
  79. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/metadata/.shards.json +0 -0
  80. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/metadata/codes.parquet +0 -0
  81. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/metadata/dataset.json +0 -0
  82. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/metadata/subject_splits.parquet +0 -0
  83. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/numeric_value/data +0 -0
  84. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/numeric_value/zdict +0 -0
  85. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/order_id/data +0 -0
  86. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/order_id/zdict +0 -0
  87. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/ordercategorydescription/data +0 -0
  88. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/ordercategorydescription/dictionary +0 -0
  89. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/ordercategorydescription/zdict +0 -0
  90. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/poe_id/data +0 -0
  91. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/poe_id/dictionary +0 -0
  92. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/poe_id/zdict +0 -0
  93. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/priority/data +0 -0
  94. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/priority/dictionary +0 -0
  95. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/priority/zdict +0 -0
  96. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/race/data +0 -0
  97. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/race/dictionary +0 -0
  98. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/race/zdict +0 -0
  99. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/route/data +0 -0
  100. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/route/dictionary +0 -0
  101. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/route/zdict +0 -0
  102. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/statusdescription/data +0 -0
  103. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/statusdescription/dictionary +0 -0
  104. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/statusdescription/zdict +0 -0
  105. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/subject_id +0 -0
  106. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/text_value/data +0 -0
  107. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/text_value/dictionary +0 -0
  108. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/text_value/zdict +0 -0
  109. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/time/data +0 -0
  110. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/time/zdict +0 -0
  111. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/unit/data +0 -0
  112. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/unit/dictionary +0 -0
  113. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/MIMIC-IV-meds/meds_reader/unit/zdict +0 -0
  114. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/finetune/full/fake_data.parquet +0 -0
  115. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/finetune/test/fake_data.parquet +0 -0
  116. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/finetune/train/fake_data.parquet +0 -0
  117. {cehrbert-1.4.2 → cehrbert-1.4.3}/sample_data/pretrain/patient_sequence.parquet +0 -0
  118. {cehrbert-1.4.2 → cehrbert-1.4.3}/setup.cfg +0 -0
  119. {cehrbert-1.4.2 → cehrbert-1.4.3}/simple_grid_search_config.ini +0 -0
  120. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/__init__.py +0 -0
  121. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/config/__init__.py +0 -0
  122. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/config/grid_search_config.py +0 -0
  123. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/config/output_names.py +0 -0
  124. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/__init__.py +0 -0
  125. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/data_classes.py +0 -0
  126. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/data_generator_base.py +0 -0
  127. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/graph_sample_method.py +0 -0
  128. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/hf_data_generator/__init__.py +0 -0
  129. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/hf_data_generator/cache_util.py +0 -0
  130. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/hf_data_generator/hf_dataset_mapping.py +0 -0
  131. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/__init__.py +0 -0
  132. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/meds_to_cehrbert_base.py +0 -0
  133. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/meds_to_cehrbert_micmic4.py +0 -0
  134. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/hf_data_generator/meds_to_cehrbert_conversion_rules/meds_to_cehrbert_omop.py +0 -0
  135. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/hf_data_generator/meds_utils.py +0 -0
  136. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/hf_data_generator/patient_block.py +0 -0
  137. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/learning_objective.py +0 -0
  138. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/data_generators/tokenizer.py +0 -0
  139. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/evaluations/__init__.py +0 -0
  140. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/evaluations/evaluation.py +0 -0
  141. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/evaluations/evaluation_parameters.py +0 -0
  142. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/evaluations/evaluation_parse_args.py +0 -0
  143. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/evaluations/model_evaluators/__init__.py +0 -0
  144. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/evaluations/model_evaluators/bert_model_evaluators.py +0 -0
  145. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/evaluations/model_evaluators/frequency_model_evaluators.py +0 -0
  146. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/evaluations/model_evaluators/hierarchical_bert_evaluators.py +0 -0
  147. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/evaluations/model_evaluators/model_evaluators.py +0 -0
  148. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/evaluations/model_evaluators/sequence_model_evaluators.py +0 -0
  149. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/evaluations/transfer_learning_evaluation.py +0 -0
  150. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/keras_transformer/__init__.py +0 -0
  151. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/keras_transformer/bert.py +0 -0
  152. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/keras_transformer/extras.py +0 -0
  153. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/keras_transformer/position.py +0 -0
  154. {cehrbert-1.4.2/src/cehrbert/med_extension → cehrbert-1.4.3/src/cehrbert/linear_prob}/__init__.py +0 -0
  155. {cehrbert-1.4.2/src/cehrbert/models → cehrbert-1.4.3/src/cehrbert/med_extension}/__init__.py +0 -0
  156. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/med_extension/schema_extension.py +0 -0
  157. {cehrbert-1.4.2/src/cehrbert/models/hf_models → cehrbert-1.4.3/src/cehrbert/models}/__init__.py +0 -0
  158. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/bert_models.py +0 -0
  159. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/bert_models_visit_prediction.py +0 -0
  160. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/evaluation_models.py +0 -0
  161. {cehrbert-1.4.2/src/cehrbert/models/layers → cehrbert-1.4.3/src/cehrbert/models/hf_models}/__init__.py +0 -0
  162. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/hf_models/hf_modeling_outputs.py +0 -0
  163. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/hf_models/tokenization_hf_cehrbert.py +0 -0
  164. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/hf_models/tokenization_utils.py +0 -0
  165. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/hierachical_bert_model_v2.py +0 -0
  166. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/hierachical_phenotype_model_new.py +0 -0
  167. {cehrbert-1.4.2/src/cehrbert/runners → cehrbert-1.4.3/src/cehrbert/models/layers}/__init__.py +0 -0
  168. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/layers/custom_layers.py +0 -0
  169. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/layers/hierarchical_custom_layers.py +0 -0
  170. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/loss_schedulers.py +0 -0
  171. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/models/parse_args.py +0 -0
  172. {cehrbert-1.4.2/src/cehrbert/tools → cehrbert-1.4.3/src/cehrbert/runners}/__init__.py +0 -0
  173. {cehrbert-1.4.2/src/cehrbert/trainers → cehrbert-1.4.3/src/cehrbert/tools}/__init__.py +0 -0
  174. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/tools/download_omop_tables.py +0 -0
  175. {cehrbert-1.4.2/src/cehrbert/utils → cehrbert-1.4.3/src/cehrbert/trainers}/__init__.py +0 -0
  176. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/trainers/model_trainer.py +0 -0
  177. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/trainers/train_cehr_bert.py +0 -0
  178. {cehrbert-1.4.2/tests → cehrbert-1.4.3/src/cehrbert/utils}/__init__.py +0 -0
  179. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/utils/checkpoint_utils.py +0 -0
  180. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/utils/logging_utils.py +0 -0
  181. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/utils/model_utils.py +0 -0
  182. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert/utils/stat_utils.py +0 -0
  183. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert.egg-info/dependency_links.txt +0 -0
  184. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert.egg-info/entry_points.txt +0 -0
  185. {cehrbert-1.4.2 → cehrbert-1.4.3}/src/cehrbert.egg-info/top_level.txt +0 -0
  186. {cehrbert-1.4.2/tests/integration_tests → cehrbert-1.4.3/tests}/__init__.py +0 -0
  187. {cehrbert-1.4.2/tests/integration_tests/runners → cehrbert-1.4.3/tests/integration_tests}/__init__.py +0 -0
  188. {cehrbert-1.4.2/tests/integration_tests/trainers → cehrbert-1.4.3/tests/integration_tests/runners}/__init__.py +0 -0
  189. {cehrbert-1.4.2/tests/unit_tests → cehrbert-1.4.3/tests/integration_tests/trainers}/__init__.py +0 -0
  190. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/integration_tests/trainers/train_cehr_bert_test.py +0 -0
  191. {cehrbert-1.4.2/tests/unit_tests/data_generators → cehrbert-1.4.3/tests/unit_tests}/__init__.py +0 -0
  192. {cehrbert-1.4.2/tests/unit_tests/data_generators/hf_data_generator → cehrbert-1.4.3/tests/unit_tests/data_generators}/__init__.py +0 -0
  193. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/data_generators/bert_masked_language_modeling_learning_objective_test.py +0 -0
  194. {cehrbert-1.4.2/tests/unit_tests/models → cehrbert-1.4.3/tests/unit_tests/data_generators/hf_data_generator}/__init__.py +0 -0
  195. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/data_generators/hf_data_generator/hf_dataset_mapping_test.py +0 -0
  196. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/data_generators/hf_data_generator/hf_generate_start_end_index_mapping_test.py +0 -0
  197. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/data_generators/hf_data_generator/hf_masked_language_modeling_mapping_test.py +0 -0
  198. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/data_generators/hf_data_generator/hf_med_to_cehrbert_mapping_test.py +0 -0
  199. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/data_generators/hf_data_generator/hf_sort_patient_sequence_dataset_mapping_test.py +0 -0
  200. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/data_generators/hf_data_generator/meds_utils_test.py +0 -0
  201. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/data_generators/hf_data_generator/omop_meds_generate_demographics_and_patient_blocks_test.py +0 -0
  202. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/data_generators/hf_data_generator/patient_block_test.py +0 -0
  203. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/data_generators/visit_prediction_learning_objective_test.py +0 -0
  204. {cehrbert-1.4.2/tests/unit_tests/models/hf_models → cehrbert-1.4.3/tests/unit_tests/models}/__init__.py +0 -0
  205. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/models/concept_value_decoder_layer_test.py +0 -0
  206. {cehrbert-1.4.2/tests/unit_tests/utils → cehrbert-1.4.3/tests/unit_tests/models/hf_models}/__init__.py +0 -0
  207. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/models/hf_models/hf_cehrbert_test.py +0 -0
  208. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/models/hf_models/numeric_concept_statistics_test.py +0 -0
  209. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/models/hf_models/tokenization_hf_cehrbert_test.py +0 -0
  210. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/utils/truncated_offline_statistics_test.py +0 -0
  211. {cehrbert-1.4.2 → cehrbert-1.4.3}/tests/unit_tests/utils/truncated_online_statistics_test.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: cehrbert
3
- Version: 1.4.2
3
+ Version: 1.4.3
4
4
  Summary: CEHR-BERT: Incorporating temporal information from structured EHR data to improve prediction tasks
5
5
  Author-email: Chao Pang <chaopang229@gmail.com>, Xinzhuo Jiang <xj2193@cumc.columbia.edu>, Krishna Kalluri <kk3326@cumc.columbia.edu>, Nishanth Parameshwar Pavinkurve <np2689@cumc.columbia.edu>, Karthik Natarajan <kn2174@cumc.columbia.edu>
6
6
  License: MIT License
@@ -39,7 +39,7 @@ Requires-Dist: tensorflow-datasets==4.5.2
39
39
  Requires-Dist: tqdm>=4.66.1
40
40
  Requires-Dist: torch==2.4.0
41
41
  Requires-Dist: tokenizers>=0.19.0
42
- Requires-Dist: transformers>=4.41.0
42
+ Requires-Dist: transformers<=4.45.0,>=4.41.0
43
43
  Requires-Dist: accelerate>=0.31.0
44
44
  Requires-Dist: Werkzeug==3.0.1
45
45
  Requires-Dist: wandb>=0.17.8
@@ -52,7 +52,7 @@ dependencies = [
52
52
  "tqdm>=4.66.1",
53
53
  "torch==2.4.0",
54
54
  "tokenizers>=0.19.0",
55
- "transformers>=4.41.0",
55
+ "transformers>=4.41.0, <= 4.45.0",
56
56
  "accelerate>=0.31.0",
57
57
  "Werkzeug==3.0.1",
58
58
  "wandb>=0.17.8",
@@ -48,7 +48,7 @@ def create_cehrbert_pretraining_dataset(
48
48
  mapping_functions = [HFTokenizationMapping(concept_tokenizer, True)]
49
49
  else:
50
50
  mapping_functions = [
51
- SortPatientSequenceMapping(),
51
+ # SortPatientSequenceMapping(),
52
52
  HFTokenizationMapping(concept_tokenizer, True),
53
53
  ]
54
54
 
@@ -91,7 +91,7 @@ def create_cehrbert_finetuning_dataset(
91
91
  else:
92
92
  mapping_functions = [
93
93
  HFFineTuningMapping(),
94
- SortPatientSequenceMapping(),
94
+ # SortPatientSequenceMapping(),
95
95
  HFTokenizationMapping(concept_tokenizer, False),
96
96
  ]
97
97
 
@@ -166,6 +166,8 @@ def apply_cehrbert_dataset_mapping(
166
166
  )
167
167
  if mapping_function.remove_columns():
168
168
  dataset = dataset.remove_columns(mapping_function.remove_columns())
169
- if cache_file_collector:
170
- cache_file_collector.add_cache_files(dataset)
169
+
170
+ if cache_file_collector:
171
+ cache_file_collector.add_cache_files(dataset)
172
+
171
173
  return dataset
@@ -0,0 +1,396 @@
1
+ import collections
2
+ import random
3
+ from typing import Any, Dict, Optional, Tuple
4
+
5
+ import numpy as np
6
+ import torch
7
+ from torch.nn.utils.rnn import pad_sequence
8
+
9
+ from cehrbert.data_generators.hf_data_generator.hf_dataset_mapping import TruncationType
10
+ from cehrbert.models.hf_models.tokenization_hf_cehrbert import CehrBertTokenizer
11
+
12
+
13
+ class CehrBertDataCollator:
14
+ def __init__(
15
+ self,
16
+ tokenizer: CehrBertTokenizer,
17
+ max_length: int,
18
+ mlm_probability: float = 0.15,
19
+ is_pretraining: bool = True,
20
+ truncate_type: TruncationType = TruncationType.RANDOM_RIGHT_TRUNCATION,
21
+ ):
22
+ self.tokenizer = tokenizer
23
+ self.max_length = max_length
24
+ self.mlm_probability = mlm_probability
25
+ self.is_pretraining = is_pretraining
26
+ # We only enable random truncations during pretraining
27
+ # We always take the most recent history during finetuning indicated by TruncationType.TAIL
28
+ self.truncate_type = truncate_type if is_pretraining else TruncationType.TAIL
29
+ # Pre-compute these so we can use them later on
30
+ # We used VS for the historical data, currently, we use the new [VS] for the newer data
31
+ # so we need to check both cases.
32
+ self.vs_token_id = tokenizer.convert_token_to_id("VS")
33
+ if self.vs_token_id == tokenizer.oov_token_index:
34
+ self.vs_token_id = tokenizer.convert_token_to_id("[VS]")
35
+ self.ve_token_id = tokenizer.convert_token_to_id("VE")
36
+ if self.ve_token_id == tokenizer.oov_token_index:
37
+ self.ve_token_id = tokenizer.convert_token_to_id("[VE]")
38
+
39
+ @staticmethod
40
+ def _convert_to_tensor(features: Any) -> torch.Tensor:
41
+ if isinstance(features, torch.Tensor):
42
+ return features
43
+ else:
44
+ return torch.tensor(features)
45
+
46
+ def __call__(self, examples):
47
+
48
+ examples = [self.generate_start_end_index(_) for _ in examples]
49
+ batch = {}
50
+ batch_size = len(examples)
51
+
52
+ # Assume that each example in the batch is a dictionary with 'input_ids' and 'attention_mask'
53
+ batch_input_ids = [self._convert_to_tensor(example["input_ids"]) for example in examples]
54
+ batch_attention_mask = [
55
+ (
56
+ self._convert_to_tensor(example["attention_mask"]).to(torch.float)
57
+ if "attention_mask" in example
58
+ else torch.ones_like(self._convert_to_tensor(example["input_ids"]), dtype=torch.float)
59
+ )
60
+ for example in examples
61
+ ]
62
+ batch_ages = [self._convert_to_tensor(example["ages"]) for example in examples]
63
+ batch_dates = [self._convert_to_tensor(example["dates"]) for example in examples]
64
+ batch_visit_concept_orders = [self._convert_to_tensor(example["visit_concept_orders"]) for example in examples]
65
+ batch_concept_values = [self._convert_to_tensor(example["concept_values"]) for example in examples]
66
+ batch_concept_value_masks = [self._convert_to_tensor(example["concept_value_masks"]) for example in examples]
67
+ batch_visit_segments = [self._convert_to_tensor(example["visit_segments"]) for example in examples]
68
+
69
+ # Pad sequences to the max length in the batch
70
+ batch["input_ids"] = pad_sequence(
71
+ batch_input_ids,
72
+ batch_first=True,
73
+ padding_value=self.tokenizer.pad_token_index,
74
+ )
75
+ batch["attention_mask"] = pad_sequence(batch_attention_mask, batch_first=True, padding_value=0.0)
76
+ batch["ages"] = pad_sequence(batch_ages, batch_first=True, padding_value=0)
77
+ batch["dates"] = pad_sequence(batch_dates, batch_first=True, padding_value=0)
78
+ batch["visit_concept_orders"] = pad_sequence(
79
+ batch_visit_concept_orders,
80
+ batch_first=True,
81
+ padding_value=self.max_length - 1,
82
+ )
83
+ batch["concept_values"] = pad_sequence(batch_concept_values, batch_first=True, padding_value=0.0)
84
+ batch["concept_value_masks"] = pad_sequence(batch_concept_value_masks, batch_first=True, padding_value=0.0)
85
+ batch["visit_segments"] = pad_sequence(batch_visit_segments, batch_first=True, padding_value=0)
86
+
87
+ if not getattr(self, "sample_packing", False):
88
+ # Prepend the CLS token and their associated values to the corresponding time series features
89
+ batch["input_ids"] = torch.cat(
90
+ [
91
+ torch.full((batch_size, 1), self.tokenizer.cls_token_index),
92
+ batch["input_ids"],
93
+ ],
94
+ dim=1,
95
+ )
96
+ # The attention_mask is set to 1 to enable attention for the CLS token
97
+ batch["attention_mask"] = torch.cat([torch.full((batch_size, 1), 1.0), batch["attention_mask"]], dim=1)
98
+ # Set the age of the CLS token to the starting age
99
+ batch["ages"] = torch.cat([batch["ages"][:, 0:1], batch["ages"]], dim=1)
100
+ # Set the age of the CLS token to the starting date
101
+ batch["dates"] = torch.cat([batch["dates"][:, 0:1], batch["dates"]], dim=1)
102
+ # Set the visit_concept_order of the CLS token to the first visit_concept_order in the sequence subtract by 1
103
+ visit_concept_orders_first = batch["visit_concept_orders"][:, 0:1] - 1
104
+ visit_concept_orders_first = torch.maximum(
105
+ visit_concept_orders_first, torch.zeros_like(visit_concept_orders_first)
106
+ )
107
+ batch["visit_concept_orders"] = torch.cat(
108
+ [visit_concept_orders_first, batch["visit_concept_orders"]], dim=1
109
+ )
110
+ # Set the concept_value of the CLS token to a default value -1.0.
111
+ batch["concept_values"] = torch.cat([torch.full((batch_size, 1), -1.0), batch["concept_values"]], dim=1)
112
+ # Set the concept_value of the CLS token to a default value 0.0 indicating that
113
+ # there is no value associated with this token
114
+ batch["concept_value_masks"] = torch.cat(
115
+ [torch.full((batch_size, 1), 0.0), batch["concept_value_masks"]], dim=1
116
+ )
117
+ # Set the visit_segments of the CLS token to a default value 0 because this doesn't belong to a visit
118
+ batch["visit_segments"] = torch.cat([torch.full((batch_size, 1), 0), batch["visit_segments"]], dim=1)
119
+ else:
120
+ assert (
121
+ batch["attention_mask"].shape[0] == 1
122
+ ), f"batch['attention_mask'].shape[0] must be 0 in sample packing"
123
+
124
+ # This is the most crucial logic for generating the training labels
125
+ if self.is_pretraining:
126
+ # If the labels field is already provided, we will build the MLM labels off of that.
127
+ # The labels value indicates the positions that are not allowed for MLM.
128
+ if "labels" in examples[0]:
129
+ batch_labels = [self._convert_to_tensor(example["labels"]) for example in examples]
130
+ batch["labels"] = pad_sequence(batch_labels, batch_first=True, padding_value=-100)
131
+ # Disable MLM for the CLS token
132
+ batch["labels"] = torch.cat([torch.full((batch_size, 1), -100), batch["labels"]], dim=1)
133
+ else:
134
+ # If the labels is not already provided, we assume all the tokens are subject to
135
+ # the MLM and simply clone the input_ids
136
+ batch["labels"] = batch["input_ids"].clone()
137
+
138
+ batch["input_ids"], batch["labels"] = self.torch_mask_tokens(batch["input_ids"], batch["labels"])
139
+
140
+ bz = len(examples)
141
+ if "person_id" in examples[0]:
142
+ batch["person_id"] = (
143
+ torch.cat(
144
+ [self._convert_to_tensor(example["person_id"]).reshape(-1, 1) for example in examples],
145
+ dim=0,
146
+ )
147
+ .to(torch.int32)
148
+ .reshape(bz, -1)
149
+ )
150
+
151
+ if "index_date" in examples[0]:
152
+ batch["index_date"] = (
153
+ torch.cat(
154
+ [self._convert_to_tensor(example["index_date"]).reshape(-1, 1) for example in examples],
155
+ dim=0,
156
+ )
157
+ .to(torch.float64)
158
+ .reshape(bz, -1)
159
+ )
160
+
161
+ if "age_at_index" in examples[0]:
162
+ batch["age_at_index"] = (
163
+ torch.cat(
164
+ [self._convert_to_tensor(example["age_at_index"]).reshape(-1, 1) for example in examples],
165
+ dim=0,
166
+ )
167
+ .to(torch.float32)
168
+ .reshape(bz, -1)
169
+ )
170
+
171
+ if "classifier_label" in examples[0]:
172
+ batch["classifier_label"] = (
173
+ torch.cat(
174
+ [self._convert_to_tensor(example["classifier_label"]).reshape(-1, 1) for example in examples],
175
+ dim=0,
176
+ )
177
+ .to(torch.float)
178
+ .reshape(bz, -1)
179
+ )
180
+
181
+ return batch
182
+
183
+ def torch_mask_tokens(self, inputs: torch.Tensor, labels: torch.Tensor) -> Tuple[Any, Any]:
184
+ """Prepare masked tokens inputs/labels for masked language modeling: 80% MASK, 10% random, 10% original."""
185
+ # We sample a few tokens in each sequence for MLM training (with probability `self.mlm_probability`)
186
+ probability_matrix = torch.full(labels.shape, self.mlm_probability)
187
+ pad_token_mask = inputs == self.tokenizer.pad_token_index
188
+
189
+ probability_matrix.masked_fill_(pad_token_mask, value=0.0)
190
+ masked_indices = torch.bernoulli(probability_matrix).bool()
191
+ labels[~masked_indices] = -100 # We only compute loss on masked tokens
192
+
193
+ # 80% of the time, we replace masked input tokens with tokenizer.mask_token ([MASK])
194
+ indices_replaced = torch.bernoulli(torch.full(labels.shape, 0.8)).bool() & masked_indices
195
+ inputs[indices_replaced] = self.tokenizer.mask_token_index
196
+
197
+ # 10% of the time, we replace masked input tokens with random word
198
+ indices_random = torch.bernoulli(torch.full(labels.shape, 0.5)).bool() & masked_indices & ~indices_replaced
199
+ random_words = torch.randint(self.tokenizer.vocab_size, labels.shape, dtype=torch.long)
200
+ inputs[indices_random] = random_words[indices_random]
201
+
202
+ # The rest of the time (10% of the time) we keep the masked input tokens unchanged
203
+ return inputs, labels
204
+
205
+ def generate_start_end_index(
206
+ self, record: Dict[str, Any], max_length_allowed: Optional[int] = None
207
+ ) -> Dict[str, Any]:
208
+ """
209
+ Adapted from https://github.com/OHDSI/Apollo/blob/main/data_loading/data_transformer.py.
210
+
211
+ Adding the start and end indices to extract a portion of the patient sequence
212
+ """
213
+ sample_packing = getattr(self, "sample_packing", False)
214
+ max_length_allowed = self.max_length if max_length_allowed is None else max_length_allowed
215
+ seq_length = len(record["input_ids"])
216
+ # Subtract one for the [CLS] token
217
+ new_max_length = max_length_allowed if sample_packing else max_length_allowed - 1
218
+
219
+ # Return the record directly if the actual sequence length is less than the max sequence
220
+ if seq_length <= new_max_length:
221
+ return record
222
+
223
+ # If it is random truncate, we don't care if we slice at the start or end of a visit
224
+ if self.truncate_type == TruncationType.RANDOM_TRUNCATION:
225
+ start_index = random.randint(0, seq_length - new_max_length)
226
+ end_index = min(seq_length, start_index + new_max_length)
227
+ elif self.truncate_type in (
228
+ TruncationType.RANDOM_RIGHT_TRUNCATION,
229
+ TruncationType.RANDOM_COMPLETE,
230
+ ):
231
+ # We randomly pick a [VS] token
232
+ starting_points = []
233
+ for i in range(seq_length - new_max_length):
234
+ current_token = record["input_ids"][i]
235
+ if current_token == self.vs_token_id:
236
+ starting_points.append(i)
237
+
238
+ assert len(starting_points) > 0, f"{record['input_ids'][:seq_length - new_max_length]}"
239
+ start_index = random.choice(starting_points)
240
+ end_index = min(start_index + new_max_length, seq_length)
241
+
242
+ # We randomly backtrack to a [VE] token so the sample is complete
243
+ if self.truncate_type == TruncationType.RANDOM_COMPLETE:
244
+ for i in reversed(list(range(start_index + 1, end_index))):
245
+ current_token = record["input_ids"][i]
246
+ if current_token == self.ve_token_id:
247
+ end_index = i
248
+ break
249
+ else:
250
+ start_index = max(0, seq_length - new_max_length)
251
+ end_index = seq_length
252
+ for i in range(start_index, seq_length):
253
+ current_token = record["input_ids"][i]
254
+ if current_token == self.vs_token_id:
255
+ start_index = i
256
+ break
257
+
258
+ new_record = collections.OrderedDict()
259
+ for k, v in record.items():
260
+ if isinstance(v, list) or isinstance(v, np.ndarray) or (isinstance(v, torch.Tensor) and v.dim() > 0):
261
+ if len(v) == seq_length:
262
+ new_record[k] = v[start_index:end_index]
263
+ else:
264
+ new_record[k] = v
265
+ return new_record
266
+
267
+
268
+ class SamplePackingCehrBertDataCollator(CehrBertDataCollator):
269
+ def __init__(self, max_tokens, max_position_embeddings, *args, **kwargs):
270
+ self.max_tokens_per_batch = max_tokens
271
+ self.max_position_embeddings = max_position_embeddings
272
+ self.sample_packing = True
273
+ super(SamplePackingCehrBertDataCollator, self).__init__(*args, **kwargs)
274
+
275
+ def __call__(self, examples):
276
+ flattened_examples = []
277
+
278
+ # Main inputs
279
+ current_input_ids = []
280
+ current_attention_mask = []
281
+ current_concept_values = []
282
+ current_concept_value_masks = []
283
+ current_ages = []
284
+ current_dates = []
285
+ current_visit_concept_orders = []
286
+ current_visit_segments = []
287
+
288
+ # Demographics
289
+ current_person_ids = []
290
+ current_index_dates = []
291
+
292
+ # Binary classification inputs
293
+ current_age_at_indexes = []
294
+ current_labels = []
295
+
296
+ for idx, example in enumerate(examples):
297
+ # If the sample length exceeds the model's capacity, truncate this example
298
+ if len(example["input_ids"]) > self.max_position_embeddings:
299
+ example = self.generate_start_end_index(example, self.max_position_embeddings)
300
+
301
+ input_ids = example["input_ids"]
302
+ # We add the flattened example to the list either when the example exceeds the total max tokens
303
+ # we add the length by two because we need to add two more tokens [CLS] .... [PAD]
304
+ if len(current_input_ids) + len(input_ids) + 2 > self.max_tokens_per_batch and current_input_ids:
305
+ packed_example = {
306
+ "input_ids": current_input_ids,
307
+ "attention_mask": current_attention_mask,
308
+ "ages": current_ages,
309
+ "dates": current_dates,
310
+ "visit_concept_orders": current_visit_concept_orders,
311
+ "concept_values": current_concept_values,
312
+ "concept_value_masks": current_concept_value_masks,
313
+ "visit_segments": current_visit_segments,
314
+ }
315
+
316
+ if current_labels:
317
+ packed_example.update(
318
+ {
319
+ "person_id": current_person_ids,
320
+ "index_date": current_index_dates,
321
+ "age_at_index": current_age_at_indexes,
322
+ "classifier_label": current_labels,
323
+ }
324
+ )
325
+
326
+ flattened_examples.append(packed_example)
327
+
328
+ # Main inputs
329
+ current_input_ids = []
330
+ current_attention_mask = []
331
+ current_concept_values = []
332
+ current_concept_value_masks = []
333
+ current_ages = []
334
+ current_dates = []
335
+ current_visit_concept_orders = []
336
+ current_visit_segments = []
337
+
338
+ # Demographics
339
+ current_person_ids = []
340
+ current_index_dates = []
341
+
342
+ # Binary classification inputs
343
+ current_age_at_indexes = []
344
+ current_labels = []
345
+
346
+ current_input_ids.extend([self.tokenizer.cls_token_index] + input_ids + [self.tokenizer.pad_token_index])
347
+ current_attention_mask.extend([1] + np.ones_like(input_ids).tolist() + [0])
348
+ current_concept_values.extend([-1] + example["concept_values"] + [-1])
349
+ current_concept_value_masks.extend([0] + example["concept_value_masks"] + [0])
350
+ current_ages.extend([example["ages"][0]] + example["ages"] + [0])
351
+ current_dates.extend([example["dates"][0]] + example["dates"] + [0])
352
+ current_visit_concept_orders.extend(
353
+ [max(0, example["visit_concept_orders"][0] - 1)]
354
+ + example["visit_concept_orders"]
355
+ + [example["visit_concept_orders"][-1]]
356
+ )
357
+ current_visit_segments.extend([0] + example["visit_segments"] + [0])
358
+
359
+ if "person_id" in example:
360
+ current_person_ids.append(example["person_id"])
361
+
362
+ if "index_date" in example:
363
+ current_index_dates.append(example["index_date"])
364
+
365
+ if "age_at_index" in example:
366
+ current_age_at_indexes.append(example["age_at_index"])
367
+
368
+ if "classifier_label" in example:
369
+ current_labels.append(example["classifier_label"])
370
+
371
+ # The final batch needs to be added
372
+ if current_input_ids:
373
+ packed_example = {
374
+ "input_ids": current_input_ids,
375
+ "attention_mask": current_attention_mask,
376
+ "ages": current_ages,
377
+ "dates": current_dates,
378
+ "visit_concept_orders": current_visit_concept_orders,
379
+ "concept_values": current_concept_values,
380
+ "concept_value_masks": current_concept_value_masks,
381
+ "visit_segments": current_visit_segments,
382
+ }
383
+
384
+ if current_labels:
385
+ packed_example.update(
386
+ {
387
+ "person_id": current_person_ids,
388
+ "index_date": current_index_dates,
389
+ "age_at_index": current_age_at_indexes,
390
+ "classifier_label": current_labels,
391
+ }
392
+ )
393
+
394
+ flattened_examples.append(packed_example)
395
+
396
+ return super().__call__(flattened_examples)
@@ -0,0 +1,138 @@
1
+ from typing import Iterator, List, Optional
2
+
3
+ import torch
4
+ import torch.distributed as dist
5
+ from torch.utils.data import Sampler
6
+ from transformers import logging
7
+
8
+ LOG = logging.get_logger("transformers")
9
+
10
+
11
+ class SamplePlacerHolder:
12
+ def __init__(self):
13
+ self.epoch = 0
14
+
15
+ def set_epoch(self, epoch):
16
+ self.epoch = epoch
17
+
18
+
19
+ class SamplePackingBatchSampler(Sampler[List[int]]):
20
+ """
21
+ A batch sampler that creates batches by packing samples together.
22
+
23
+ to maximize GPU utilization, ensuring the total tokens per batch
24
+ doesn't exceed max_tokens.
25
+ """
26
+
27
+ def __init__(
28
+ self,
29
+ lengths: List[int],
30
+ max_tokens_per_batch: int,
31
+ max_position_embeddings: int,
32
+ num_replicas: Optional[int] = None,
33
+ rank: Optional[int] = None,
34
+ seed: int = 0,
35
+ drop_last: bool = False,
36
+ ):
37
+ """
38
+ Args:
39
+
40
+ lengths: List of sequence lengths for each sample
41
+ max_tokens: Maximum number of tokens in a batch
42
+ drop_last: Whether to drop the last incomplete batch
43
+ """
44
+ super().__init__()
45
+
46
+ if num_replicas is None:
47
+ if dist.is_available() and dist.is_initialized():
48
+ num_replicas = dist.get_world_size()
49
+ LOG.info(
50
+ "torch.distributed is initialized and there are %s of replicas",
51
+ num_replicas,
52
+ )
53
+ else:
54
+ num_replicas = 1
55
+ LOG.info("torch.dist is not initialized and therefore default to 1 for num_replicas")
56
+
57
+ if rank is None:
58
+ if dist.is_available() and dist.is_initialized():
59
+ rank = dist.get_rank()
60
+ LOG.info("torch.distributed is initialized and the current rank is %s", rank)
61
+ else:
62
+ rank = 0
63
+ LOG.info("torch.distributed is not initialized and therefore default to 0 for rank")
64
+
65
+ if not (0 <= rank < num_replicas):
66
+ raise ValueError(f"Invalid rank {rank}, rank should be in the interval [0, {num_replicas - 1}]")
67
+
68
+ self.lengths = lengths
69
+ self.max_tokens_per_batch = max_tokens_per_batch
70
+ self.max_position_embeddings = max_position_embeddings
71
+ self.num_replicas = num_replicas
72
+ self.rank = rank
73
+ self.seed = seed
74
+ self.drop_last = drop_last
75
+ # Trainer https://github.com/huggingface/transformers/blame/main/src/transformers/trainer.py#L2470
76
+ # http://github.com/huggingface/accelerate/blob/v0.31.0/src/accelerate/data_loader.py#L482
77
+ # the huggingface trainer will call the accelerate.data_loader.DataLoaderShard.set_epoch,
78
+ # which will call batch_sampler.sample.set_epoch
79
+ self.sampler = SamplePlacerHolder()
80
+
81
+ def __iter__(self) -> Iterator[List[int]]:
82
+
83
+ # deterministically shuffle based on epoch and seed
84
+ g = torch.Generator()
85
+ g.manual_seed(self.seed + self.sampler.epoch)
86
+ indices = torch.randperm(len(self.lengths), generator=g).tolist()
87
+
88
+ # Partition indices for this rank
89
+ indices = indices[self.rank :: self.num_replicas]
90
+
91
+ batch = []
92
+ current_batch_tokens = 0
93
+
94
+ for idx in indices:
95
+ # We take the minimum of the two because each sequence will be truncated to fit
96
+ # the context window of the model
97
+ sample_length = min(self.lengths[idx], self.max_position_embeddings)
98
+ # If adding this sample would exceed max_tokens_per_batch, yield the current batch
99
+ # Plus 2 for [CLS] and [PAD]
100
+ if current_batch_tokens + sample_length + 2 > self.max_tokens_per_batch and batch:
101
+ yield batch
102
+ batch = []
103
+ current_batch_tokens = 0
104
+
105
+ # Add the sample to the current batch
106
+ batch.append(idx)
107
+ # plus extract one for the PAD token to separate samples
108
+ current_batch_tokens += sample_length + 2
109
+
110
+ # Yield the last batch if it's not empty and we're not dropping it
111
+ if batch and not self.drop_last:
112
+ yield batch
113
+
114
+ def __len__(self) -> int:
115
+ """
116
+ Estimates the number of batches that will be generated.
117
+
118
+ This is an approximation since the exact number depends on the specific
119
+ sequence lengths and their order.
120
+ """
121
+ if len(self.lengths) == 0:
122
+ return 0
123
+
124
+ # We need to truncate the lengths due to the context window limit imposed by the model
125
+ truncated_lengths = [min(self.max_position_embeddings, length) for length in self.lengths]
126
+ # Calculate average sequence length
127
+ avg_seq_length = sum(truncated_lengths) // len(truncated_lengths)
128
+
129
+ # Estimate average number of sequences per batch
130
+ seqs_per_batch = self.max_tokens_per_batch // avg_seq_length
131
+
132
+ # Estimate total number of batches
133
+ if self.drop_last:
134
+ # If dropping last incomplete batch
135
+ return len(truncated_lengths) // seqs_per_batch * self.num_replicas
136
+ else:
137
+ # If keeping last incomplete batch, ensure at least 1 batch
138
+ return max(1, len(truncated_lengths) // seqs_per_batch) * self.num_replicas