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

Make penalize_range more efficient #287

Merged
merged 4 commits into from
Aug 26, 2024
Merged
Show file tree
Hide file tree
Changes from all 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
11 changes: 5 additions & 6 deletions src/plenoptic/tools/optim.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,9 +126,8 @@ def penalize_range(
penalty
Penalty for values outside range
"""
# the indexing should flatten it
below_min = synth_img[synth_img < allowed_range[0]]
below_min = torch.pow(below_min - allowed_range[0], 2)
above_max = synth_img[synth_img > allowed_range[1]]
above_max = torch.pow(above_max - allowed_range[1], 2)
return torch.sum(torch.cat([below_min, above_max]))
# Using clip like this is equivalent to using boolean indexing (e.g.,
# synth_img[synth_img < allowed_range[0]]) but much faster
below_min = torch.clip(synth_img - allowed_range[0], max=0).pow(2).sum()
above_max = torch.clip(synth_img - allowed_range[1], min=0).pow(2).sum()
return below_min + above_max
13 changes: 13 additions & 0 deletions tests/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -458,3 +458,16 @@ def test_validate_metric_identical(self):
@pytest.mark.parametrize('model', ['frontend.OnOff.nograd'], indirect=True)
def test_remove_grad(self, model):
po.tools.validate.validate_model(model, device=DEVICE)


class TestOptim(object):

def test_penalize_range_above(self):
img = .5 * torch.ones((1, 1, 4, 4))
img[..., 0, :] = 2
assert po.tools.optim.penalize_range(img).item() == 4

def test_penalize_range_below(self):
img = .5 * torch.ones((1, 1, 4, 4))
img[..., 0, :] = -1
assert po.tools.optim.penalize_range(img).item() == 4