Repository navigation
Conversation
A task can offer named views (alternative input schemas) over the same samples, labels and split. BaseTask gains optional views, default_view and feature_roles, and view=/model= arguments. The views of a task share one task cache; each view has its own processed samples. SplitPlan saves a patient-to-part assignment so every task and view uses the same split. Models declare accepted_views. The YAIB tasks take their views from the shared numeric_series_views recipe; their default view is unchanged. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
DenseSeriesProcessor and DenseStaticProcessor turn a numeric time series and static record into padded tensors with an explicit step mask, with the same imputation and scaling as the jagged view (values are equal). EmbeddingModel unpacks a processor's (value, mask) tuple by its schema and uses the given mask instead of guessing one from zeros. The YAIB tasks offer the dense view, and 17 sequence models declare that they read it. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
EventStreamProcessor writes a task's numeric time series as a timeline of coded events, one per measured value with nothing imputed or scaled, and EventBirthProcessor derives the birth time from the age. The YAIB tasks offer this as the events view, so foundation models are compared on the same measurements, cohort, labels and split. EHRFoundationModelBase accepts the view and finds its fields without being told their keys. Codes default to YAIB/<feature> and can be mapped to a model's vocabulary. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
|
/review |
Remove the shared pyhealth/tasks/views.py recipe: each YAIB task file now writes its views out as plain input schemas, so a task is self-contained. BaseTask takes view_overrides to change a view's processor settings, or swap a processor, field by field; a subclass can add a named view. A test checks that the three YAIB datasets define the same views. Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
Nothing read it: every drug recommendation task already names its fields the way the drug models expect, so roles would never change which field a model finds. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
- Keep master's task cache key; for a task with views only the input schema moves to the processed-samples key, so views share one task cache. Drop BaseTask.cache_key() and its class-constant and source hashing. - Replace SplitPlan with SubjectSplit.draw/save/load/load_or_draw, reusing SubjectSplit's validation and indexing. Its missing-subject warning now gives a count and a few ids instead of every id. - Drop EventStreamProcessor's vocabulary argument; default codes are YAIB/<feature>. - Shorten the Task Views docs and the view tests to match. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Test CoverageTotal: 86.32% (45657 / 52895 lines)
|
| from .base_processor import LegacyFeatureProcessor | ||
|
|
||
|
|
||
| class _DenseNumeric(LegacyFeatureProcessor): |
There was a problem hiding this comment.
Fixed in a5d9b5a by reuse rather than explanation: both dense processors now build and fit an inner JaggedFeatureProcessor and only reshape its output (values plus missing indicators, and a step mask). Forward fill, mean imputation, z-scoring and indicators are no longer re-implemented. TimeseriesProcessor is not reused because it resamples (timestamps, values) input onto its own grid; the YAIB samples are already hourly records with NaN. The description now says this.
| StageNetTensorProcessor, | ||
| TensorProcessor, | ||
| TimeseriesProcessor, | ||
| DenseSeriesProcessor, |
There was a problem hiding this comment.
Intended, and now stated in the description. EmbeddingModel chooses each field's layer by processor class, and every numeric processor (TimeseriesProcessor, NestedFloatsProcessor, StageNetTensorProcessor, ...) is listed in the same isinstance check, so listing the two dense processors follows the existing pattern rather than adding a new kind of link.
| if isinstance(tensor, (tuple, list)) and hasattr(processor, "schema"): | ||
| parts = dict(zip(processor.schema(), tensor)) | ||
| if "value" in parts: | ||
| tensor = parts["value"] |
There was a problem hiding this comment.
Fixed in a5d9b5a. You were right: the unpacking ran before the passthrough branch, so a field without an embedding layer lost its time or mask. It now runs only for fields EmbeddingModel embeds; passed-through fields keep their whole tuple, as before this PR. New test in tests/core/test_embedding_model_padding.py checks both paths; it fails on the previous commit.
| builder.view = task.view | ||
| # A task with views is compared across models, so its | ||
| # processors may only learn from the training part. | ||
| builder.fit(dataset, split=split, require_split=bool(task.views)) |
There was a problem hiding this comment.
Added to Behaviour changes: set_task without split= now raises for the default jagged view (and dense); the events view still works without a split.
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. Task views let one task feed many model families on fixed samples and splits. The saved SubjectSplit, the dense and events processors, and the thorough tests (29 view tests, split tests, one training step for each of the 17 dense models) are valuable. Coverage is good: the whole repository is at 86.31%, and every changed file is at or above 77%. jamba_ehr.py is the only one below 80%, at 77.33%. The change only adds one line there, so that is fine.
This change touches core code, so it can't be approved automatically and a maintainer will need to review it. It changes these shared pieces:
BaseTask: newviews,default_view,view=,model=andview_overrides=.BaseModel: the newaccepted_viewscheck in__init__.BaseDataset.set_taskand its cache keys.SampleDataset.fit,saveandload.EmbeddingModel.forward, which many models share.
A maintainer will want to look at how the cache key and the new hard error for a missing split affect existing users.
To get this merged:
dense_processor.pyre-implements forward fill, z-score scaling and missing indicators, whichJaggedProcessorandTimeseriesProcessoralready do. Please explain in the description why a separate processor is needed. Or reuse or extend the existing ones if that is simpler.EmbeddingModelnow imports and special-casesDenseSeriesProcessorandDenseStaticProcessor. It also unpacks any(value, mask)tuple throughschema(). Please say in the description that this link is intended, and why.EmbeddingModel.forwardnow passes only the "value" tensor through for tuple-valued fields that have no embedding layer. This can change the output for existing processors such as StageNet or temporal ones. Please add a test showing that existing models are unaffected, or restrict the change to the new dense processors.
Optional suggestions:
- Under "Behaviour changes", say that
set_taskwithoutsplit=now raises an error for the default YAIB view. That view uses statistics-learning processors, so the error is not only a warning anymore. - The foundation-model test is skipped when
transformersis missing. Consider noting that in the test docs.
Reviewed commit 9ba08dd
…sing - EmbeddingModel passes a field without an embedding layer through as its whole tuple again; only fields it embeds are unpacked by schema. The time or mask of a passed-through field is no longer dropped. Test added. - DenseSeriesProcessor and DenseStaticProcessor delegate imputation and scaling to an inner JaggedFeatureProcessor and only reshape its output, so the dense view no longer re-implements forward fill, mean imputation, z-scoring and missing indicators. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| if isinstance(tensor, (tuple, list)) and hasattr(processor, "schema"): | ||
| parts = dict(zip(processor.schema(), tensor)) | ||
| if "value" in parts: | ||
| tensor = parts["value"] |
There was a problem hiding this comment.
Fixed in a5d9b5a. You were right: the unpacking ran before the passthrough branch, so a field without an embedding layer lost its time or mask. It now runs only for fields EmbeddingModel embeds; passed-through fields keep their whole tuple, as before this PR. New test in tests/core/test_embedding_model_padding.py checks both paths; it fails on the previous commit.
| from .base_processor import LegacyFeatureProcessor | ||
|
|
||
|
|
||
| class _DenseNumeric(LegacyFeatureProcessor): |
There was a problem hiding this comment.
Fixed in a5d9b5a by reuse rather than explanation: both dense processors now build and fit an inner JaggedFeatureProcessor and only reshape its output (values plus missing indicators, and a step mask). Forward fill, mean imputation, z-scoring and indicators are no longer re-implemented. TimeseriesProcessor is not reused because it resamples (timestamps, values) input onto its own grid; the YAIB samples are already hourly records with NaN. The description now says this.
| StageNetTensorProcessor, | ||
| TensorProcessor, | ||
| TimeseriesProcessor, | ||
| DenseSeriesProcessor, |
There was a problem hiding this comment.
Intended, and now stated in the description. EmbeddingModel chooses each field's layer by processor class, and every numeric processor (TimeseriesProcessor, NestedFloatsProcessor, StageNetTensorProcessor, ...) is listed in the same isinstance check, so listing the two dense processors follows the existing pattern rather than adding a new kind of link.
| builder.view = task.view | ||
| # A task with views is compared across models, so its | ||
| # processors may only learn from the training part. | ||
| builder.fit(dataset, split=split, require_split=bool(task.views)) |
There was a problem hiding this comment.
Added to Behaviour changes: set_task without split= now raises for the default jagged view (and dense); the events view still works without a split.
|
/review |
|
|
||
| for other in (YAIBMortalityMIMIC3, YAIBMortalityEICU): | ||
| self.assertEqual(sorted(other.views), sorted(YAIBMortalityMIMIC4.views)) | ||
| for view in ("jagged", "dense"): |
There was a problem hiding this comment.
Fixed in f51ad39: the drift test now loops over every view, events included. All three datasets already defined identical events views (same feature names and age column), so nothing else changed.
|
|
||
|
|
||
| @register_processor("event_stream") | ||
| class EventStreamProcessor(FeatureProcessor): |
There was a problem hiding this comment.
Added to the description: EHRFoundationModelTask builds the same (time, code, value, unit) timeline from a patient's raw events, so a foundation model sees everything recorded. The events view builds it from the YAIB task's hourly measurements, so it sees exactly the features the other views do on the same cohort, labels and split. They're complementary; this PR leaves EHRFoundationModelTask unchanged.
|
|
||
|
|
||
| @register_processor("dense_series") | ||
| class DenseSeriesProcessor(_DenseNumeric): |
There was a problem hiding this comment.
Fixed in f51ad39: added docs/api/processors pages for DenseSeriesProcessor, DenseStaticProcessor, EventStreamProcessor and EventBirthProcessor in the TimeseriesProcessor style, plus toctree and list entries in docs/api/processors.rst.
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. Task views let one task feed many model families on fixed samples, labels and splits. The change adds the dense and events processors, saved subject splits, and view-aware caching. It looks close, and the coverage is well above the bar (86.31% overall, and every changed file is at or above 77%; jamba_ehr.py is the lowest at 77.33%, just under the 80% guideline).
This change touches shared core code, so it can't be approved automatically and a maintainer will need to decide. It changes BaseTask (__init__ and __init_subclass__, with the new view selection). It changes BaseModel.init, which now checks the dataset view for every model. It changes BaseDataset.set_task and the task cache key, SampleDataset.fit, EmbeddingModel.forward, which most models share, and SubjectSplit. These are shared API contracts that many components depend on.
To get this merged:
- The description says a test fails if the three YAIB task files drift apart.
test_the_three_datasets_define_the_same_viewsonly compares thejaggedanddenseviews. Please also compareevents, for example the processor names and the settings other than the feature names. Alternatively, change the description to say that onlyjaggedanddenseare checked.
Optional suggestions:
EHRFoundationModelTaskalready builds a similar(time, code, value, unit)timeline. A sentence in the description on how theeventsview relates to it would help.- The four new public processors (
DenseSeriesProcessor,DenseStaticProcessor,EventStreamProcessor,EventBirthProcessor) have no docs/api/processors pages. Adding them would help. - A saved dataset-wide split silently leaves out patients added to the dataset later. A short note in the
load_or_drawdocstring would make that clear. jamba_ehr.pyis at 77.33% coverage, slightly under the 80% guideline. A small extra test would bring it over.
Reviewed commit a5d9b5a
- The YAIB drift test now compares all three views across MIMIC-IV, MIMIC-III and eICU, events included. - Add docs/api pages for DenseSeriesProcessor, DenseStaticProcessor, EventStreamProcessor and EventBirthProcessor, and list them. - Note in SubjectSplit.load_or_draw that a saved split leaves out patients added to the dataset later. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
|
||
| for other in (YAIBMortalityMIMIC3, YAIBMortalityEICU): | ||
| self.assertEqual(sorted(other.views), sorted(YAIBMortalityMIMIC4.views)) | ||
| for view in ("jagged", "dense"): |
There was a problem hiding this comment.
Fixed in f51ad39: the drift test now loops over every view, events included. All three datasets already defined identical events views (same feature names and age column), so nothing else changed.
|
|
||
|
|
||
| @register_processor("event_stream") | ||
| class EventStreamProcessor(FeatureProcessor): |
There was a problem hiding this comment.
Added to the description: EHRFoundationModelTask builds the same (time, code, value, unit) timeline from a patient's raw events, so a foundation model sees everything recorded. The events view builds it from the YAIB task's hourly measurements, so it sees exactly the features the other views do on the same cohort, labels and split. They're complementary; this PR leaves EHRFoundationModelTask unchanged.
|
|
||
|
|
||
| @register_processor("dense_series") | ||
| class DenseSeriesProcessor(_DenseNumeric): |
There was a problem hiding this comment.
Fixed in f51ad39: added docs/api/processors pages for DenseSeriesProcessor, DenseStaticProcessor, EventStreamProcessor and EventBirthProcessor in the TimeseriesProcessor style, plus toctree and list entries in docs/api/processors.rst.
|
/review |
| ), | ||
| }, | ||
| } | ||
| default_view: ClassVar[str] = "jagged" |
There was a problem hiding this comment.
Fixed in 68d243d: all 15 YAIB examples (MIMIC-IV, MIMIC-III, eICU) now draw a saved split with SubjectSplit.load_or_draw and pass it to set_task.
| of the task's views. | ||
| """ | ||
| self._select_view(view, model) | ||
| if view_overrides: |
There was a problem hiding this comment.
Fixed in 68d243d: view_overrides on a task without views now raises the same no-views error as view= and model= (tested).
| Returns: | ||
| The saved split. | ||
| """ | ||
| path = Path(dataset.cache_dir) / "splits" / f"{name}.json" |
There was a problem hiding this comment.
Fixed in 68d243d: load_or_draw rejects a name that is not a plain file name (path separators, '..', '.', empty), tested.
| self.assertEqual(value[:, 1].tolist(), [5.0, 5.0, 5.0]) | ||
| self.assertEqual(mask.tolist(), [1.0, 1.0, 1.0]) | ||
|
|
||
| def test_padding_does_not_change_a_prediction(self): |
There was a problem hiding this comment.
Fixed in 68d243d: the padding test now also runs Transformer, which pools by attention rather than RNN's last step. Both give the same prediction alone and in a padded batch.
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. Task views let one task feed several model families on the same samples, labels and split. The change also adds the dense and event processors and saved subject splits. The design is clear, the description is thorough, and coverage is good: the whole repository is at 86.31% against the 60% bar. Every changed file is above 80% except jamba_ehr.py at 77.33%, which is slightly below.
This touches the core of the codebase, so it can't be approved automatically and a maintainer will need to decide. The core pieces involved are:
BaseTask: new view selection and overrides.BaseModel: theaccepted_viewscheck in its constructor.BaseDataset.set_task: the cache keys.SampleDataset.fit: it now raises an error when a task with views has no split.EmbeddingModel.forward: it now unpacks tuple fields and uses their masks.
All of these are shared by many models and tasks.
To get this merged:
- Update the YAIB task docstrings and any examples that call
set_taskwithoutsplit=. With the defaultjaggedview this now raises aValueError, so those examples would fail as written. Showsplit=in them, for example withSubjectSplit.load_or_draw. - Check
jamba_ehr.py, which is at 77.33% coverage against the 80% guideline. Either add a small test that covers the uncovered lines, or say in the description why they are hard to test.
Optional suggestions:
- Padding invariance is only tested with RNN. A parametrized check over a few more dense models would help.
- The description could briefly say that the breaking
ValueErrorfor YAIB tasks without a split is intended.
Reviewed commit f51ad39
…ents - The YAIB docstring examples draw a saved split and pass it to set_task, which the default view now requires. - view_overrides on a task without views raises, like view= and model=. - SubjectSplit.load_or_draw rejects a split name that is a path. - Padding invariance is also tested on Transformer. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| ), | ||
| }, | ||
| } | ||
| default_view: ClassVar[str] = "jagged" |
There was a problem hiding this comment.
Fixed in 68d243d: all 15 YAIB examples (MIMIC-IV, MIMIC-III, eICU) now draw a saved split with SubjectSplit.load_or_draw and pass it to set_task.
| of the task's views. | ||
| """ | ||
| self._select_view(view, model) | ||
| if view_overrides: |
There was a problem hiding this comment.
Fixed in 68d243d: view_overrides on a task without views now raises the same no-views error as view= and model= (tested).
| Returns: | ||
| The saved split. | ||
| """ | ||
| path = Path(dataset.cache_dir) / "splits" / f"{name}.json" |
There was a problem hiding this comment.
Fixed in 68d243d: load_or_draw rejects a name that is not a plain file name (path separators, '..', '.', empty), tested.
| self.assertEqual(value[:, 1].tolist(), [5.0, 5.0, 5.0]) | ||
| self.assertEqual(mask.tolist(), [1.0, 1.0, 1.0]) | ||
|
|
||
| def test_padding_does_not_change_a_prediction(self): |
There was a problem hiding this comment.
Fixed in 68d243d: the padding test now also runs Transformer, which pools by attention rather than RNN's last step. Both give the same prediction alone and in a padded batch.
|
/review |
| """Writes the patient lists to ``path`` as JSON.""" | ||
| path = Path(path) | ||
| path.parent.mkdir(parents=True, exist_ok=True) | ||
| path.write_text(json.dumps([list(part) for part in self.subjects])) |
There was a problem hiding this comment.
Fixed in 1162e1b: save() writes a temporary file beside the target and os.replace()s it into place, so a concurrent load_or_draw never reads a partial split.
| def __init_subclass__(cls, **kwargs: Any) -> None: | ||
| super().__init_subclass__(**kwargs) | ||
| own = cls.__dict__ | ||
| if "views" in own: |
There was a problem hiding this comment.
Fixed in 1162e1b: a subclass that sets only default_view now gets that view (input_schema recomputed); naming a view that doesn't exist, or setting default_view on a task without views, raises TypeError. Tested.
There was a problem hiding this comment.
Previous review
AI Review
suggestion: approve
decision: human review
Thank you for this contribution. Task views let one task feed many model families on the same cohort, labels and split. The change also adds the dense and event processors and saved SubjectSplit plans. The diff looks correct and complete, and the description matches the code. It looks ready to merge from my side.
Core code touched. This change touches shared base code, so it can't be approved automatically and a maintainer will need to decide. The affected pieces are:
BaseTask: the newviews,view=,model=andview_overrides=arguments, and__init_subclass__.BaseModel.__init__: the newaccepted_viewscheck that every model inherits.SampleBuilder.fit: the newrequire_splitoption.BaseDataset.set_taskand_task_cache_dir: the cache keys shared by all tasks.SubjectSplit: the new draw, save and load methods.EmbeddingModel.forward: it now unpacks tuple fields.
Existing behaviour and cache keys look preserved for tasks without views. Two behaviour changes are stated clearly. Existing YAIB caches rebuild once, and set_task on a YAIB task without split= now raises an error for the jagged and dense views.
Coverage.
- The whole repository is at 86.31%, above the 60% bar.
- Every changed file is at or above 80%, except
jamba_ehr.pyat 77.33%. You explained that your change there is one covered line and the uncovered lines are in code you didn't touch, which is reasonable.
Sharing between components. The links are all named in the description with a reason. dense_processor.py wraps JaggedFeatureProcessor, EmbeddingModel lists the dense processors, and ehr_fm.py imports the event processors.
Optional suggestions:
SubjectSplit.savecould write atomically, via a temporary file and a rename, so an interrupted run never leaves a half-written split.- A subclass that sets only
default_viewwithoutviewsis silently ignored. A clear error would help. - The
events_keydocstring inEHRFoundationModelBasestill says it defaults to "events". It could mention the auto-detection from theeventsview.
Reviewed commit 68d243d
- SubjectSplit.save writes a temporary file and renames it into place. - A subclass that sets only default_view now gets that view; one that names a missing view, or sets default_view without views, raises. - Document how EHRFoundationModelBase finds the events view's fields. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
| """Writes the patient lists to ``path`` as JSON.""" | ||
| path = Path(path) | ||
| path.parent.mkdir(parents=True, exist_ok=True) | ||
| path.write_text(json.dumps([list(part) for part in self.subjects])) |
There was a problem hiding this comment.
Fixed in 1162e1b: save() writes a temporary file beside the target and os.replace()s it into place, so a concurrent load_or_draw never reads a partial split.
| def __init_subclass__(cls, **kwargs: Any) -> None: | ||
| super().__init_subclass__(**kwargs) | ||
| own = cls.__dict__ | ||
| if "views" in own: |
There was a problem hiding this comment.
Fixed in 1162e1b: a subclass that sets only default_view now gets that view (input_schema recomputed); naming a view that doesn't exist, or setting default_view on a task without views, raises TypeError. Tested.
|
/review |
|
|
||
|
|
||
| @register_processor("dense_static") | ||
| class DenseStaticProcessor(_DenseNumeric): |
There was a problem hiding this comment.
Explained in the description rather than switched. TensorProcessor reads a flat list; the YAIB samples hold the static values as a record ({"values": [[...]]}), which is the format every view reads (I checked: TensorProcessor.fit raises TypeError on it). Emitting a flat list instead would change the extraction shared by all views, which this PR keeps fixed. DenseStaticProcessor does no preprocessing of its own: it delegates to JaggedFeatureProcessor, so its values equal the jagged view's by construction.
| if not name or Path(name).name != name or name in (".", ".."): | ||
| raise ValueError(f"Split name must be a plain file name, got {name!r}.") | ||
| path = Path(dataset.cache_dir) / "splits" / f"{name}.json" | ||
| if path.exists(): |
There was a problem hiding this comment.
Fixed in 429d750: save() now records the split the lists were drawn with, and load_or_draw raises ValueError if a split of that name was drawn with a different PatientSplit (tested), rather than returning the old one silently.
| """Returns the birth datetime, or None if the age is missing.""" | ||
| age = float(np.asarray(value["values"], dtype=np.float64)[0, self.age_index]) | ||
| if np.isnan(age): | ||
| return None |
There was a problem hiding this comment.
Fixed in 429d750: test for the None path, and a docstring note that CLMBR then counts ages from the first event. One correction to my own reasoning while doing this: the YAIB cohorts keep stays with a missing or out-of-range age (NaN < 18 is false), so a few samples can hit this; the note says so.
There was a problem hiding this comment.
Previous review
AI Review
suggestion: need change
decision: human review
Thank you for this PR. Task views let one task feed many model families on the same cohort, labels and split. The dense and events processors, the accepted_views check, and the saved SubjectSplit all fit that goal well. The tests are broad. Coverage is good: 86% overall, and every added or modified file is above 80% except jamba_ehr.py at 77%. Your note that this PR adds only one line there, and that the dense-model training test covers it, is reasonable.
This change touches shared core code, so it can't be approved automatically and a maintainer will need to decide. The core pieces are:
BaseTask(the views,__init_subclass__and the constructor).BaseModel(theaccepted_viewscheck in__init__).BaseDataset.set_task(the task cache key and the required-splitfit).SampleDataset.- The shared
EmbeddingModel, which many models use. SubjectSplit.
The set_task change to a hard error without a split affects existing YAIB users. You describe it clearly, which helps.
To get this merged:
DenseStaticProcessorlooks close to the existingTensorProcessor. Withnormalization="zscore",missing_indicators=Trueandimpute_strategy="zero",TensorProcessorshould give a similar static vector. The description explains whyTimeseriesProcessorisn't reused, but it doesn't mentionTensorProcessor. Please say in the description why a new processor is needed. For example,TensorProcessormay not read the{"values": [[...]]}records with NaN, or the dense processors may need to match thejaggedvalues exactly. Or reuseTensorProcessorif it fits.
Optional suggestions:
load_or_drawsilently ignores a differentPatientSplitwhen a saved split of that name exists. A warning would help, or a check that the saved split's shape matches the one given.- Add a test for
EventBirthProcessorwith a missing age. Its docstring covers that case, but the tests don't. - Consider a short docs note that
jaggedanddensenow needsplit=inset_task.
Reviewed commit 1162e1b
- SubjectSplit.save records the split the lists were drawn with, and load_or_draw raises if a split of that name was drawn with a different one, instead of silently returning the old split. - EventBirthProcessor documents that a missing age leaves CLMBR counting ages from the first event, and that YAIB cohorts can contain such stays; the None path is tested. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
|
||
|
|
||
| @register_processor("dense_static") | ||
| class DenseStaticProcessor(_DenseNumeric): |
There was a problem hiding this comment.
Explained in the description rather than switched. TensorProcessor reads a flat list; the YAIB samples hold the static values as a record ({"values": [[...]]}), which is the format every view reads (I checked: TensorProcessor.fit raises TypeError on it). Emitting a flat list instead would change the extraction shared by all views, which this PR keeps fixed. DenseStaticProcessor does no preprocessing of its own: it delegates to JaggedFeatureProcessor, so its values equal the jagged view's by construction.
| if not name or Path(name).name != name or name in (".", ".."): | ||
| raise ValueError(f"Split name must be a plain file name, got {name!r}.") | ||
| path = Path(dataset.cache_dir) / "splits" / f"{name}.json" | ||
| if path.exists(): |
There was a problem hiding this comment.
Fixed in 429d750: save() now records the split the lists were drawn with, and load_or_draw raises ValueError if a split of that name was drawn with a different PatientSplit (tested), rather than returning the old one silently.
| """Returns the birth datetime, or None if the age is missing.""" | ||
| age = float(np.asarray(value["values"], dtype=np.float64)[0, self.age_index]) | ||
| if np.isnan(age): | ||
| return None |
There was a problem hiding this comment.
Fixed in 429d750: test for the None path, and a docstring note that CLMBR then counts ages from the first event. One correction to my own reasoning while doing this: the YAIB cohorts keep stays with a missing or out-of-range age (NaN < 18 is false), so a few samples can hit this; the note says so.
|
/review |
| samples: Sample dictionaries; with a split, the training part. | ||
| field: Key of the field in each sample. | ||
| """ | ||
| for sample in samples: |
There was a problem hiding this comment.
[low] Fit loop consumes one-shot iterables before the inner processor fits
_DenseNumeric.fit iterates samples to find the feature count, then breaks and passes the same iterable to self.jagged.fit(samples, field) on line 77. If samples is a one-shot iterator, the first non-empty sample is consumed and the inner jagged processor never sees it, so the imputation means and scales are wrong. The library's own callers pass re-iterable objects, so this is latent. Fix by deriving the feature count from the jagged processor's fit, or by fitting on a materialized list when the input is not re-iterable.
|
|
||
| @register_processor("dense_series") | ||
| class DenseSeriesProcessor(_DenseNumeric): | ||
| """A numeric time series as a ``[T, F]`` tensor with a ``[T]`` step mask. |
There was a problem hiding this comment.
[low] DenseSeriesProcessor docstring gives shape [T, F] but default output is [T, 2F]
With the default missing_indicator=True, process returns values of width 2F (values plus one indicator per feature), as the doctest in this class shows. The summary line says [T, F]. Say [T, F] before indicators, or [T, 2F] with the default, so users size their models correctly. The same applies to the docs/api page for this class.
|
|
||
| @register_processor("dense_static") | ||
| class DenseStaticProcessor(_DenseNumeric): | ||
| """A single numeric record as an ``[F]`` tensor. |
There was a problem hiding this comment.
[low] DenseStaticProcessor docstring gives shape [F] but default output is [2F]
Like DenseSeriesProcessor, the default missing_indicator=True makes process return [2F], not [F]. Correct the summary line, and the matching sentence in docs/api/processors/pyhealth.processors.DenseStaticProcessor.rst, to state the width with and without indicators.
There was a problem hiding this comment.
AI Review
suggestion: approve
decision: human review
Thank you for this contribution. Task views let one task feed many model families on fixed samples, labels and splits. You also added the dense and event processors, saved SubjectSplit plans, and accepted_views on models.
The diff looks correct and complete. The description explains the sharing between components: the dense processors wrap JaggedFeatureProcessor, EmbeddingModel lists the dense processors, and EHRFoundationModelBase finds the event processors. The three YAIB files stay self-contained, and a test checks that their views match. The docs match the code. Coverage meets the bar. The whole repository is at 86.3%, and every changed file is at or above 80% except jamba_ehr.py at 77%. You explained that one: the PR adds a single covered line there, and the uncovered lines are existing code.
This touches the core part of the codebase, so a maintainer needs to review it rather than have it approved automatically:
BaseTaskgains view selection and__init_subclass__behavior that every task inherits.BaseModel.__init__gains a view check that every model runs.BaseDataset.set_taskand_task_cache_dirchange how cache keys are built.SampleDataset.fitgains arequire_spliterror.- The
EmbeddingModelforward path changes for fields that arrive as(value, mask)tuples. SubjectSplitgains new methods and a shorter warning message.
Optional suggestions:
- Add a
set_taskround trip with the real YAIBdenseandeventsviews. - Build
CLMBRin a test for theeventsview, since the description names it. - The
BaseTaskdocstring says a subclass has its own cache. The key is built from the task name and attributes, so a subclass with the sametask_nameshares it. Consider rewording.
Reviewed commit 429d750
What this does
A task can now offer several views: named input schemas over the same samples. The task still defines the cohort, prediction time, label and measurements once. A view only decides how those measurements become model input, so different model families can run on the same task without the task being rewritten per model.
The rule the design enforces: for a given patient population, the extracted features and the splits are fixed; everything else may vary per model.
Why
In the task x model compatibility run on master (18 MIMIC tasks x 21 models), 148 of 378 pairs crash, and the YAIB tasks run with exactly one model (
RNN_V2). The largest group, 65 crashes, is "input type not handled": a task fixes one tensor layout ininput_schema, and every model has to carry code for every layout.Changes
Tasks (
pyhealth/tasks/base_task.py)BaseTaskgains optionalviewsanddefault_view, andview=/model=/view_overrides=constructor arguments. No new task base class and no new module. A task withoutviewsbehaves exactly as before.view_overrideschanges processor settings (or swaps a processor) field by field,view=accepts a whole input schema, and a subclass can add a named view. Every version gets its own processed cache and reads the task's one cache of samples.Three views for the YAIB tasks
jagged(default)RNN_V2dense(value [T, F], mask [T])and a static vectorevents(time, code, value, unit)event per measured value, plus birth timeHFEHRFoundationModel,CLMBRjaggedanddensehold identical values (tested); they differ only in layout.eventscarries the same measurements with nothing imputed or scaled.Splits and caching (
pyhealth/datasets/)SubjectSplitgainsdraw,save,loadandload_or_draw: a seeded split is fixed once as patient lists over all patients of a dataset and saved, so every task and every view puts a patient in the same part, even when task cohorts differ. Its missing-subject warning now gives a count and a few ids instead of every id.task_df.ld; each view gets its own processed samples. The task cache key is master's, except that for a task with views the input schema moves from the task key to the processed-samples key. Changing a processor setting therefore re-runs only the processing, not the cohort extraction.split=is now an error instead of a warning.Models (
pyhealth/models/)BaseModel.accepted_views: the view names a model reads.Task(model=M)uses it, and building a model on a dataset of another view raises an error naming the view to use.EmbeddingModelunpacks a field it embeds from its processor's(value, mask)tuple byschema(), and uses the given mask instead of guessing padding from zeros, so a standardized value of 0 is no longer read as padding. Fields it does not embed are passed through as their whole tuple, as before.EmbeddingModellistsDenseSeriesProcessorandDenseStaticProcessoramong the numeric processors it gives a linear layer. That is intended: it chooses each field's layer by processor class, and every numeric processor (TimeseriesProcessor,NestedFloatsProcessor,StageNetTensorProcessor, ...) is listed the same way.DenseSeriesProcessorandDenseStaticProcessordo no preprocessing of their own: an innerJaggedFeatureProcessorimputes and scales, and they only reshape its output into padded tensors with a step mask.TimeseriesProcessoris not reused because it resamples(timestamps, values)input onto its own grid, while the YAIB samples are already hourly records withNaNfor missing values.TensorProcessoris not reused for the static field because it reads a flat list, while the YAIB samples hold the static values as a record ({"values": [[...]]}), the format every view reads. Changing that format would change the extraction for all views, which this PR keeps fixed. Delegating toJaggedFeatureProcessoralso makes the dense values equal thejaggedones by construction.EHRFoundationModelBasefinds the event and birth fields of theeventsview without being told their keys.eventsrelates toEHRFoundationModelTask: that task builds the same(time, code, value, unit)timeline, but from a patient's raw events, so a foundation model sees everything recorded. Theeventsview builds it from the YAIB task's own hourly measurements, so a foundation model sees exactly the features the other views do, on the same cohort, labels and split. The two are complementary; this PR does not changeEHRFoundationModelTask.How this addresses the issues discussed
dense, 2 foundation models viaevents. Wrong pairings now give one actionable error.SubjectSplitfixes the split across tasks and views.EmbeddingModel; models that compute their own masks are unchanged.RNN_V2(dataset)builds with default embedding sizes.Behaviour changes
jaggedprocessor name instead of the deprecatedsequence_v2alias. Their configuration is otherwise equal to master.input_schema(survival, acuity, KnowRare) does not inherit the YAIB views.set_taskon a YAIB task withoutsplit=now raises aValueErrorfor the defaultjaggedview (and fordense), because their processors learn statistics. It used to log a warning. Theeventsview learns nothing and still works without a split. This is intended: models are only comparable if no view learns from validation or test patients. The YAIB docstring examples now pass a split.Testing
tests/core/test_task_views.py(including a check that MIMIC-IV, MIMIC-III and eICU define all three views alike): 29 tests covering view selection and errors, view overrides,set_taskend to end (shared task cache, same samples/labels/split across views, train-only fitting), dense/jagged value equality, padding invariance, one training step for each of the 17densemodels, and a foundation model oneventswith full vocabulary coverage (skipped whentransformersis not installed).tests/core/test_embedding_model_padding.py: a passed-through tuple field stays whole, and an embedded(value, mask)field uses its own mask.tests/core/test_subject_split.py: drawing, saving and loading a split, and a smaller cohort keeping each patient's part.Coverage note:
jamba_ehr.pyis at 77% against the 80% guideline. This PR adds one line there (accepted_views), which the dense-model training test covers; the uncovered lines are in code this PR does not touch.Limits and follow-ups
RNN_V2; thedensemodels have no per-step head.eventscodes default toYAIB/<feature>, which no pretrained vocabulary knows. A verified feature-to-code table per model vocabulary is needed (set throughview_overrides); no pretrained checkpoint was run. Sex, height and weight are not in the timeline.denseyet.tabularview for tree models, k-fold split plans, survival labels for generic models, and the nightly task x view x model matrix. AutomaticRNN_V2settings are in RNN_V2: build from the dataset alone with default embedding sizes #1591.🤖 Generated with Claude Code