-
Notifications
You must be signed in to change notification settings - Fork 498
[DRAFT]: Refactor of diffusion samplers #1106
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
CharlelieLrt
wants to merge
2
commits into
NVIDIA:main
Choose a base branch
from
CharlelieLrt:diffusion-samplers-refactor
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 1 commit
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,17 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2023 - 2024 NVIDIA CORPORATION & AFFILIATES. | ||
| # SPDX-FileCopyrightText: All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from .guidance import ModelBasedGuidance |
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 |
|---|---|---|
| @@ -0,0 +1,113 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2023 - 2024 NVIDIA CORPORATION & AFFILIATES. | ||
| # SPDX-FileCopyrightText: All rights reserved. | ||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|
|
||
| from typing import Callable, Dict, Any, TypeAlias | ||
|
|
||
| import torch | ||
| from torch import Tensor | ||
| from torch.func import grad, vmap | ||
|
|
||
|
|
||
| class ModelBasedGuidance: | ||
| r""" """ | ||
|
|
||
| # TODO: for each one of the scaling parameters, need explanations | ||
| # + reference + make sure default values are sensible | ||
| def __init__( | ||
| self, | ||
| guide_model: Callable[[torch.Tensor], torch.Tensor], | ||
| std: float = 0.075, | ||
| gamma: float = 0.05, | ||
| mu: float = 1, | ||
| scale: float = 1, | ||
| power: float = 1, | ||
| norm_ord: float = 1, | ||
| ): | ||
| self.guide_model = torch.func.vmap(guide_model) | ||
| self.std = std | ||
| self.gamma = gamma | ||
| self.mu = mu | ||
| self.scale = scale | ||
| self.power = power | ||
| self.norm_ord = norm_ord | ||
|
|
||
| def _log_likelihood( | ||
| self, | ||
| x_0_hat: torch.Tensor, | ||
| y: torch.Tensor, | ||
| t: torch.Tensor, | ||
| ) -> torch.Tensor: | ||
| # Compute L1 error between model prediction and observation | ||
| # NOTE: for now only Tweedie's formula to estimate clean state x_0 | ||
| y_x0: torch.Tensor = self.guide_model(x_0_hat) # (*_y,) | ||
| if y_x0.shape != y.shape: | ||
| raise ValueError( | ||
| f"Expected 'guide_model' output and y to have same shape, " | ||
| f"but got {y_x0.shape} and {y.shape}" | ||
| ) | ||
| err1 = torch.abs((y - y_x0)) ** self.norm_ord # (*_y,) | ||
|
|
||
| # Compute log-likelihood p(y|x_0_hat) | ||
|
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. This is relatively specific to DPS, I believe. Other model-based guidance approaches may use a different parameterization of the time-dependent variance (rather than with gamma), or a different loss altogether (cBottle TC uses BinaryCrossEntropy |
||
| var = self.std**2 + self.gamma * (t / self.mu) ** 2 # (,) | ||
| log_p = -0.5 * (err1 / var).sum() # (,) | ||
| return log_p | ||
|
|
||
| def __call__( | ||
| self, | ||
| x: torch.Tensor, | ||
| x_0_hat: torch.Tensor, | ||
| t: torch.Tensor, | ||
| y: torch.Tensor, | ||
| ) -> torch.Tensor: | ||
| B = x.shape[0] | ||
| ndim = x.ndim | ||
|
|
||
| # Parameters validation | ||
| if t.shape != (B,): | ||
| raise ValueError(f"Expected t to have shape {(B,)}, but got {t.shape}") | ||
| if y.shape[0] != B: | ||
| raise ValueError(f"Expected y to have batch size {B}, but got {y.shape[0]}") | ||
| if x_0_hat.shape != x.shape: | ||
| raise ValueError( | ||
| f"Expected x_0_hat and x to have same shape, " | ||
| f"but got {x_0_hat.shape} and {x.shape}" | ||
| ) | ||
|
|
||
| # NOTE: tensor is detached without requires_grad to save memory | ||
| # (not required with torch.func anyways) | ||
| x_0_hat = x_0_hat.clone().detach().requires_grad_(False) # (*_x,) | ||
|
|
||
| # Compute likelihood score | ||
| score = torch.func.vmap( | ||
| torch.func.grad( | ||
| self._log_likelihood, | ||
| argnums=0, | ||
| ) | ||
| )(x_0_hat, y, t) # (B, *_x,) | ||
|
|
||
| # Scale the likelihood score | ||
| scale = torch.where(t < 1, self.scale * t.pow(self.power), self.scale).view( | ||
| B, *([1] * (ndim - 1)) | ||
| ) # (B, 1, ..., 1) | ||
| score_mag = torch.abs(score).mean( | ||
| dim=tuple(range(1, ndim)), keepdim=True | ||
| ) # (B, 1, ..., 1) | ||
| score_scaled = ( | ||
| score * scale * t.view(B, *([1] * (ndim - 1))) / (1 + score_mag) | ||
| ) # (B, *_x) | ||
|
|
||
| return score_scaled | ||
|
|
||
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.
I would maybe call this DPSGuidance (to be more precise, this implementation also assumes Gaussian noise model), since there are several other guidance methods; see, e.g., https://arxiv.org/pdf/2503.11043 for an overview.