Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion monai/metrics/embedding_collapse.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,10 @@ def _effective_rank_score(emb: torch.Tensor) -> torch.Tensor:
probs = sv / sv_sum
safe_probs = probs.clamp_min(torch.finfo(probs.dtype).tiny)
eff_rank: torch.Tensor = torch.exp(-(probs * safe_probs.log()).sum())
max_rank: torch.Tensor = emb.new_tensor(float(min(emb.shape[0], emb.shape[1])))
# Mean-centering above forces the rows to sum to zero, a linear dependency, so
# rank(centered) <= min(N - 1, D). Normalizing by min(N, D) would impose a 1/N
# floor on the score whenever N <= D. No-op when N > D: both expressions equal D.
max_rank: torch.Tensor = emb.new_tensor(float(min(emb.shape[0] - 1, emb.shape[1])))
return (emb.new_tensor(1.0) - eff_rank / max_rank).clamp(0.0, 1.0)


Expand Down
23 changes: 22 additions & 1 deletion tests/metrics/test_embedding_collapse.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,10 +224,31 @@ def test_formula_matches_manual(self):
probs = sv / sv_sum
safe_probs = probs.clamp_min(torch.finfo(probs.dtype).tiny)
eff_rank = (-(probs * safe_probs.log()).sum()).exp()
expected = (1.0 - eff_rank / min(20, 16)).clamp(0.0, 1.0)
expected = (1.0 - eff_rank / min(20 - 1, 16)).clamp(0.0, 1.0)
score = _effective_rank_score(emb)
self.assertAlmostEqual(float(score), float(expected), places=5)

def test_effective_rank_no_collapse_when_n_leq_d(self):
# Isotropic embeddings have NO dimensional collapse -> score must be ~0.
# RED on dev: returns ~0.25 (the 1/N floor). GREEN after fix: ~0.0004.
torch.manual_seed(0)
score = _effective_rank_score(torch.randn(4, 768))
self.assertLess(float(score), 0.05)

def test_effective_rank_two_distinct_samples_report_no_collapse(self):
# Two maximally-spread points span the only subspace 2 samples CAN span.
# RED on dev: returns exactly 0.5 ("50% collapsed"). GREEN after fix: 0.0.
emb = torch.zeros(2, 768)
emb[0, 0] = 1.0
emb[1, 0] = -1.0
self.assertAlmostEqual(float(_effective_rank_score(emb)), 0.0, places=5)

def test_effective_rank_unchanged_when_n_gt_d(self):
# Regression guard: the fix MUST be a no-op where the code is already correct.
torch.manual_seed(0)
score = _effective_rank_score(torch.randn(1024, 768))
self.assertAlmostEqual(float(score), 0.1234, places=3)

Comment on lines +231 to +251

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

📐 Maintainability & Code Quality | 🟡 Minor | ⚡ Quick win

Add missing docstrings to test definitions.

Convert the inline comments to Google-style docstrings for the new test methods. As per path instructions, Docstrings should be present for all definition which describe each variable, return value, and raised exception in the appropriate section of the Google-style of docstrings.

📝 Proposed fix
-    def test_effective_rank_no_collapse_when_n_leq_d(self):
-        # Isotropic embeddings have NO dimensional collapse -> score must be ~0.
-        # RED on dev: returns ~0.25 (the 1/N floor). GREEN after fix: ~0.0004.
+    def test_effective_rank_no_collapse_when_n_leq_d(self):
+        """Isotropic embeddings have no dimensional collapse (score must be ~0).
+
+        Returns:
+            None
+        """
         torch.manual_seed(0)
         score = _effective_rank_score(torch.randn(4, 768))
         self.assertLess(float(score), 0.05)
 
-    def test_effective_rank_two_distinct_samples_report_no_collapse(self):
-        # Two maximally-spread points span the only subspace 2 samples CAN span.
-        # RED on dev: returns exactly 0.5 ("50% collapsed"). GREEN after fix: 0.0.
+    def test_effective_rank_two_distinct_samples_report_no_collapse(self):
+        """Two maximally-spread points span the only subspace 2 samples can span.
+
+        Returns:
+            None
+        """
         emb = torch.zeros(2, 768)
         emb[0, 0] = 1.0
         emb[1, 0] = -1.0
         self.assertAlmostEqual(float(_effective_rank_score(emb)), 0.0, places=5)
 
-    def test_effective_rank_unchanged_when_n_gt_d(self):
-        # Regression guard: the fix MUST be a no-op where the code is already correct.
+    def test_effective_rank_unchanged_when_n_gt_d(self):
+        """Regression guard: the fix must be a no-op when n > d.
+
+        Returns:
+            None
+        """
         torch.manual_seed(0)
         score = _effective_rank_score(torch.randn(1024, 768))
         self.assertAlmostEqual(float(score), 0.1234, places=3)
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
def test_effective_rank_no_collapse_when_n_leq_d(self):
# Isotropic embeddings have NO dimensional collapse -> score must be ~0.
# RED on dev: returns ~0.25 (the 1/N floor). GREEN after fix: ~0.0004.
torch.manual_seed(0)
score = _effective_rank_score(torch.randn(4, 768))
self.assertLess(float(score), 0.05)
def test_effective_rank_two_distinct_samples_report_no_collapse(self):
# Two maximally-spread points span the only subspace 2 samples CAN span.
# RED on dev: returns exactly 0.5 ("50% collapsed"). GREEN after fix: 0.0.
emb = torch.zeros(2, 768)
emb[0, 0] = 1.0
emb[1, 0] = -1.0
self.assertAlmostEqual(float(_effective_rank_score(emb)), 0.0, places=5)
def test_effective_rank_unchanged_when_n_gt_d(self):
# Regression guard: the fix MUST be a no-op where the code is already correct.
torch.manual_seed(0)
score = _effective_rank_score(torch.randn(1024, 768))
self.assertAlmostEqual(float(score), 0.1234, places=3)
def test_effective_rank_no_collapse_when_n_leq_d(self):
"""Isotropic embeddings have no dimensional collapse (score must be ~0).
Returns:
None
"""
torch.manual_seed(0)
score = _effective_rank_score(torch.randn(4, 768))
self.assertLess(float(score), 0.05)
def test_effective_rank_two_distinct_samples_report_no_collapse(self):
"""Two maximally-spread points span the only subspace 2 samples can span.
Returns:
None
"""
emb = torch.zeros(2, 768)
emb[0, 0] = 1.0
emb[1, 0] = -1.0
self.assertAlmostEqual(float(_effective_rank_score(emb)), 0.0, places=5)
def test_effective_rank_unchanged_when_n_gt_d(self):
"""Regression guard: the fix must be a no-op when n > d.
Returns:
None
"""
torch.manual_seed(0)
score = _effective_rank_score(torch.randn(1024, 768))
self.assertAlmostEqual(float(score), 0.1234, places=3)
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@tests/metrics/test_embedding_collapse.py` around lines 231 - 251, Replace the
inline comments in test_effective_rank_no_collapse_when_n_leq_d,
test_effective_rank_two_distinct_samples_report_no_collapse, and
test_effective_rank_unchanged_when_n_gt_d with Google-style method docstrings
describing the test inputs, expected score behavior, return value, and any
raised exceptions as applicable. Preserve the existing test logic and
assertions.

Source: Path instructions


class TestPerClassRank(unittest.TestCase):
def test_keys_present_for_each_class(self):
Expand Down
Loading