-
Notifications
You must be signed in to change notification settings - Fork 80
feat(evaluation): add ImageRewardMetric #548
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
davidberenstein1957
wants to merge
8
commits into
main
Choose a base branch
from
feat/metric-image_reward
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
8 commits
Select commit
Hold shift + click to select a range
1e5bfc4
feat(evaluation): add ImageRewardMetric
davidberenstein1957 3d99855
fix(evaluation): use List-based scores pattern matching Pruna standards
davidberenstein1957 45f6e6c
fix(evaluation): fix linting issues
davidberenstein1957 0b18959
fix(evaluation): fix import usage
davidberenstein1957 bb517b2
fix(evaluation): resolve ImageReward CI - remove from deps, fix insta…
davidberenstein1957 6cb793f
fix(evaluation): skip docstring check for metrics modules
davidberenstein1957 1e273e0
ci: trigger new CI
davidberenstein1957 165577e
Apply suggestions from code review
davidberenstein1957 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
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,143 @@ | ||
| # Copyright 2025 - Pruna AI GmbH. All rights reserved. | ||
| # | ||
| # 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. | ||
|
|
||
| """ | ||
| Image Reward Metric for Pruna. | ||
|
|
||
| This metric computes image reward scores using the ImageReward library. | ||
|
|
||
| Based on the InferBench implementation: | ||
| https://github.com/PrunaAI/InferBench | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| from typing import Any, List | ||
|
|
||
| import torch | ||
| from PIL import Image | ||
|
|
||
| from pruna.engine.utils import set_to_best_available_device | ||
| from pruna.evaluation.metrics.metric_stateful import StatefulMetric | ||
| from pruna.evaluation.metrics.registry import MetricRegistry | ||
| from pruna.evaluation.metrics.result import MetricResult | ||
| from pruna.evaluation.metrics.utils import SINGLE, get_call_type_for_single_metric, metric_data_processor | ||
| from pruna.logging.logger import pruna_logger | ||
|
|
||
| METRIC_IMAGE_REWARD = "image_reward" | ||
|
|
||
|
|
||
| @MetricRegistry.register(METRIC_IMAGE_REWARD) | ||
| class ImageRewardMetric(StatefulMetric): | ||
| """ | ||
| Image Reward metric for evaluating image-text alignment. | ||
|
|
||
| This metric uses the ImageReward model to compute how well generated images | ||
| match their text prompts based on learned human preferences. | ||
| Higher scores indicate better alignment. | ||
|
|
||
| Reference | ||
| ---------- | ||
| ImageReward: https://github.com/thaosu/ImageReward | ||
|
|
||
| Parameters | ||
| ---------- | ||
| *args : Any | ||
| Additional arguments. | ||
| device : str | torch.device | None, optional | ||
| The device to be used, e.g., 'cuda' or 'cpu'. Default is None. | ||
| If None, the best available device will be used. | ||
| model_name : str, optional | ||
| The ImageReward model to use. Default is "ImageReward-v1.0". | ||
| call_type : str, optional | ||
| The type of call to use for the metric. | ||
| **kwargs : Any | ||
| Additional keyword arguments. | ||
| """ | ||
|
|
||
| scores: List[float] | ||
| default_call_type: str = "y" | ||
| higher_is_better: bool = True | ||
| metric_name: str = METRIC_IMAGE_REWARD | ||
| runs_on: List[str] = ["cpu", "cuda", "mps"] | ||
|
|
||
| def __init__( | ||
| self, | ||
| *args, | ||
| device: str | torch.device | None = None, | ||
| model_name: str = "ImageReward-v1.0", | ||
| call_type: str = SINGLE, | ||
| **kwargs, | ||
| ) -> None: | ||
| super().__init__(device=device) | ||
| self.device = set_to_best_available_device(device) | ||
| self.model_name = model_name | ||
| self.call_type = get_call_type_for_single_metric(call_type, self.default_call_type) | ||
|
|
||
| import ImageReward as ImageRewardModule | ||
|
|
||
| self.model = ImageRewardModule.load(self.model_name, device=str(self.device)) | ||
| self.add_state("scores", []) | ||
|
|
||
| @torch.no_grad() | ||
| def update(self, x: List[Any] | torch.Tensor, gt: torch.Tensor, outputs: torch.Tensor) -> None: | ||
| """ | ||
| Update the metric with new batch data. | ||
|
|
||
| Parameters | ||
| ---------- | ||
| x : List[Any] | torch.Tensor | ||
| The input data (text prompts). | ||
| gt : torch.Tensor | ||
| The ground truth / cached images. | ||
| outputs : torch.Tensor | ||
| The output images to score. | ||
| """ | ||
| inputs = metric_data_processor(x, gt, outputs, self.call_type) | ||
| images = inputs[0] | ||
| prompts = x if isinstance(x, list) else [""] * len(images) | ||
|
|
||
| for i, image in enumerate(images): | ||
| if isinstance(image, torch.Tensor): | ||
| image = self._tensor_to_pil(image) | ||
|
|
||
| prompt = prompts[i] if i < len(prompts) else "" | ||
| score = self.model.score(prompt, image) | ||
| self.scores.append(score) | ||
|
|
||
| def compute(self) -> MetricResult: | ||
| """ | ||
| Compute the mean ImageReward metric. | ||
|
|
||
| Returns | ||
| ------- | ||
| MetricResult | ||
| The mean ImageReward metric. | ||
| """ | ||
| if not self.scores: | ||
| return MetricResult(self.metric_name, self.__dict__, 0.0) | ||
|
|
||
| import numpy as np | ||
|
|
||
| mean_score = float(np.mean(self.scores)) | ||
| return MetricResult(self.metric_name, self.__dict__, mean_score) | ||
|
|
||
| def _tensor_to_pil(self, tensor: torch.Tensor) -> Image.Image: | ||
| """Convert tensor to PIL Image.""" | ||
| if tensor.ndim == 4: | ||
| tensor = tensor[0] | ||
| if tensor.max() > 1: | ||
| tensor = tensor / 255.0 | ||
| np_img = (tensor.cpu().numpy() * 255).astype("uint8") | ||
| return Image.fromarray(np_img.transpose(1, 2, 0)) |
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.