-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge branch 'main' into training_v2
# Conflicts: # pytest.ini # src/metrics/randomization/model_randomization.py
- Loading branch information
Showing
12 changed files
with
219 additions
and
43 deletions.
There are no files selected for viewing
This file contains 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 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,43 @@ | ||
from abc import ABC, abstractmethod | ||
|
||
import torch | ||
|
||
|
||
class ExplanationsAggregator(ABC): | ||
def __init__(self, training_size: int, *args, **kwargs): | ||
self.scores = torch.zeros(training_size) | ||
|
||
@abstractmethod | ||
def update(self, explanations: torch.Tensor): | ||
raise NotImplementedError | ||
|
||
def reset(self, *args, **kwargs): | ||
""" | ||
Used to reset the aggregator state. | ||
""" | ||
self.scores = torch.zeros_like(self.scores) | ||
|
||
def load_state_dict(self, state_dict: dict, *args, **kwargs): | ||
""" | ||
Used to load the aggregator state. | ||
""" | ||
self.scores = state_dict["scores"] | ||
|
||
def state_dict(self, *args, **kwargs): | ||
""" | ||
Used to return the metric state. | ||
""" | ||
return {"scores": self.scores} | ||
|
||
def compute(self) -> torch.Tensor: | ||
return self.scores.argsort() | ||
|
||
|
||
class SumAggregator(ExplanationsAggregator): | ||
def update(self, explanations: torch.Tensor) -> torch.Tensor: | ||
self.scores += explanations.sum(dim=0) | ||
|
||
|
||
class AbsSumAggregator(ExplanationsAggregator): | ||
def update(self, explanations: torch.Tensor) -> torch.Tensor: | ||
self.scores += explanations.abs().sum(dim=0) |
This file contains 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,30 @@ | ||
from typing import Optional | ||
|
||
import torch | ||
|
||
from utils.explain_wrapper import ExplainFunc | ||
|
||
|
||
def get_self_influence_ranking( | ||
model: torch.nn.Module, | ||
model_id: str, | ||
cache_dir: str, | ||
training_data: torch.utils.data.Dataset, | ||
explain_fn: ExplainFunc, | ||
explain_fn_kwargs: Optional[dict] = None, | ||
) -> torch.Tensor: | ||
size = len(training_data) | ||
self_inf = torch.zeros((size,)) | ||
|
||
for i, (x, y) in enumerate(training_data): | ||
self_inf[i] = explain_fn( | ||
model=model, | ||
model_id=f"{model_id}_id_{i}", | ||
cache_dir=cache_dir, | ||
test_tensor=x[None], | ||
test_label=y[None], | ||
train_dataset=training_data, | ||
train_ids=[i], | ||
**explain_fn_kwargs, | ||
) | ||
return self_inf.argsort() |
This file contains 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 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 was deleted.
Oops, something went wrong.
This file contains 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 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 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 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,47 @@ | ||
import pytest | ||
import torch | ||
|
||
from src.explainers.aggregators.aggregators import ( | ||
AbsSumAggregator, | ||
SumAggregator, | ||
) | ||
|
||
|
||
@pytest.mark.aggregators | ||
@pytest.mark.parametrize( | ||
"test_id, dataset, explanations", | ||
[ | ||
( | ||
"mnist", | ||
"load_mnist_dataset", | ||
"load_mnist_explanations_1", | ||
), | ||
], | ||
) | ||
def test_sum_aggregator(test_id, dataset, explanations, request): | ||
dataset = request.getfixturevalue(dataset) | ||
explanations = request.getfixturevalue(explanations) | ||
aggregator = SumAggregator(training_size=len(dataset)) | ||
aggregator.update(explanations) | ||
global_rank = aggregator.compute() | ||
assert torch.allclose(global_rank, explanations.sum(dim=0).argsort()) | ||
|
||
|
||
@pytest.mark.aggregators | ||
@pytest.mark.parametrize( | ||
"test_id, dataset, explanations", | ||
[ | ||
( | ||
"mnist", | ||
"load_mnist_dataset", | ||
"load_mnist_explanations_1", | ||
), | ||
], | ||
) | ||
def test_abs_aggregator(test_id, dataset, explanations, request): | ||
dataset = request.getfixturevalue(dataset) | ||
explanations = request.getfixturevalue(explanations) | ||
aggregator = AbsSumAggregator(training_size=len(dataset)) | ||
aggregator.update(explanations) | ||
global_rank = aggregator.compute() | ||
assert torch.allclose(global_rank, explanations.abs().mean(dim=0).argsort()) |
This file contains 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,38 @@ | ||
from collections import OrderedDict | ||
|
||
import pytest | ||
import torch | ||
from torch.utils.data import TensorDataset | ||
|
||
from src.explainers.aggregators.self_influence import ( | ||
get_self_influence_ranking, | ||
) | ||
from src.utils.explain_wrapper import explain | ||
from src.utils.functions.similarities import dot_product_similarity | ||
|
||
|
||
@pytest.mark.self_influence | ||
@pytest.mark.parametrize( | ||
"test_id, explain_kwargs", | ||
[ | ||
( | ||
"random_data", | ||
{"method": "SimilarityInfluence", "layer": "identity", "similarity_metric": dot_product_similarity}, | ||
), | ||
], | ||
) | ||
def test_self_influence_ranking(test_id, explain_kwargs, request): | ||
model = torch.nn.Sequential(OrderedDict([("identity", torch.nn.Identity())])) | ||
X = torch.randn(100, 200) | ||
rand_dataset = TensorDataset(X, torch.randint(0, 10, (100,))) | ||
|
||
self_influence_rank = get_self_influence_ranking( | ||
model=model, | ||
model_id="0", | ||
cache_dir="temp_captum", | ||
training_data=rand_dataset, | ||
explain_fn=explain, | ||
explain_fn_kwargs=explain_kwargs, | ||
) | ||
|
||
assert torch.allclose(self_influence_rank, torch.linalg.norm(X, dim=-1).argsort()) |
This file contains 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