Skip to content
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

Visualize intermediate images of Composer #244

Merged
merged 19 commits into from
Feb 4, 2024
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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
10 changes: 9 additions & 1 deletion mart/attack/composer/modular.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
from typing import TYPE_CHECKING, Any, Iterable

import torch
from torchvision.transforms.functional import to_pil_image

from mart.nn import SequentialDict

Expand All @@ -19,7 +20,7 @@


class Composer(torch.nn.Module):
def __init__(self, perturber: Perturber, modules, sequence) -> None:
def __init__(self, perturber: Perturber, modules, sequence, visualize: bool = False) -> None:
"""_summary_

Args:
Expand All @@ -34,6 +35,7 @@ def __init__(self, perturber: Perturber, modules, sequence) -> None:
if isinstance(sequence, dict):
sequence = [sequence[key] for key in sorted(sequence)]
self.functions = SequentialDict(modules, {"composer": sequence})
self.visualize = visualize

def configure_perturbation(self, input: torch.Tensor | Iterable[torch.Tensor]):
return self.perturber.configure_perturbation(input)
Expand Down Expand Up @@ -76,6 +78,12 @@ def _compose(
input=input, target=target, perturbation=perturbation, step="composer"
)

# Visualize intermediate images.
if self.visualize:
for key, value in output.items():
if isinstance(value, torch.Tensor):
to_pil_image(value / 255).save(f"{key}.png")

# SequentialDict returns a dictionary DotDict,
# but we only need the return value of the most recently executed module.
last_added_key = next(reversed(output))
Expand Down
Loading