Repository navigation
Lrp for review - #900
Lrp for review#900Nimanui wants to merge 23 commits into
Conversation
| if mode == "binary": | ||
| # Binary logits have shape [B] or [B, 1]. | ||
| # target_class_idx=1 (positive) → use logit as-is. | ||
| # target_class_idx=0 (negative) → negate so LRP attributes for the | ||
| # "not-positive" direction (relevance conservation still holds for -logit). | ||
| if target_class_idx is not None: | ||
| idx = ( | ||
| target_class_idx | ||
| if isinstance(target_class_idx, int) | ||
| else int(target_class_idx.item()) | ||
| ) | ||
| if idx == 0: | ||
| return -logits | ||
| return logits | ||
| if mode in ("multiclass", "multilabel"): | ||
| if target_class_idx is None: | ||
| target_class_idx = torch.argmax(logits, dim=-1) | ||
| elif not isinstance(target_class_idx, torch.Tensor): | ||
| target_class_idx = torch.tensor( | ||
| target_class_idx, device=logits.device | ||
| ) | ||
| batch_size = logits.size(0) | ||
| output_relevance = torch.zeros_like(logits) | ||
| output_relevance[range(batch_size), target_class_idx] = logits[ | ||
| range(batch_size), target_class_idx | ||
| ] | ||
| return output_relevance |
There was a problem hiding this comment.
The target_class_index hanlding has been unified in #926. With the following semantics
- binary will always have targret_class_index 0
- the attribution is always towards positive, and up to the evaluator to flip the sign for negative class contribution
- if not specified, both multi-class and multi-label uses argmax
Test CoverageTotal: 76.19% (22726 / 29828 lines)
|
|
/review |
|
I'll look into this and see if it can be reduced a bit 🤔
…On Mon, Oct 26, 2026, 12:37 PM github-actions[bot] ***@***.***> wrote:
*github-actions[bot]* left a comment (sunlabuiuc/PyHealth#900)
<#900 (comment)>
AI Review
*suggestion:* human review
*decision:* not available
This PR is too large for AI review (over 300 files or 200000 diff
characters), so it is labeled status: manual and needs a human review.
—
Reply to this email directly, view it on GitHub
<#900?email_source=notifications&email_token=A2GWZOOFEXIHA4T6SWOMA7L5V6DTXA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMNBSGMYDINBYGM42M4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2KYZTPN52GK4S7MNWGSY3L#issuecomment-6423044839>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/A2GWZOJLWZRV7GMGNDTCDEL5V6DTXAVCNFSNUABFKJSXA33TNF2G64TZHMZDQNBXHAYDEMBWHNEXG43VMU5TIMJQGU3TMNBXGM2KC5QC>
.
Triage notifications, keep track of coding agent tasks and review pull
requests on the go with GitHub Mobile for iOS
<https://github.com/notifications/mobile/ios/A2GWZOMKMJ5JPM4CLIQG3DD5V6DTXA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMNBSGMYDINBYGM42M4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2KUZTPN52GK4S7NFXXG>
and Android
<https://github.com/notifications/mobile/android/A2GWZOI65FN4EVJZYXGQGWD5V6DTXA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMNBSGMYDINBYGM42M4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2K4ZTPN52GK4S7MFXGI4TPNFSA>.
Download it today!
You are receiving this because you authored the thread.Message ID:
***@***.***>
|
i don't think your PR has 300 different files. maybe simply due to outdated branch. i think you can try to merge the latest master and see. |
|
Only thoughts is the notebooks could be bloating it, but yeah I'll update
the main branch on it.
Andrea
…On Mon, Oct 26, 2026, 4:32 PM Logic ***@***.***> wrote:
*Logiquo* left a comment (sunlabuiuc/PyHealth#900)
<#900 (comment)>
I'll look into this and see if it can be reduced a bit
i don't think your PR has 300 different files. maybe simply due to
outdated branch. i think you can try to merge the latest master and see.
—
Reply to this email directly, view it on GitHub
<#900?email_source=notifications&email_token=A2GWZOK2B7FWYNRMKERRHQD5V67FDA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMNBSG44DGMBRGE4KM4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2KYZTPN52GK4S7MNWGSY3L#issuecomment-6427830118>,
or unsubscribe
<https://github.com/notifications/unsubscribe-auth/A2GWZOOZDLTRCCXDIECHTUL5V67FDAVCNFSNUABFKJSXA33TNF2G64TZHMZDQNBXHAYDEMBWHNEXG43VMU5TIMJQGU3TMNBXGM2KC5QC>
.
Triage notifications, keep track of coding agent tasks and review pull
requests on the go with GitHub Mobile for iOS
<https://github.com/notifications/mobile/ios/A2GWZOO7EUZ4HXTU7FYVNO35V67FDA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMNBSG44DGMBRGE4KM4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2KUZTPN52GK4S7NFXXG>
and Android
<https://github.com/notifications/mobile/android/A2GWZON42FGIZDOE2DX32P35V67FDA5CNFSNUABFM5UWIORPF5TWS5BNNB2WEL2JONZXKZKDN5WW2ZLOOQXTMNBSG44DGMBRGE4KM4TFMFZW63VGMF2XI2DPOKSWK5TFNZ2K4ZTPN52GK4S7MFXGI4TPNFSA>.
Download it today!
You are receiving this because you authored the thread.Message ID:
***@***.***>
|
|
/review |
|
/review |
|
Still no luck, I still suspect it's the python notebooks causing the glut of extra lines. Do you think it's worth separating those out and trying again? I could put those in a different PR. |
|
Yes thats an existing limitation of the auto review system, but that would probably resolve the context issues. |
Keeps this PR within the AI review size limit: the example scripts and notebooks move to a follow-up PR, test_lrp_simple.py is folded into test_lrp.py (its one unique check, target-class sensitivity on StageNet, is kept), unused pytest fixtures are removed, and tests are added for lrp_base handlers, CNN/residual LRP paths, SaliencyVisualizer and the mean ablation baseline. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
Turns out it was definitely the pics. Had the AI do an analysis with the character limitation in mind and it should be below the limit now. I'll have to do a follow-up PR with the notebook examples though. I've also added a few more tests to improve the test coverage. |
|
In general any PR with pics will probably be punted to manual due to the limitations. |
|
@Logiquo Can you try setting this to automatic one more time and see if removing the notebooks worked. |
|
/review |
|
|
||
| For complete working examples, see: | ||
|
|
||
| - ``examples/interpretability/lrp_stagenet_synthetic.py`` — self-contained run on synthetic data, no external dataset required |
There was a problem hiding this comment.
[medium] Docs reference example files that do not exist
The Quick Start section lists three example files: examples/interpretability/lrp_stagenet_synthetic.py, examples/interpretability/lrp_stagenet_mimic4.py and examples/ChestXray-Classification-ResNet-with-Saliency.ipynb. None of them exists in the repository, and the PR does not add them. Either add the examples in this PR or remove these references (and the matching note in the PR description about pruning examples) so the docs do not point to missing files.
| img = img.squeeze(-1) | ||
|
|
||
| # Ensure values are in reasonable range for display | ||
| if img.max() > 1.0 and img.max() <= 255.0: |
There was a problem hiding this comment.
[medium] Normalized RGB images are blackened by a spurious /255 rescale
_process_image divides any image whose max is in (1, 255] by 255. Images normalized with ImageNet statistics (max about 2.2 to 2.6) match this condition, so an RGB image is divided by 255 and imshow renders it nearly black. The existing BasicGradientSaliencyMaps.visualize_saliency_map now routes through this function, so its output regresses for the normalized inputs its docstring recommends. Rescale only when the dtype is uint8 or the data is known to be in [0, 255], and add a test with ImageNet-normalized input.
| import torch | ||
|
|
||
|
|
||
| class SaliencyVisualizer: |
There was a problem hiding this comment.
[medium] SaliencyVisualizer duplicates existing interpret utilities
pyhealth/interpret/utils.py already provides normalize_attribution (line 227, including a percentile method) and visualize_image_attr (line 272, which normalizes the image and attribution and builds the overlay). SaliencyVisualizer._normalize_saliency and the overlay logic in plot_saliency_overlay reimplement these. Reuse normalize_attribution and visualize_image_attr (or extend them) instead of adding a parallel visualization stack with five plotting methods and two module-level helpers.
| interpret/pyhealth.interpret.methods.chefer | ||
| interpret/pyhealth.interpret.methods.attention_rollout | ||
| interpret/pyhealth.interpret.methods.deeplift | ||
| interpret/pyhealth.interpret.methods.lrp |
There was a problem hiding this comment.
[medium] Existing API doc pages removed from the toctree without explanation
The toctree drops interpret/pyhealth.interpret.methods.ig_gim, ensemble, baseline and base_interpreter. Their RST files still exist under docs/api/interpret/, so Sphinx will report them as not included in any toctree, and the public API for those classes disappears from the rendered docs. The PR description does not mention this. Restore those entries, or move the removal into a separate, explained change.
| # ============================================================================ | ||
|
|
||
|
|
||
| def create_default_registry() -> LRPHandlerRegistry: |
There was a problem hiding this comment.
[low] create_default_registry and check_tensor_validity are unused in production
create_default_registry duplicates the handler list in LayerwiseRelevancePropagation.init (lrp.py), and the two lists already differ because only the factory registers EmbeddingLRPHandler. check_tensor_validity (line 61) is never called outside its doctest. Keep one registration path and delete the unused helpers, or call them from the interpreter.
| unittest.main() | ||
|
|
||
|
|
||
| class TestMeanAblationBaseline(unittest.TestCase): |
There was a problem hiding this comment.
[low] New test class is defined after the main block
TestMeanAblationBaseline is placed after the if name == 'main': unittest.main() block at line 538. Running the file as a script calls unittest.main() before the class exists, so these regression tests only run under pytest. Move the class above the main guard.
| relative_diff = abs(total_relevance - logit) / max(abs(logit), 1e-6) | ||
| print(f"Relative difference: {relative_diff:.2%}") | ||
|
|
||
| self.assertLess(relative_diff, 3.0, |
There was a problem hiding this comment.
[low] Conservation tests accept errors of up to 300% and 150%
test_relevance_sums_to_output allows relative error below 3.0, and the StageNet conservation test (line 1190) allows 1.5. Neither would catch a sign flip or a missing residual term, so the conservation property is effectively untested for the model paths. The linear-layer test in test_lrp_base.py does check conservation exactly and is the stronger check. Assert a tight bound on a model whose logit dominates its biases, or on the exact linear handler, and keep the looser bound as a documented smoke test.
| print("[RemovalBasedMetric] WARNING: Unknown classifier") | ||
| print(f" - Mode detected: {mode}") | ||
|
|
||
| def _mean_baseline(self, x: torch.Tensor) -> torch.Tensor: |
There was a problem hiding this comment.
[low] Metrics fix is not described and the mean-ablation docs are stale
_mean_baseline changes what Comprehensiveness and Sufficiency return for 'mean' ablation at batch_size=1, which was previously a silent no-op. The fix is sound, but the PR description does not mention it. The evaluator and base docstrings (base.py line 43) still say 'feature mean across batch', which no longer holds at batch_size=1. Split this into its own PR or describe it, and update the docstrings.
| at construction and dispatches each layer through it, so support for a custom | ||
| layer can be added without subclassing the interpreter:: | ||
|
|
||
| lrp._registry.register(MyLayerHandler()) |
There was a problem hiding this comment.
[low] Docs advertise the private _registry attribute as an extension point
The docs tell users to call lrp._registry.register(...) to add a custom layer handler. Documenting a leading-underscore attribute as public API makes it hard to change later. Expose a public register_handler method on LayerwiseRelevancePropagation and document that instead.
There was a problem hiding this comment.
AI Review
suggestion: need change
decision: human review
Thank you for this contribution. It adds alpha-beta and epsilon LRP attribution with per-layer handlers, a shared saliency visualizer, and tests that cover the new LRP code well. It is close, but a few things need fixing first.
A maintainer will also take a look. The change modifies the shared RemovalBasedMetric base class: mean ablation at batch_size=1 now returns different scores than before, which previously came back as a silent 0.0. That counts as touching core code.
To get this merged:
- The LRP doc page references example files that aren't in the PR:
examples/interpretability/lrp_stagenet_synthetic.py,examples/interpretability/lrp_stagenet_mimic4.py, andexamples/ChestXray-Classification-ResNet-with-Saliency.ipynb. Either add them or remove the references. docs/api/interpret.rstdropsig_gim,ensemble,baselineandbase_interpreterfrom the toctree, which leaves their existing pages orphaned. Please restore them unless the removal is intentional, and explain it in the description if it is.SaliencyVisualizer._process_imagedivides any image whose max is in (1, 255] by 255. ImageNet-normalized inputs, which the docs recommend, would then render nearly black in the existingvisualize_saliency_map. Please make this rescaling more careful, for example only for uint8 dtype or a max above 1.5 together with non-negative values.saliency_visualization.pyappears to overlap with the existingnormalize_attributionandvisualize_image_attrhelpers inpyhealth/interpret/utils.py. Please reuse them or explain why a new module is needed.
Optional suggestions:
- Mention the metrics mean-ablation fix in the PR description, and update the
_mean_baselinedocstring. TestMeanAblationBaselineis placed after theif __name__ == "__main__"block intest_interp_metrics.py. Move it above the block so it runs when the file is run as a script.- The conservation assertions (relative error below 3.0 and 1.5) are very loose and would not catch regressions.
create_default_registryandcheck_tensor_validityare unused in production code, and the docs advertise the privatelrp._registryas an extension point. Consider a public API for registering handlers.
Coverage: the new files are at 96–100%, above the 80% bar. The whole repository is at 76.19%, above the 60% bar. metrics/interpretability/base.py is at 73.25%, below the 80% file-level guideline, though that is mostly pre-existing code.
Reviewed commit ab5604f
Looking to add some alpha, beta, and epsilon LRP saliency options run across a few different models (both the MIMIC IV stagenet and the chest x-ray CNN)
Original implementation is based off of https://arxiv.org/abs/1604.00825 and is very vibey so I'm expecting some comments
I may prune down the example options a bit as this ended up a bit bloated, and I'll need to add some more documentation