Repository navigation
Conversation
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
This was referenced Nov 24, 2026
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
rianfyi
force-pushed
the
tranche1_final-commits
branch
from
November 27, 2026 21:18
68b598d to
ffe267d
Compare
This was referenced Nov 27, 2026
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
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 base2c9dfacf). Upstream master has since moved to0181aa2f; this series stays on59890580for review, and upstream PRs will be cut from current master when they are opened.tranche1_finalis unmodified upstream at2c9dfacfuntil 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
Processors and unified embedding
normalize_content=Truelayer-norms content; padded slots zeroedBackbones and collation
collate(); 2-tuple output unchanged except that ragged trailing dimensions are now padded; other tuple arities stay per-sample lists{field}__pad_maskfor ragged 2-tuple fields and text fieldsModels, processors, tasks, runner
Changed by the rebase
**loader_kwargs, so the argument checks were dropped. Its subject changed to "Test the DataLoader worker options that get_dataloader forwards."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 assignsself.mode.edsub-dataset. The equivalence test is tie-aware: the fixture repeats onepatient_id, each path's output is first checked to be sorted bypatient_id, and the two frames are then compared after a stable sort on(patient_id, _source_row).collate(), whichget_dataloaderuses 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_maskfor ragged 2-tuple fields and text fields.Decisions already made
use_dask_distributed, instead of an environment variable. This is the only code rewritten for this PR. The runner gets--no-dask-distributed.normalize_contentis on by default.Please read before reviewing item 28
window_hours=0keeps 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-hoursfor that. The window caps labs and radiology notes at the same point. Discharge-note sections stay unbounded by design.Verification
tools/check_pr_rules.pypasses on each of the 29 commits (exit 0, ruff 0.17.6), each run with that commit checked out.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.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.59890580: 16 failed, 4165 passed. Tipffe267d0: 20 failed, 4291 passed. Against the upstream failing set, the tip has four extra failures, all intests/core/test_lime.py(threeTestLimeExplainerMLPtests and oneTestLimeExplainerStageNetbasic_attributiontest). 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.pypassed all 34 tests twice on this tip and once on upstream59890580. The 31 failures from the first version of commit 20 are gone.labsandnotes_labswith--dev 1000, and thenotes_labscache 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.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):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):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
966a658band by 0.0007 ona4337a4f. 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 upstream2afbdaefchanges event order andc210ab2dthe trainer's eval path. The figures therefore apply to the measured trees (966a658banda4337a4f) and have not been re-measured on the rebased tree.Not in this PR
numeric_standardizershook stays, but nothing plugs into it until the z-score commit lands.https://claude.ai/code/session_011iPyPDjj4ktrHDkPbEkk95