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

Optionally Avoid recomputing features #722

Merged
merged 17 commits into from
Apr 11, 2022
Merged
Show file tree
Hide file tree
Changes from 3 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
14 changes: 14 additions & 0 deletions torchmetrics/image/fid.py
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,9 @@ class FID(Metric):
- an ``nn.Module`` for using a custom feature extractor. Expects that its forward method returns
an ``[N,d]`` matrix where ``N`` is the batch size and ``d`` is the feature size.

reset_real_features: Whether to also reset the real features. Since in many cases the real dataset does not
change, the features can cached them to avoid recomputing them which is costly. Set this to ``False`` if
your dataset does not change.
compute_on_step:
Forward only calls ``update()`` and return ``None`` if this is set to ``False``.
dist_sync_on_step:
Expand Down Expand Up @@ -209,6 +212,7 @@ class FID(Metric):
def __init__(
self,
feature: Union[int, torch.nn.Module] = 2048,
reset_real_features: bool = True,
compute_on_step: bool = False,
dist_sync_on_step: bool = False,
process_group: Optional[Any] = None,
Expand Down Expand Up @@ -248,6 +252,13 @@ def __init__(
self.add_state("real_features", [], dist_reduce_fx=None)
self.add_state("fake_features", [], dist_reduce_fx=None)

if reset_real_features:
exclude_states = ()
else:
exclude_states = ("real_features",)
Borda marked this conversation as resolved.
Show resolved Hide resolved

self._reset_excluded_states = exclude_states

def update(self, imgs: Tensor, real: bool) -> None: # type: ignore
"""Update the state with extracted features.

Expand Down Expand Up @@ -282,3 +293,6 @@ def compute(self) -> Tensor:

# compute fid
return _compute_fid(mean1, cov1, mean2, cov2).to(orig_dtype)

def reset(self, exclude_states: Optional[Sequence[str]] = None) -> None:
justusschock marked this conversation as resolved.
Show resolved Hide resolved
super().reset({*self._reset_excluded_states, *exclude_states})
14 changes: 14 additions & 0 deletions torchmetrics/image/kid.py
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,9 @@ class KID(Metric):
Scale-length of polynomial kernel. If set to ``None`` will be automatically set to the feature size
coef:
Bias term in the polynomial kernel.
reset_real_features: Whether to also reset the real features. Since in many cases the real dataset does not
change, the features can cached them to avoid recomputing them which is costly. Set this to ``False`` if
your dataset does not change.
compute_on_step:
Forward only calls ``update()`` and return ``None`` if this is set to ``False``.
dist_sync_on_step:
Expand Down Expand Up @@ -174,6 +177,7 @@ def __init__(
degree: int = 3,
gamma: Optional[float] = None, # type: ignore
coef: float = 1.0,
reset_real_features: bool = True,
compute_on_step: bool = False,
dist_sync_on_step: bool = False,
process_group: Optional[Any] = None,
Expand Down Expand Up @@ -235,6 +239,13 @@ def __init__(
self.add_state("real_features", [], dist_reduce_fx=None)
self.add_state("fake_features", [], dist_reduce_fx=None)

if reset_real_features:
exclude_states = ()
else:
exclude_states = ("real_features",)
Borda marked this conversation as resolved.
Show resolved Hide resolved

self._reset_excluded_states = exclude_states

def update(self, imgs: Tensor, real: bool) -> None: # type: ignore
"""Update the state with extracted features.

Expand Down Expand Up @@ -276,3 +287,6 @@ def compute(self) -> Tuple[Tensor, Tensor]:
kid_scores_.append(o)
kid_scores = torch.stack(kid_scores_)
return kid_scores.mean(), kid_scores.std(unbiased=False)

def reset(self, exclude_states: Optional[Sequence[str]] = None) -> None:
super().reset({*self._reset_excluded_states, *exclude_states})
4 changes: 3 additions & 1 deletion torchmetrics/metric.py
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ def compute(self) -> Any:
"""Override this method to compute the final metric value from state variables synchronized across the
distributed backend."""

def reset(self) -> None:
def reset(self, exclude_states: Optional[Sequence[str]] = None) -> None:
"""This method automatically resets the metric state variables to their default value."""
Borda marked this conversation as resolved.
Show resolved Hide resolved
self._update_called = False
self._forward_cache = None
Expand All @@ -403,6 +403,8 @@ def reset(self) -> None:
self._computed = None

for attr, default in self._defaults.items():
if exclude_states is not None and attr in exclude_states:
continue
current_val = getattr(self, attr)
if isinstance(default, Tensor):
setattr(self, attr, default.detach().clone().to(current_val.device))
Expand Down