Skip to content

Tranche 1: 29 commits for commit-by-commit review - #56

Open
rianfyi wants to merge 29 commits into
tranche1_finalfrom
tranche1_final-commits
Open

rianfyi wants to merge 29 commits into
tranche1_finalfrom
tranche1_final-commits

Conversation

@rianfyi

@rianfyi rianfyi commented Nov 5, 2026 •

Copy link
Copy Markdown

Tranche 1, split into 29 small commits for review one at a time. Please use the Commits tab: each commit makes one change and has its own tests.

This branch is rebased onto upstream master 59890580 (earlier base 2c9dfacf). Upstream master has since moved to 0181aa2f; this series stays on 59890580 for review, and upstream PRs will be cut from current master when they are opened. tranche1_final is unmodified upstream at 2c9dfacf until the rebased series is pushed, so this diff holds only these 29 commits. Nothing here goes upstream yet. Upstream PR 1185 stays open as it is.

Commits

"Earlier review" is the verdict on the matching commits in upstream PR 1185: ✅ approved, ✅ partial = only some source commits approved, ⏸ asked for another reviewer, ? questioned, — not reviewed. "Default change" is what an existing user who passes no new arguments sees.

Infrastructure and precision

# Commit Subject Earlier review Default change
1 b4a3935 Add mixed precision and gradient accumulation to Trainer ✅ partial —
2 e35de64 Fill attention masks with dtype min and use fused SDPA ⏸ Joshua to review Fused SDPA on ordinary forwards; equal at valid positions
3 2d4d5f6 Test the DataLoader worker options that get_dataloader forwards — —
4 4bd7a58 Allow skipping the Dask distributed cluster for event caching — —

Processors and unified embedding

# Commit Subject Earlier review Default change
5 5b68490 Return zero-length sequences for empty modalities ✅ Empty inputs give length-0 tensors, not a placeholder or an error
6 9ff3240 Clean note rows and pad per-sample longest in the tuple text processor ✅ Padding width is per sample
7 051591f Give time embeddings a 10-year multi-scale span ✅ New time embedding; upstream test values updated
8 7c002d1 Reuse unimodal encoders and pool patch image tokens in the unified model — —
9 2f92a79 Flatten nested code events and expose the content embedding — —
10 764ebea Standardize numerics before projection and bound the content scale ✅ partial normalize_content=True layer-norms content; padded slots zeroed
11 c6137bd Keep frozen text encoders in eval when Trainer calls train() ✅ —
12 080e059 Avoid ambiguous -1 reshapes on batches with no note or image slots — —
13 4ad3d11 Cache frozen [CLS] embeddings keyed on real tokens, not padded rows ✅ —
14 442b9e3 Encode a frozen-cache miss once per forward, even when the cache is full — —
15 8b66532 Cap the frozen text cache and expose hit/miss counters — —

Backbones and collation

# Commit Subject Earlier review Default change
16 96cb41f Add unified-embedding mode to the Transformer — —
17 11dccb8 Add unified-embedding mode to EHRMamba — —
18 0ae79f5 Add unified-embedding mode to JambaEHR — —
19 472e7e3 Add unified-embedding mode to the RNN — —
20 5acaba4 Collate ragged processor tuples positionally so text batches stack — Text batches stack per tuple position through the processor's collate(); 2-tuple output unchanged except that ragged trailing dimensions are now padded; other tuple arities stay per-sample lists
21 88090ec Emit batch pad masks from the legacy collators ⏸ Batches gain {field}__pad_mask for ragged 2-tuple fields and text fields
22 f38fe3d Skip collate padding in the unified sequence ⏸ —
23 adbae11 Thread collate pad_mask through the unified MLP path ✅ —

Models, processors, tasks, runner

# Commit Subject Earlier review Default change
24 584b597 Add BottleneckTransformer model with unified-embedding mode — —
25 abbfdbf Let StageNetTensorProcessor skip forward fill for observation masks — —
26 e577533 Scan past empty samples when fitting StageNet processors — Bug fix: fitting no longer stops at the first sample
27 b2fd2f0 Add NotesLabsMIMIC4 and LabsMIMIC4 multimodal tasks ✅ partial —
28 5f53fa7 Share one observation window across modalities, default 0 = off ? (decided: 0 = off) —
29 ffe267d Add unified-embedding e2e runner with cache and timing flags — —

Changed by the rebase

  • Item 3 is now tests only: upstream already forwards the DataLoader options through **loader_kwargs, so the argument checks were dropped. Its subject changed to "Test the DataLoader worker options that get_dataloader forwards."
  • Items 16 to 19, 23 and 24: the label API moved to upstream's label_processor. Items 16 to 19, 23 and 24 compute the loss only when the label key is present, as the per-field path does. Item 24 no longer assigns self.mode.
  • Item 4: the local-scheduler branch uses upstream's dev-mode cap, and the flag also reaches the ed sub-dataset. The equivalence test is tie-aware: the fixture repeats one patient_id, each path's output is first checked to be sorted by patient_id, and the two frames are then compared after a stable sort on (patient_id, _source_row).
  • Item 20 was redesigned. Positional stacking now lives in the text processor's collate(), which get_dataloader uses as the field collator, as upstream does. The generic collator batches 2-tuples only and pads every ragged dimension. Other tuple arities stay per-sample lists, so the 3-tuple image processors and the unified bridge keep the shape they expect. Item 21 adds {field}__pad_mask for ragged 2-tuple fields and text fields.

Decisions already made

  • Item 2: Joshua reviews.
  • Item 4: a constructor argument, use_dask_distributed, instead of an environment variable. This is the only code rewritten for this PR. The runner gets --no-dask-distributed.
  • Item 10: normalize_content is on by default.
  • Item 28: the observation window defaults to 0 = off.

Please read before reviewing item 28

window_hours=0 keeps the full stay through discharge, so mortality features can include data up to discharge or death. That is the agreed default, but it isn't a prediction-from-a-fixed-point setup, and any result from it has to say so. Pass a positive --observation-window-hours for that. The window caps labs and radiology notes at the same point. Discharge-note sections stay unbounded by design.

Verification

  • CI rules: tools/check_pr_rules.py passes on each of the 29 commits (exit 0, ruff 0.17.6), each run with that commit checked out.
  • Per commit: cumulative series tests after the rebase, one run per commit, excluding tests/core/test_tuple_time_text_tokenizer.py (it needs a tokenizer download). Counts at commits 1, 15 and 29: 13, 119 and 181 passed, with no failures at any commit in the series.
  • Targeted run (31 tests): the files that failed at the first version of commit 20 (test_dipro, test_disease_progression_mimic4, test_time_region_image_processor, test_unified_bridge, test_time_image_processor, test_stagenet_processor): 278 passed, 0 failed at commit 20; 285 passed, 0 failed at the tip.
  • Full suite, CPU, same environment: upstream 59890580: 16 failed, 4165 passed. Tip ffe267d0: 20 failed, 4291 passed. Against the upstream failing set, the tip has four extra failures, all in tests/core/test_lime.py (three TestLimeExplainerMLP tests and one TestLimeExplainerStageNet basic_attribution test). LIME is randomized and flaky in both directions; the same four pass on the three later tips. Run alone on the same server, test_lime.py passed all 34 tests twice on this tip and once on upstream 59890580. The 31 failures from the first version of commit 20 are gone.
  • Real MIMIC-IV: pending. The smoke runs on the rebased tip (labs and notes_labs with --dev 1000, and the notes_labs cache ON/OFF pair) have not run, because all eight GPUs on the lab server were busy and both GPU pools were fully claimed. A watcher starts them when two GPUs are free. The figures below were measured on earlier trees.
  • GPU checks, run on an earlier build and not repeated here: fp16 and bf16 with gradient accumulation stay finite. Fused against explicit attention has a max diff of 0, 2e-4 and 1e-3 in fp32, fp16 and bf16. An all-padding sample gives zero output.

Cache A/B

Full notes_labs, 180,733 samples, Transformer 128 dims and 2 layers, frozen Bio_ClinicalBERT, bf16, seed 1, 3 epochs, full stay (window 0), one RTX 6000 Ada per arm. Two runs, each on its own tree.

Earlier build 966a658b (W6, not pushed):

Train epoch 1 (cold) Train epoch 2 (warm) Train epoch 3 (warm) Test inference
Cache off 1712 s 1718 s 1708 s 530 s
Cache on 1682 s 439 s 429 s 45 s
Off / on 1.02× 3.92× 3.98× 11.7×

Final tree a4337a4f (X8; the stats tip of the pre-rebase stack, whose cache, collate and model code matched this PR's pre-rebase tip):

Train epoch 1 (cold) Train epoch 2 (warm) Train epoch 3 (warm) Test inference
Cache off 1629 s 1629 s 1618 s 504 s
Cache on 1666 s 544 s 519 s 54 s
Off / on 0.98× 2.99× 3.12× 9.3×

Across the two runs, the cache is roughly 3–4× faster per warm epoch and 9–12× faster for test inference.

Train losses were identical to 4 decimals in every epoch, between the two arms, on both measured trees. Test PR-AUC differed by 0.0003 on 966a658b and by 0.0007 on a4337a4f. This is one seed and one backbone, on the default full-stay window.

The rebased tip changes the measured path: commit 20 moved text-batch stacking into the processor's collate(), and upstream 2afbdaef changes event order and c210ab2d the trainer's eval path. The figures therefore apply to the measured trees (966a658b and a4337a4f) and have not been re-measured on the rebased tree.

Not in this PR

  • Moved to later: "Skip optimizer steps with non-finite gradients", "Bound trainable text-encoder memory with checkpointing and chunked rows", and "Fit lab z-scores on observed train rows". Item 10's numeric_standardizers hook stays, but nothing plugs into it until the z-score commit lands.
  • CXR: Joshua's.
  • Systems: a separate PR on top of this one.

https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95

Validates amp_dtype (unknown spellings raise), follows the trainer device
for autocast, and steps every accumulation_steps batches with GradScaler
for fp16. With use_amp=False the step matches upstream: clip only when
max_grad_norm is set, with no unconditional grad-norm pass and no skipping.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
The -1e9 fill overflows fp16 under AMP; the explicit path behind
register_hook fills with finfo(dtype).min instead. Ordinary forwards
use scaled_dot_product_attention; rows whose keys are all masked (an
all-padded sample) attend uniformly and are zeroed by the query mask,
so the fused path stays finite. Interpretability readers only see the
explicit path, where attn_map and gradients are still captured.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Upstream already forwards these options through **loader_kwargs (sunlabuiuc#1280),
so get_dataloader is unchanged here. This commit adds the tests that keep
that path working: defaults, pass-through to the seeded loader, seeded
shuffles with two workers covering every sample once, and the invalid
combinations that PyTorch's DataLoader rejects (num_workers < 0,
persistent_workers without workers, prefetch_factor without workers).
The argument checks from the first version of this commit duplicated
DataLoader and are dropped. prefetch_factor=0 is not rejected at
construction, so it is not tested.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
BaseDataset takes use_dask_distributed=True. False writes the event cache
with the local Dask scheduler instead of starting a distributed cluster,
for sandboxes where the cluster cannot start. True keeps the distributed
path unchanged. The flag does not affect the cache key. A synthetic
end-to-end run shows both paths write the same cache contents.

The local branch gets the dev-mode fix from upstream 7722dc8
(unique().head(1000, npartitions=-1)): head() reads only the first
partition unless told otherwise. MIMIC4Dataset passes the flag to the ED
sub-dataset that upstream added after the original commit.

Both paths sort by patient_id. Rows that share a patient_id can still
come out in a different order from each scheduler. The equivalence test
checks that each path's output is sorted by patient_id, then compares the
frames after a stable sort on (patient_id, _source_row); the fixture
repeats a patient_id so that case is covered. The order does not change
samples: Patient sorts events by (timestamp, event_type, _source_row)
(upstream 2afbdae), and _source_row is unique per row, so the row order
the cache keeps within a patient does not reach the samples.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Empty code lists, lab series, and image lists now encode as zero-length tensors instead of a fake pad token, pad visit, or black frame, so missingness is visible to the mask logic instead of looking like a real event.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Malformed texts and unparseable timestamps are dropped with their times, empty note lists return zero-length tensors, tokenization pads to the longest note in the sample bounded by max_length (default now 512), and missing tokenizer fields fall back instead of raising KeyError.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Wavelengths are now log-spaced from 1 hour to 10 years instead of normalizing every frequency by 720 hours, which aliased any stay past 30 days onto the first. The model default follows the new span.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
…del.

Fields accept pre-built EmbeddingModel, VisionEmbeddingModel, or TextEmbedding modules through field_embeddings instead of always training new encoders. The default image encoder is now PatchEmbedding with mean pooling, matching VisionEmbeddingModel, replacing the resnet18 stub.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
A (B, S, C) code field now encodes to (B, S*C, E) with time and mask expanded along the codes instead of failing on the 3D input. Forward also returns token_emb, the pre-time/type content sequence for masked-modeling targets.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
NUMERIC fields accept standardizer modules fed by the sibling {field}_mask observation flags. A {field}_mask input is skipped as a modality ONLY when {field} has a registered entry in numeric_standardizers; a field merely named x_mask with no standardizer stays a normal modality. Content passes through parameter-free layer norm so raw feature magnitude cannot decide the sum, and padded slots are zeroed for mask-ignoring consumers.

normalize_content defaults to True, which CHANGES outputs versus the previous unnormalized sum (content + time + type): the content term is rescaled to unit variance per event before the additive terms. The default is on because raw feature magnitude is an accident of feature scaling, not a modelling decision.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
nn.Module.train() re-enables dropout inside a frozen encoder even when every weight has requires_grad=False. Pin frozen fields back to eval so a frozen note embedding is deterministic across steps.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Use the known embedding width instead of -1 when restoring the batch shape, and skip the image encoder entirely when a batch has zero image slots, since torch cannot infer -1 for a 0-element tensor.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
A frozen encoder repeats the identical forward every epoch while batch padding width changes each shuffle, so keys hash only the attended tokens. Keys are (hash, real-token length): the length is a cheap guard so a hash collision alone cannot silently return the wrong embedding. cache_frozen_text is the on/off switch; the cache never drops notes, recalculating rows past the cap. Empty note batches return zero-length vectors even for parameter-free encoders (dtype falls back to the default when the encoder has no parameters).

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
…ull.

Misses share one batched encoder call and assembly serves overflow rows from that result instead of re-encoding them one by one, so a full cache costs one batch per new note per forward.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
The cap defaults to 1M entries since 200k is too small for full MIMIC; None or <=0 means uncapped, growth is logged, and frozen_text_cache_size plus frozen_text_cache_stats with a reset method feed the cache on/off A/B.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
With unified_embedding given, codes, labs, and notes share one time-sorted sequence through a single TransformerLayer for full cross-modal attention. Per-field mode is unchanged; the padded path runs alongside sequence_v2, which has no text encoders yet.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
With unified_embedding given, all temporal fields share one time-sorted sequence through a single MambaBlock stack pooled to the last valid event. Per-field mode is unchanged; the padded path runs alongside sequence_v2, which has no text encoders yet.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
With unified_embedding given, all temporal fields share one time-sorted sequence through a single JambaLayer pooled to the last valid event. Per-field mode is unchanged; the padded path runs alongside sequence_v2, which has no text encoders yet.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
With unified_embedding given, the existing RNN class jointly embeds all temporal fields as one time-sorted sequence through a single RNNLayer. RNN_V2 is untouched and the packed-lengths clamp stays as upstream has it. The padded path runs alongside sequence_v2, which owns per-step labels.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Tokenized note fields are one 5-tuple (value, mask, token_type_ids, time,
tag) per sample, with a ragged note count. collate_fn_dict_with_padding
batched only 2-tuples, so these stayed a per-sample list, and every unified
backbone crashed in _build_unified_inputs ('tuple' object has no attribute
'to'). No notes_labs forward ran.

The stacking lives in the processor. TupleTimeTextProcessor.collate()
stacks each tuple position on its own (tensors pad every ragged dimension,
the tag stays a list). get_dataloader batches a field with its processor's
collate(), as upstream does. The generic branch keeps upstream's 2-tuple
(time, values) case, now through the same helper, and no longer batches
other arities: 3-tuples such as TimeImageProcessor's (images, timestamps,
tag) stay per-sample lists, as dipro, the time-region processor and the
unified bridge expect. A processor with emits_pad_mask = True also gets
{field}__pad_mask from its collator; other collators are unchanged.

Upstream's 2-tuple path pad_sequence-pads only dimension 0. On random
batches with ragged trailing dimensions it wrote a (1, 1) sample into three
columns (4 of 300 batches differed, all of this kind). The helper pads
every dimension, which matches upstream whenever upstream is correct.

Tests: TestP1TextTupleCollate now collates through
TupleTimeTextProcessor().collate, as get_dataloader does, and checks the
ragged stack with pad mask. The 2-tuple contract test is unchanged. The
builder-consumption test lands with the unified pad-mask threading commit.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
collate_temporal and collate_fn_dict_with_padding now record {field}__pad_mask wherever they pad, after the collators dispatch so packed sequence_v2 fields never see one. Ragged batching pads every varying dimension, which tokenized notes need.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
The collator mask is authoritative for event validity: text/image encoders run only on valid slots, padded slots sort past every real event with a stable order, and the four unified heads thread pad_mask through. Padding no longer looks like admission-time data.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
MLP gains unified mode with masked mean-pooling over the joint event sequence, threading pad_mask like the other heads so padded slots score nothing. Per-field mode is unchanged.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Per-field mode embeds each feature stream, prefixes a learnable [CLS] per modality, and fuses via shared bottleneck tokens; unified mode runs the same encoder with n_modality=1 over the time-sorted cross-modal sequence (with the collate pad_mask threaded through, as in the other unified heads). New synthetic tests cover per-field and unified forward + backward, finite outputs. Adds the model docs page per the model checklist.

Sources: sunlabuiuc#1185 a92c25a (model) + 7c4c056 (pad-skip hunk); imports adapted from the embedding/ package to the flat unified_embedding module.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
The multimodal MIMIC-IV tasks declare labs_mask as
("stagenet_tensor", {"forward_fill": False}), but the processor took no
kwargs, so set_task raised TypeError. Port sunlabuiuc#1185's forward_fill switch
(reference 49c87c6): default True keeps the historical forward-fill;
False writes missing values as 0.0 in place so a 0/1 observation mask can
never turn a later gap into an observed value after an earlier True.

Tests: TestStageNetTensorProcessorForwardFill (spec instantiation through
get_processor, default still fills, no-fill keeps gaps, mask round-trip).

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Both StageNet fits stopped after the first non-None sample even when it
carried no structural information (an empty lab stay or an empty code
list). Real task streams start with whatever patient sorts first, and
the multimodal tasks emit empty-lab records by design, so the labs and
mask processors routinely stayed unfitted: value_dim() reported 1 and
the unified numeric encoder was built with the wrong input width (first
forward dies with a matmul shape error). The codes fit was worse: an
empty-first stream left _is_nested unset and the vocab loop then crashed
with TypeError on the first nested list. Break only once a sample
determines the structure, matching sunlabuiuc#1185 fit.

Tests: TestStageNetFitSkipsEmptySamples. The empty-first unit tests
fail or crash without it. The fitted-width assertion on the real demo
set_task lands with the tasks commit, which is what needs it.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
One timeline across stays, full stay by default, and admission-context discharge sections stamped at admit. No ICDLabsMIMIC4. The CXR classes are NOT in this commit; they go to the CXR owner set. The emitted_data_version field stays without the cache-history comments. New synthetic tests port the time-axis and observation-window proofs; adds the task docs page per the task checklist.

Sources: sunlabuiuc#1185 49c87c6 task file, minus the CXR classes.

New in v4: regression tests the original series lacked. test_p3_task_schema_specs instantiates every input/output processor spec for both task classes through SampleBuilder._get_processor_instance; test_p3_multimodal_set_task runs real dataset.set_task on MIMIC-IV demo data. Both fail on v3 and pass with the forward_fill fix.

New in v5: the fitted-width assertion on the real demo set_task moved here from the empty-first fit commit, so this commit tests what it needs.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
One parameter, window_hours = 0, on the base task, applied through the single _admission_window_end helper to labs and radiology notes in NotesLabsMIMIC4 and LabsMIMIC4. 0 means no cap (full stay through discharge); a positive value caps each admission at min(admit + N h, discharge), anchored at each admission, not at the first admission's clock. Negative or None raises ValueError. Discharge notes stay unbounded by design (admission-context sections stamped at admit); there is deliberately no switch for them.

Tests: 0 equals the full-stay output exactly; N h drops later labs/radiology per admission; negative and None raise.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Wires the NotesLabsMIMIC4/LabsMIMIC4 tasks and the unified-mode backbones in this series (MLP, RNN, Transformer, BottleneckTransformer, EHRMamba, JambaEHR). Flags: Trainer AMP, loader options, observation-window-hours default 0, freeze-encoder, cache-frozen-text with max-frozen-text-cache, --no-dask-distributed to skip the distributed cluster. No hardcoded MIMIC roots. run() takes injectable sample_dataset for tests; main(argv) injectable for CLI tests. Per-epoch train time, eval/inference time, frozen-text cache stats printed and written to metrics.json for the cache A/B.

Tests: CLI help/defaults/no-cache flag, tiny synthetic end-to-end (MLP, 1 epoch, CPU), plus committed demo-data real-path tests (TestUnifiedE2ERunnerDemoData): labs with mlp+rnn on the MIMIC-IV demo fixture (1 epoch, CPU, shared set_task, seed 2 so val/test have no all-empty batch for the RNN pack), asserting metrics.json key set and finite losses; notes_labs skipped unless Bio_ClinicalBERT is in the local HF cache (never downloads).

New in v5: demo-data runner test added here so the runner commit proves the real path it wires.

Claude-Session: https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant