-
Notifications
You must be signed in to change notification settings - Fork 26
Fix dimension mismatch and add auto-loss support to TRAK #246
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
traderbxy
wants to merge
2
commits into
TRAIS-Lab:main
Choose a base branch
from
traderbxy:main
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
2 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -15,6 +15,7 @@ | |
| import torch | ||
| from torch.func import vmap | ||
| from tqdm import tqdm | ||
| import torch.nn.functional as F | ||
|
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. Is F used? |
||
|
|
||
| from dattri.func.projection import random_project | ||
| from dattri.func.utils import _unflatten_params | ||
|
|
@@ -36,7 +37,7 @@ class TRAKAttributor(BaseAttributor): | |
| def __init__( | ||
| self, | ||
| task: AttributionTask, | ||
| correct_probability_func: Callable, | ||
| correct_probability_func: Optional[Callable] = None, | ||
| projector_kwargs: Optional[Dict[str, Any]] = None, | ||
| layer_name: Optional[Union[str, List[str]]] = None, | ||
| device: str = "cpu", | ||
|
|
@@ -74,6 +75,42 @@ def m(params, image_label_pair): | |
| Added as `regularization * I`, where `I` is the identity matrix. | ||
| Default is 0.0. | ||
| """ | ||
|
|
||
| if correct_probability_func is None: | ||
| print(getattr(task, 'task_type', None)) | ||
| if getattr(task, 'task_type', None) in['image_classification', 'text_classification']: | ||
| def default_m(params, data): | ||
| if isinstance(data, dict): | ||
| if 'label' in data: | ||
| label = data['label'] | ||
| elif 'labels' in data: | ||
| label = data['labels'] | ||
| else: | ||
| raise ValueError("Dictionary data must contain 'label' or 'labels'") | ||
| inputs = {k: v for k, v in data.items() if k not in ['label', 'labels']} | ||
| elif isinstance(data, (tuple, list)): | ||
| inputs, label = data[0], data[1] | ||
| else: | ||
| inputs, label = data | ||
|
|
||
| if isinstance(inputs, dict): | ||
| inputs_vmap = {'input_ids': data['input_ids'].unsqueeze(0)} | ||
| yhat = torch.func.functional_call(self.task.get_model(), params, kwargs=inputs_vmap) | ||
| else: | ||
| yhat = torch.func.functional_call(self.task.get_model(), params, inputs.unsqueeze(0)) | ||
|
|
||
| if hasattr(yhat, 'logits'): | ||
| yhat = yhat.logits | ||
|
|
||
| loss_val = torch.nn.functional.cross_entropy(yhat, label.unsqueeze(0)) | ||
| return torch.exp(-loss_val) | ||
|
|
||
| selected_prob_func = default_m | ||
| else: | ||
| raise ValueError(f"Unsupported task type: {task_type}, please provide loss_func and correct_probability_func.") | ||
| else: | ||
| selected_prob_func = correct_probability_func | ||
|
|
||
| self.task = task | ||
| self.norm_scaler = ( | ||
| sum( | ||
|
|
@@ -91,7 +128,7 @@ def m(params, image_label_pair): | |
| self.grad_target_func = self.task.get_grad_target_func(in_dims=(None, 0)) | ||
| self.grad_loss_func = self.task.get_grad_loss_func(in_dims=(None, 0)) | ||
| self.correct_probability_func = vmap( | ||
| correct_probability_func, | ||
| selected_prob_func, | ||
| in_dims=(None, 0), | ||
| randomness="different", | ||
| ) | ||
|
|
@@ -143,6 +180,11 @@ def cache( | |
| train_batch_data = tuple( | ||
| data.to(self.device) for data in train_data | ||
| ) | ||
| elif isinstance(train_data, dict): | ||
| train_batch_data = { | ||
| k: v.to(self.device) if isinstance(v, torch.Tensor) else v | ||
| for k, v in train_data.items() | ||
| } | ||
| else: | ||
| train_batch_data = train_data | ||
|
|
||
|
|
@@ -307,6 +349,8 @@ def attribute( # noqa: PLR0912, PLR0914, PLR0915 | |
| # TODO: reorganize the data pre-grad processing. | ||
| if isinstance(test_data, (tuple, list)): | ||
| test_batch_data = tuple(data.to(self.device) for data in test_data) | ||
| elif isinstance(test_data, dict): | ||
| test_batch_data = {k: v.to(self.device) if isinstance(v, torch.Tensor) else v for k, v in test_data.items()} | ||
| else: | ||
| test_batch_data = test_data | ||
| grad_t = self.grad_target_func(parameters, test_batch_data) | ||
|
|
||
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
Oops, something went wrong.
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.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Could you add a unit test related to this bug fix so that we could make sure future changes won't introduce such bugs again?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
In addition, I would recommend separating this bug fix from the other change to maintain a clean change log.