THUDM / ImageReward

[NeurIPS 2023] ImageReward: Learning and Evaluating Human Preferences for Text-to-image Generation
Apache License 2.0
1.07k stars 59 forks source link

Image Reward Fails to Load #21

Open mageofthesands opened 1 year ago

mageofthesands commented 1 year ago

ImageReward does not work. I am using stable-diffusion-webui-directml. I followed instructions from "Quick Start" as well as "Integration into Stable Diffusion Web UI". Attached screenshots to show that ImageReward is installed, and script is in then place instructions say.
imagerewardscriptfail imagerewardscriptfail2 imagerewardscriptfail3

tongyx361 commented 1 year ago

Thank you so much for the issue! Let's resolve it together 😀

This error seems a bit unusual because the line of code <title>ImageReward/image_reward.py at main THUDM/ImageReward GitHub</title> does not exist in the sdwebui/image_reward.py file.

Could you please provide the content of your stable-diffusion-webui/scripts/image_reward.py file?

mageofthesands commented 1 year ago

Here it is. I copied it from the file I downloaded from here.

`

<!DOCTYPE html>

ImageReward/image_reward.py at main · THUDM/ImageReward · GitHub
Permalink
main
Switch branches/tags

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?
Go to file
1 contributor

Users who have contributed to this file

121 lines (105 sloc) 4.14 KB
import os
import subprocess
import sys
from pathlib import Path
import gradio as gr
import modules.images as images
import modules.scripts as scripts
import torch
from huggingface_hub.constants import HUGGINGFACE_HUB_CACHE
from modules import sd_samplers, shared
from modules.processing import (
Processed,
StableDiffusionProcessing,
create_infotext,
process_images,
)
from modules.shared import cmd_opts, opts, state
try:
import ImageReward as reward
except ModuleNotFoundError as error:
print('"image-reward" package has not been properly installed. Installing...')
if subprocess.check_call(["pip", "install", "image-reward"]) == 0:
print(f'"image-reward" package is successfully installed!')
import ImageReward as reward
else:
print('"image-reward" package installation failed!')
print(
"Please open an issue with full error message at https://github.com/THUDM/ImageReward/issues"
)
def unload_image_reward_model():
del shared.image_reward_model
class Script(scripts.Script):
def title(self):
return "ImageReward - generate human preference scores"
def show(self, is_txt2img):
return True
def ui(self, is_txt2img):
with gr.Blocks():
with gr.Row():
gr.Markdown(
value="**Tip**: It will take a little time to **load** the ImageReward model before **the first generation**."
)
with gr.Row():
with gr.Column():
filter_out_low_scores = gr.Checkbox(
value=False, label="Filter out images with low scores"
)
with gr.Column():
lower_score_limit = gr.Textbox(value=0, label="Lower score limit")
with gr.Row():
gr.Markdown(
value="ImageReward model takes about **1,600 MB** of memory."
)
with gr.Row():
unload_button = gr.Button(value="Unload Model From Memory")
unload_button.click(unload_image_reward_model)
return [filter_out_low_scores, lower_score_limit]
def run(self, p, filter_out_low_scores, lower_score_limit):
try:
shared.image_reward_model # if loaded, do nothing
except AttributeError:
# load the model
if sys.platform == "win32":
download_root = HUGGINGFACE_HUB_CACHE
else:
download_root = None
print(f"Loading ImageReward model from {download_root}...")
shared.image_reward_model = reward.load(
"ImageReward-v1.0", download_root=download_root
) # using shared to make the model object global among modules
# preprocess parameters
if lower_score_limit != "":
lower_score_limit = float(lower_score_limit)
# generate images
proc = process_images(p)
# score
gens = proc.images
with torch.no_grad():
for img in gens:
score = shared.image_reward_model.score(p.prompt, img)
img.info["score"] = score
if img.info.get("parameters") is None:
img.info["parameters"] = f"ImageReward Score: {score:.4f}"
else:
img.info["parameters"] += f"\n ImageReward Score: {score:.4f}"
# filter out images with scores lower than the lower limit
if filter_out_low_scores:
imgs = list(filter(lambda x: x.info["score"] > lower_score_limit, gens))
else:
imgs = gens
# append score to info
infotexts = [img.info["parameters"] for img in imgs]
# sort to score
img_info_list = list(zip(imgs, infotexts))
img_info_list.sort(key=lambda x: x[0].info["score"], reverse=True)
imgs, infotexts = list(zip(*img_info_list))
# return Processed object
return Processed(
p=p,
images_list=imgs,
info=proc.info,
seed=proc.seed,
infotexts=infotexts,
index_of_first_image=proc.index_of_first_image,
)

`

tongyx361 commented 1 year ago

It looks like you have downloaded the HTML of a web page instead of our script code file. This is actually the wrong way to do it.

The contents of image_reward.py should be the following Python code:

https://github.com/THUDM/ImageReward/blob/ed5c202ec4ffa368ddc2546c08fa272ce86bca8e/sdwebui/image_reward.py#L1-L121

instead of the HTML code starting with

<meta name="optimizely-datafile" content="{&quot;groups&quot;: [], ...
mageofthesands commented 1 year ago

When I right click that script code file, and "save link as..." I get a file that starts off with

<!DOCTYPE html>
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system">
  <head>
    <meta charset="utf-8">
  <link rel="dns-prefetch" href="https://github.githubassets.com">
  <link rel="dns-prefetch" href="https://avatars.githubusercontent.com">
  <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com">
  <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">
  <link rel="preconnect" href="https://github.githubassets.com" crossorigin>
  <link rel="preconnect" href="https://avatars.githubusercontent.com">
mageofthesands commented 1 year ago

I edited with .py with the information listed. I still get get an error that ImageReward is not installed.

tongyx361 commented 1 year ago

When I right click that script code file, and "save link as..." I get a file that starts off with

<!DOCTYPE html>
<html lang="en" data-color-mode="auto" data-light-theme="light" data-dark-theme="dark" data-a11y-animated-images="system">
  <head>
    <meta charset="utf-8">
  <link rel="dns-prefetch" href="https://github.githubassets.com">
  <link rel="dns-prefetch" href="https://avatars.githubusercontent.com">
  <link rel="dns-prefetch" href="https://github-cloud.s3.amazonaws.com">
  <link rel="dns-prefetch" href="https://user-images.githubusercontent.com/">
  <link rel="preconnect" href="https://github.githubassets.com" crossorigin>
  <link rel="preconnect" href="https://avatars.githubusercontent.com">

I edited with .py with the information listed. I still get get an error that ImageReward is not installed.

The link we provided for the script file points to its GitHub page, not the raw content. So "save as link" will save the HTML code of the GitHub page, not the actual Python code of the script.

If the image_reward.py code you have is correct Python code yet still triggered an error, that would be strange.

Could you provide the full error message?

mageofthesands commented 1 year ago

imagerewardfail1

mageofthesands commented 1 year ago

imagereward6323851

Starting from launching.

tongyx361 commented 1 year ago

imagereward6323851

Starting from launching.

File "F:\AI\Diffusion\stable-diffusion-webui-directml\scripts\image_reward.py", line 1
     import os 
IndentationError: unexpected indent 

The error above means the indentation syntax in your image_reward.py is wrong, which might be caused by some copying mistake.

You might try directly downloading the image_reward.py with the button shown below, and move it into the scripts/ directory. image

mageofthesands commented 1 year ago

Steps followed. On launch, the software said that ImageReward was installed incorrectly, and it would now do so correctly. New issue. tqdm.exe is not found. I attempted to correct myself, but tqdm is already installed. It looks like Image Reward installed tqdm, but couldn't run it? imagereward64231042

tongyx361 commented 1 year ago

Steps followed. On launch, the software said that ImageReward was installed incorrectly, and it would now do so correctly. New issue. tqdm.exe is not found. I attempted to correct myself, but tqdm is already installed. It looks like Image Reward installed tqdm, but couldn't run it? imagereward64231042

The key error message here is

WARNING: Failed to write executable - trying to use .deleteme logic
ERROR: Could not install packages due to an OSError: [WinError 2] The system cannot find the file specified: 'C:\\Python311\\\\Scripts\\\\tqdm.exe' -> 'C. \\\Python311\\Scripts\\\tqdm.exe.deleteme'

pip may have failed to write to the executable due to lack of permissions, etc., causing the "image-reward" pip package to fail to be installed.

"tqdm" is one of the dependencies of "image-reward". You are on the right track: you could try installing the "tqdm" package manually. But you may have missed a special design of SD Web UI: webui-user.bat uses the automatically created venv environment, while you should have tried to install "tqdm" in the machine's Python when you fixed it, and the two environments are different, so the error was not fixed.

You can refer to this issue to try to install "tqdm" manually in venv, and install "image-reward" again.

mageofthesands commented 1 year ago

It's now loading. Script is working. Although, I guess I can't run it at the same time as the StylePile Script. On the image browser though, it's not letting me use the Generate ImageReward Scores for all images button. I hope this has assisted in development of your software. imagereward652023836 imagereward652023852 imagereward652023854

tongyx361 commented 1 year ago

It's now loading. Script is working. Although, I guess I can't run it at the same time as the StylePile Script. On the image browser though, it's not letting me use the Generate ImageReward Scores for all images button. I hope this has assisted in development of your software. imagereward652023836 imagereward652023852 imagereward652023854

Glad you got the error resolved! If you encounter any related errors/new bugs in the future, please feel free to reply under this issue/open a new one, so that we can work together to make this project better!👍

Regarding the issue with running other scripts at the same time, I'm sorry, but the SD Web UI hasn't supported running multiple scripts at the same time so far.

Also, from your reply and image, it looks like "the StylePile script" is integrated with ImageReward, and I'm glad that other developers are willing to use our work!

But I failed to retrieve ImageReward in the StylePile code repository. could you please provide a full UI screenshot of your last image? We'd like to get more insight into the application of our work.

mageofthesands commented 1 year ago

It doesn't look like there is any integration between the two. This is what a StylePile looks like. A bunch of variables, either set or pulled from random. I should be able to generate Image Reward scores from the image browser, right? That button is unusable.
imagereward6623822

tongyx361 commented 1 year ago

It doesn't look like there is any integration between the two. This is what a StylePile looks like. A bunch of variables, either set or pulled from random. I should be able to generate Image Reward scores from the image browser, right? That button is unusable. imagereward6623822

The UI is quite different from a usual SD Web UI's interface. Are you using the extension edition of StockPile? I wonder how I can get the same UI as yours.

It seems that you want to score these images with ImageReward? We're sorry that we could have been only able to ensure generating ImageReward Score with the ImageReward script. Perhaps you could use "Send to txt2img" or "Send to img2img" to use the script in the "txt2img" or "img2img" tab to generate ImageReward scores for the images.

mageofthesands commented 1 year ago

Ah, yes. I am using the "Catppuccin Theme". https://github.com/catppuccin/stable-diffusion-webui I wanted a dark mode. I couldn't see the tool tips otherwise. Also the Image Browser extension. https://github.com/AlUlkesh/stable-diffusion-webui-images-browser I forget what isn't default.

Are you saying that you didn't place that button there? It was there before I was able to get the script working.

imagereward6623948

tongyx361 commented 1 year ago

Thank you so much! We'll delve into them soon. Please stay tuned.