-
Notifications
You must be signed in to change notification settings - Fork 1
Feat/mlp depth loss weight bootstrap #167
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
kirilklein
wants to merge
5
commits into
main
Choose a base branch
from
feat/mlp-depth-loss-weight-bootstrap
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
5 commits
Select commit
Hold shift + click to select a range
ce0c6b1
Add configurable MLP head depth for better confounding adjustment
kvk-cmd 5711724
Normalize outcome losses and add exposure loss weighting
kvk-cmd 94d346c
Add bootstrap sampling method for variance estimation
kvk-cmd e4f0541
ruff
kvk-cmd d514b75
format
kvk-cmd File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -73,17 +73,22 @@ class MLPHead(nn.Module): | |
| """ | ||
|
|
||
| def __init__( | ||
| self, input_size: int, hidden_size_ratio: int = 2, dropout_prob: float = 0.1 | ||
| self, | ||
| input_size: int, | ||
| hidden_size_ratio: int = 2, | ||
| dropout_prob: float = 0.1, | ||
| num_hidden_layers: int = 1, | ||
| ): | ||
| super().__init__() | ||
| intermediate_size = input_size // hidden_size_ratio | ||
| self.classifier = nn.Sequential( | ||
| nn.LayerNorm(input_size), | ||
| nn.Linear(input_size, intermediate_size), | ||
| nn.GELU(), | ||
| # nn.Dropout(dropout_prob), | ||
| nn.Linear(intermediate_size, 1, bias=True), | ||
| ) | ||
| layers = [nn.LayerNorm(input_size)] | ||
| current_size = input_size | ||
| for _ in range(num_hidden_layers): | ||
| next_size = current_size // hidden_size_ratio | ||
| layers.append(nn.Linear(current_size, next_size)) | ||
| layers.append(nn.GELU()) | ||
| current_size = next_size | ||
| layers.append(nn.Linear(current_size, 1, bias=True)) | ||
|
Comment on lines
+85
to
+90
Contributor
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Add guardrails for invalid/degenerated MLP dimensions.
Proposed fix def __init__(
self,
input_size: int,
hidden_size_ratio: int = 2,
dropout_prob: float = 0.1,
num_hidden_layers: int = 1,
):
super().__init__()
+ if hidden_size_ratio <= 0:
+ raise ValueError(f"hidden_size_ratio must be > 0, got {hidden_size_ratio}")
+ if num_hidden_layers < 0:
+ raise ValueError(f"num_hidden_layers must be >= 0, got {num_hidden_layers}")
+
layers = [nn.LayerNorm(input_size)]
current_size = input_size
- for _ in range(num_hidden_layers):
+ for layer_idx in range(num_hidden_layers):
next_size = current_size // hidden_size_ratio
+ if next_size < 1:
+ raise ValueError(
+ f"Invalid MLP config at hidden layer {layer_idx}: "
+ f"current_size={current_size}, hidden_size_ratio={hidden_size_ratio}"
+ )
layers.append(nn.Linear(current_size, next_size))
layers.append(nn.GELU())
current_size = next_size🤖 Prompt for AI Agents |
||
| self.classifier = nn.Sequential(*layers) | ||
|
|
||
| def forward(self, x: torch.Tensor) -> torch.Tensor: | ||
| """ | ||
|
|
||
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
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,70 @@ | ||
| """Unit tests for cohort sampling utilities.""" | ||
|
|
||
| import unittest | ||
|
|
||
| import torch | ||
|
|
||
| from corebehrt.functional.causal.cohort_sampler import sample_cohort | ||
|
|
||
|
|
||
| class TestSampleCohort(unittest.TestCase): | ||
| def setUp(self): | ||
| self.full_pids = torch.tensor([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) | ||
|
|
||
| def test_default_method_is_resample(self): | ||
| """Default method should be resample (without replacement).""" | ||
| sampled = sample_cohort(self.full_pids, sample_size=5, seed=42) | ||
| self.assertEqual(len(sampled), 5) | ||
| # No duplicates | ||
| self.assertEqual(len(set(sampled.tolist())), 5) | ||
|
|
||
| def test_resample_no_duplicates(self): | ||
| """Resample method should produce no duplicate PIDs.""" | ||
| sampled = sample_cohort( | ||
| self.full_pids, sample_size=10, seed=42, method="resample" | ||
| ) | ||
| self.assertEqual(len(set(sampled.tolist())), 10) | ||
|
|
||
| def test_resample_rejects_oversize(self): | ||
| """Resample method should reject sample_size > n_total.""" | ||
| with self.assertRaises(ValueError): | ||
| sample_cohort(self.full_pids, sample_size=20, seed=42, method="resample") | ||
|
|
||
| def test_bootstrap_allows_duplicates(self): | ||
| """Bootstrap method should sample with replacement (duplicates possible).""" | ||
| # Use a large sample to make duplicates very likely | ||
| sampled = sample_cohort( | ||
| self.full_pids, sample_size=100, seed=42, method="bootstrap" | ||
| ) | ||
| self.assertEqual(len(sampled), 100) | ||
| # With 100 draws from 10 items, duplicates are virtually guaranteed | ||
| self.assertLess(len(set(sampled.tolist())), 100) | ||
|
|
||
| def test_bootstrap_accepts_oversize(self): | ||
| """Bootstrap method should accept sample_size > n_total.""" | ||
| sampled = sample_cohort( | ||
| self.full_pids, sample_size=20, seed=42, method="bootstrap" | ||
| ) | ||
| self.assertEqual(len(sampled), 20) | ||
|
|
||
| def test_invalid_method_raises(self): | ||
| """Invalid method should raise ValueError.""" | ||
| with self.assertRaises(ValueError): | ||
| sample_cohort(self.full_pids, sample_size=5, seed=42, method="invalid") | ||
|
|
||
| def test_bootstrap_with_fraction(self): | ||
| """Bootstrap with fraction should work.""" | ||
| sampled = sample_cohort( | ||
| self.full_pids, sample_fraction=0.5, seed=42, method="bootstrap" | ||
| ) | ||
| self.assertEqual(len(sampled), 5) | ||
|
|
||
| def test_resample_reproducibility(self): | ||
| """Same seed should produce same results.""" | ||
| s1 = sample_cohort(self.full_pids, sample_size=5, seed=123) | ||
| s2 = sample_cohort(self.full_pids, sample_size=5, seed=123) | ||
| self.assertTrue(torch.equal(s1, s2)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| unittest.main() |
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
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.
Uh oh!
There was an error while loading. Please reload this page.