Skip to content

Task views: run one task with many model families on fixed features and splits - #1590

Open
jhnwu3 wants to merge 12 commits into
masterfrom
refactor/task-views
Open

jhnwu3 wants to merge 12 commits into
masterfrom
refactor/task-views

Conversation

@jhnwu3

@jhnwu3 jhnwu3 commented Nov 23, 2026 •

Copy link
Copy Markdown
Collaborator

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.

split = SubjectSplit.load_or_draw(dataset, "seed0", PatientSplit((0.8, 0.1, 0.1), seed=0))

task = YAIBMortalityMIMIC4()                             # default view, same tensors as before
task = YAIBMortalityMIMIC4(view="dense")                 # a view by name
task = YAIBMortalityMIMIC4(model=Transformer)            # the view Transformer reads
task = YAIBMortalityMIMIC4(model=HFEHRFoundationModel)   # the view the foundation models read
task = YAIBMortalityMIMIC4(view="dense",                 # your own version of a view
                           view_overrides={"dynamic": {"normalize": False}})

train, val, test = dataset.set_task(task, split=split)
model = Transformer(train)

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 in input_schema, and every model has to carry code for every layout.

Changes

Tasks (pyhealth/tasks/base_task.py)

  • BaseTask gains optional views and default_view, and view= / model= / view_overrides= constructor arguments. No new task base class and no new module. A task without views behaves exactly as before.
  • Each task is self-contained: its views are plain input schemas written in the task file. The three YAIB files (MIMIC-IV, MIMIC-III, eICU) each define the same three views, and a test fails if they drift apart.
  • Users can define their own version of a view: view_overrides changes 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

View What the model receives Read by
jagged (default) Record structures, as today RNN_V2
dense Padded (value [T, F], mask [T]) and a static vector RNN, MultimodalRNN, TCN, Transformer, RETAIN, MultimodalRETAIN, MultimodalAdaCare, GRASP, Agent, JambaEHR, StageNet, MLP, LogisticRegression, KnowRare, BEHRT, BiteNet, UDC
events One (time, code, value, unit) event per measured value, plus birth time HFEHRFoundationModel, CLMBR

jagged and dense hold identical values (tested); they differ only in layout. events carries the same measurements with nothing imputed or scaled.

Splits and caching (pyhealth/datasets/)

  • SubjectSplit gains draw, save, load and load_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.
  • All views of a task share one cached 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.
  • For a task with views, fitting a statistics-learning processor without 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.
  • EmbeddingModel unpacks a field it embeds from its processor's (value, mask) tuple by schema(), 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.
  • EmbeddingModel lists DenseSeriesProcessor and DenseStaticProcessor among 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.
  • DenseSeriesProcessor and DenseStaticProcessor do no preprocessing of their own: an inner JaggedFeatureProcessor imputes and scales, and they only reshape its output into padded tensors with a step mask. TimeseriesProcessor is not reused because it resamples (timestamps, values) input onto its own grid, while the YAIB samples are already hourly records with NaN for missing values. TensorProcessor is 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 to JaggedFeatureProcessor also makes the dense values equal the jagged ones by construction.
  • EHRFoundationModelBase finds the event and birth fields of the events view without being told their keys.
  • How events relates to EHRFoundationModelTask: that task builds the same (time, code, value, unit) timeline, but from a patient's raw events, so a foundation model sees everything recorded. The events view 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 change EHRFoundationModelTask.

How this addresses the issues discussed

Issue Status in this PR
Input type not handled (65 crashes; YAIB ran with 1 model) Addressed for the YAIB per-stay tasks: 17 sequence models via dense, 2 foundation models via events. Wrong pairings now give one actionable error.
No guarantee that models are compared on the same cohort, labels and split Addressed: views share the task's samples and labels by construction, and a saved SubjectSplit fixes the split across tasks and views.
Leakage from fitting on all samples Addressed for tasks with views (hard error without a split).
Padding inferred from zeros Addressed centrally in EmbeddingModel; models that compute their own masks are unchanged.
Cache reuse after cohort edits; representation changes re-running the cohort Addressed for tasks with views.
Hard-coded field names (48 crashes) Not a naming problem: every drug recommendation task already uses the names SafeDrug, GAMENet, MoleRec and ARMR expect. These are the drug models run on tasks that are not drug recommendation, which a CI matrix should list as not applicable.
Needs per-field config (18 crashes) In #1591, stacked on this PR: RNN_V2(dataset) builds with default embedding sizes.
Only one prediction (17 crashes) Not yet.

Behaviour changes

  • Existing YAIB caches rebuild once (their cache key changed).
  • MIMIC-III and eICU YAIB tasks use the jagged processor name instead of the deprecated sequence_v2 alias. Their configuration is otherwise equal to master.
  • A subclass that sets its own input_schema (survival, acuity, KnowRare) does not inherit the YAIB views.
  • set_task on a YAIB task without split= now raises a ValueError for the default jagged view (and for dense), because their processors learn statistics. It used to log a warning. The events view 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_task end 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 17 dense models, and a foundation model on events with full vocabulary coverage (skipped when transformers is 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.
  • YAIB input schemas compared against master for all three datasets: equal.
  • Existing YAIB, split, caching, processor, model and docs suites pass locally.

Coverage note: jamba_ehr.py is 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

  • All checks use synthetic or demo-sized data. The compatibility matrix has not been re-run, and nothing here measures model quality.
  • Per-hour tasks (AKI, sepsis, length of stay) still run only with RNN_V2; the dense models have no per-step head.
  • events codes default to YAIB/<feature>, which no pretrained vocabulary knows. A verified feature-to-code table per model vocabulary is needed (set through view_overrides); no pretrained checkpoint was run. Sex, height and weight are not in the timeline.
  • AdaCare, ConCare, EHRMamba, Deepr, GCN, GAT, CNN, StageAttentionNet and MAESTRO do not read dense yet.
  • Not in this PR: a tabular view for tree models, k-fold split plans, survival labels for generic models, and the nightly task x view x model matrix. Automatic RNN_V2 settings are in RNN_V2: build from the dataset alone with default embedding sizes #1591.

🤖 Generated with Claude Code

jhnwu3 and others added 3 commits November 23, 2026 12:01
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>
@jhnwu3 jhnwu3 added the status: manual Pending maintainer's review label Nov 23, 2026
@jhnwu3

jhnwu3 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

/review

jhnwu3 and others added 2 commits November 23, 2026 13:30
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>
jhnwu3 and others added 2 commits November 23, 2026 14:05
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>
@github-actions

github-actions Bot commented Nov 23, 2026 •

Copy link
Copy Markdown

Test Coverage

Total: 86.32% (45657 / 52895 lines)

Modified file Coverage Lines
pyhealth/datasets/base_dataset.py 93.26% 540 / 579
pyhealth/datasets/sample_dataset.py 95.12% 351 / 369
pyhealth/datasets/splitter.py 97.18% 413 / 425
pyhealth/models/adacare.py 89.17% 214 / 240
pyhealth/models/agent.py 93.13% 244 / 262
pyhealth/models/base_model.py 97.83% 45 / 46
pyhealth/models/behrt.py 94.92% 187 / 197
pyhealth/models/bitenet.py 94.10% 255 / 271
pyhealth/models/ehr_fm.py 92.12% 304 / 330
pyhealth/models/embedding.py 85.31% 122 / 143
pyhealth/models/grasp.py 92.41% 207 / 224
pyhealth/models/jamba_ehr.py 77.33% 116 / 150
pyhealth/models/knowrare.py 98.06% 303 / 309
pyhealth/models/logistic_regression.py 81.63% 80 / 98
pyhealth/models/mlp.py 84.03% 121 / 144
pyhealth/models/retain.py 90.06% 154 / 171
pyhealth/models/rnn.py 94.86% 351 / 370
pyhealth/models/stagenet.py 96.14% 199 / 207
pyhealth/models/tcn.py 96.61% 114 / 118
pyhealth/models/transformer.py 90.28% 195 / 216
pyhealth/models/udc.py 92.77% 231 / 249
pyhealth/processors/__init__.py 95.92% 47 / 49
pyhealth/processors/dense_processor.py 90.79% 69 / 76
pyhealth/processors/event_processor.py 87.76% 43 / 49
pyhealth/tasks/base_task.py 92.78% 90 / 97
pyhealth/tasks/yaib_eicu.py 91.99% 643 / 699
pyhealth/tasks/yaib_mimic3.py 92.97% 582 / 626
pyhealth/tasks/yaib_mimic4.py 93.17% 532 / 571

Workflow run · 429d750

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 9ba08dd

from .base_processor import LegacyFeatureProcessor


class _DenseNumeric(LegacyFeatureProcessor):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: new views, default_view, view=, model= and view_overrides=.
  • BaseModel: the new accepted_views check in __init__.
  • BaseDataset.set_task and its cache keys.
  • SampleDataset.fit, save and load.
  • 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:

  1. dense_processor.py re-implements forward fill, z-score scaling and missing indicators, which JaggedProcessor and TimeseriesProcessor already do. Please explain in the description why a separate processor is needed. Or reuse or extend the existing ones if that is simpler.
  2. EmbeddingModel now imports and special-cases DenseSeriesProcessor and DenseStaticProcessor. It also unpacks any (value, mask) tuple through schema(). Please say in the description that this link is intended, and why.
  3. EmbeddingModel.forward now 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_task without split= 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 transformers is 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"]

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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,

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jhnwu3

jhnwu3 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit a5d9b5a

Comment thread tests/core/test_task_views.py Outdated

for other in (YAIBMortalityMIMIC3, YAIBMortalityEICU):
self.assertEqual(sorted(other.views), sorted(YAIBMortalityMIMIC4.views))
for view in ("jagged", "dense"):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  1. The description says a test fails if the three YAIB task files drift apart. test_the_three_datasets_define_the_same_views only compares the jagged and dense views. Please also compare events, for example the processor names and the settings other than the feature names. Alternatively, change the description to say that only jagged and dense are checked.

Optional suggestions:

  • EHRFoundationModelTask already builds a similar (time, code, value, unit) timeline. A sentence in the description on how the events view 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_draw docstring would make that clear.
  • jamba_ehr.py is 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>
Comment thread tests/core/test_task_views.py Outdated

for other in (YAIBMortalityMIMIC3, YAIBMortalityEICU):
self.assertEqual(sorted(other.views), sorted(YAIBMortalityMIMIC4.views))
for view in ("jagged", "dense"):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jhnwu3

jhnwu3 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit f51ad39

),
},
}
default_view: ClassVar[str] = "jagged"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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: the accepted_views check 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:

  1. Update the YAIB task docstrings and any examples that call set_task without split=. With the default jagged view this now raises a ValueError, so those examples would fail as written. Show split= in them, for example with SubjectSplit.load_or_draw.
  2. 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 ValueError for 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"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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"

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jhnwu3

jhnwu3 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 68d243d

Comment thread pyhealth/datasets/splitter.py Outdated
"""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]))

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pyhealth/tasks/base_task.py Outdated
def __init_subclass__(cls, **kwargs: Any) -> None:
super().__init_subclass__(**kwargs)
own = cls.__dict__
if "views" in own:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 new views, view=, model= and view_overrides= arguments, and __init_subclass__.
  • BaseModel.__init__: the new accepted_views check that every model inherits.
  • SampleBuilder.fit: the new require_split option.
  • BaseDataset.set_task and _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.py at 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.save could 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_view without views is silently ignored. A clear error would help.
  • The events_key docstring in EHRFoundationModelBase still says it defaults to "events". It could mention the auto-detection from the events view.

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>
Comment thread pyhealth/datasets/splitter.py Outdated
"""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]))

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread pyhealth/tasks/base_task.py Outdated
def __init_subclass__(cls, **kwargs: Any) -> None:
super().__init_subclass__(**kwargs)
own = cls.__dict__
if "views" in own:

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jhnwu3

jhnwu3 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Previous review

Reviewed commit 1162e1b



@register_processor("dense_static")
class DenseStaticProcessor(_DenseNumeric):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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():

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@github-actions github-actions Bot left a comment •

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 (the accepted_views check in __init__).
  • BaseDataset.set_task (the task cache key and the required-split fit).
  • 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:

  • DenseStaticProcessor looks close to the existing TensorProcessor. With normalization="zscore", missing_indicators=True and impute_strategy="zero", TensorProcessor should give a similar static vector. The description explains why TimeseriesProcessor isn't reused, but it doesn't mention TensorProcessor. Please say in the description why a new processor is needed. For example, TensorProcessor may not read the {"values": [[...]]} records with NaN, or the dense processors may need to match the jagged values exactly. Or reuse TensorProcessor if it fits.

Optional suggestions:

  • load_or_draw silently ignores a different PatientSplit when 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 EventBirthProcessor with a missing age. Its docstring covers that case, but the tests don't.
  • Consider a short docs note that jagged and dense now need split= in set_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):

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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():

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@jhnwu3

jhnwu3 commented Nov 23, 2026

Copy link
Copy Markdown
Collaborator Author

/review

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reviewed commit 429d750

samples: Sample dictionaries; with a split, the training part.
field: Key of the field in each sample.
"""
for sample in samples:

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

  • BaseTask gains view selection and __init_subclass__ behavior that every task inherits.
  • BaseModel.__init__ gains a view check that every model runs.
  • BaseDataset.set_task and _task_cache_dir change how cache keys are built.
  • SampleDataset.fit gains a require_split error.
  • The EmbeddingModel forward path changes for fields that arrive as (value, mask) tuples.
  • SubjectSplit gains new methods and a shorter warning message.

Optional suggestions:

  • Add a set_task round trip with the real YAIB dense and events views.
  • Build CLMBR in a test for the events view, since the description names it.
  • The BaseTask docstring says a subclass has its own cache. The key is built from the task name and attributes, so a subclass with the same task_name shares it. Consider rewording.

Reviewed commit 429d750

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

status: manual Pending maintainer's review

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant