Spaces:
Sleeping
Sleeping
refactoring for Flux
Browse files- __pycache__/arguments.cpython-310.pyc +0 -0
- __pycache__/main.cpython-310.pyc +0 -0
- app.py +15 -9
- arguments.py +42 -9
- assets/example_prompts.txt +2 -0
- main.py +58 -41
- models/RewardFlux.py +436 -0
- models/RewardPixart.py +2 -3
- models/RewardStableDiffusion.py +1 -1
- models/RewardStableDiffusionXL.py +12 -8
- models/__init__.py +1 -1
- models/__pycache__/RewardPixart.cpython-310.pyc +0 -0
- models/__pycache__/RewardStableDiffusion.cpython-310.pyc +0 -0
- models/__pycache__/RewardStableDiffusionXL.cpython-310.pyc +0 -0
- models/__pycache__/__init__.cpython-310.pyc +0 -0
- models/__pycache__/utils.cpython-310.pyc +0 -0
- models/utils.py +86 -5
- requirements.txt +1 -1
- rewards/__pycache__/__init__.cpython-310.pyc +0 -0
- rewards/__pycache__/aesthetic.cpython-310.pyc +0 -0
- rewards/__pycache__/base_reward.cpython-310.pyc +0 -0
- rewards/__pycache__/clip.cpython-310.pyc +0 -0
- rewards/__pycache__/hps.cpython-310.pyc +0 -0
- rewards/__pycache__/imagereward.cpython-310.pyc +0 -0
- rewards/__pycache__/pickscore.cpython-310.pyc +0 -0
- rewards/__pycache__/utils.cpython-310.pyc +0 -0
- training/__pycache__/__init__.cpython-310.pyc +0 -0
- training/__pycache__/optim.cpython-310.pyc +0 -0
- training/__pycache__/trainer.cpython-310.pyc +0 -0
- training/trainer.py +22 -6
__pycache__/arguments.cpython-310.pyc
ADDED
Binary file (2.52 kB). View file
|
|
__pycache__/main.cpython-310.pyc
ADDED
Binary file (8.12 kB). View file
|
|
app.py
CHANGED
@@ -59,8 +59,8 @@ def start_over(gallery_state, loaded_model_setup):
|
|
59 |
|
60 |
def setup_model(prompt, model, seed, num_iterations, learning_rate, hps_w, imgrw_w, pcks_w, clip_w, progress=gr.Progress(track_tqdm=True)):
|
61 |
if prompt is None:
|
62 |
-
raise gr.Error("You forgot
|
63 |
-
|
64 |
"""Clear CUDA memory before starting the training."""
|
65 |
torch.cuda.empty_cache() # Free up cached memory
|
66 |
|
@@ -81,8 +81,13 @@ def setup_model(prompt, model, seed, num_iterations, learning_rate, hps_w, imgrw
|
|
81 |
args.pickscore_weighting = pcks_w
|
82 |
args.clip_weighting = clip_w
|
83 |
|
84 |
-
|
85 |
-
|
|
|
|
|
|
|
|
|
|
|
86 |
|
87 |
return None, loaded_setup
|
88 |
|
@@ -95,11 +100,12 @@ def generate_image(setup_args, num_iterations):
|
|
95 |
dtype = setup_args[3]
|
96 |
shape = setup_args[4]
|
97 |
enable_grad = setup_args[5]
|
|
|
98 |
|
99 |
-
settings = setup_args[
|
100 |
print(f"SETTINGS: {settings}")
|
101 |
|
102 |
-
save_dir = f"{args.save_dir}/{args.task}/{settings}/{args.prompt}"
|
103 |
clean_dir(save_dir)
|
104 |
|
105 |
try:
|
@@ -119,7 +125,7 @@ def generate_image(setup_args, num_iterations):
|
|
119 |
thread_status["running"] = True # Mark thread as running
|
120 |
try:
|
121 |
execute_task(
|
122 |
-
args, trainer, device, dtype, shape, enable_grad, settings, progress_callback
|
123 |
)
|
124 |
except torch.cuda.OutOfMemoryError as e:
|
125 |
print(f"CUDA Out of Memory Error: {e}")
|
@@ -154,7 +160,7 @@ def generate_image(setup_args, num_iterations):
|
|
154 |
|
155 |
if error_status["error_occurred"]:
|
156 |
torch.cuda.empty_cache() # Free up cached memory
|
157 |
-
yield (None, "CUDA out of memory.", None)
|
158 |
else:
|
159 |
main_thread.join() # Ensure thread completion
|
160 |
final_image_path = os.path.join(save_dir, "best_image.png")
|
@@ -213,7 +219,7 @@ with gr.Blocks(analytics_enabled=False) as demo:
|
|
213 |
with gr.Column():
|
214 |
prompt = gr.Textbox(label="Prompt")
|
215 |
with gr.Row():
|
216 |
-
chosen_model = gr.Dropdown(["sd-turbo", "sdxl-turbo", "pixart", "hyper-sd"], label="Model", value="sd-turbo")
|
217 |
seed = gr.Number(label="seed", value=0)
|
218 |
model_status = gr.Textbox(label="model status", visible=False)
|
219 |
|
|
|
59 |
|
60 |
def setup_model(prompt, model, seed, num_iterations, learning_rate, hps_w, imgrw_w, pcks_w, clip_w, progress=gr.Progress(track_tqdm=True)):
|
61 |
if prompt is None:
|
62 |
+
raise gr.Error("You forgot the prompt !")
|
63 |
+
|
64 |
"""Clear CUDA memory before starting the training."""
|
65 |
torch.cuda.empty_cache() # Free up cached memory
|
66 |
|
|
|
81 |
args.pickscore_weighting = pcks_w
|
82 |
args.clip_weighting = clip_w
|
83 |
|
84 |
+
if model == "flux":
|
85 |
+
args.cpu_offloading = True
|
86 |
+
args.enable_multi_apply= True
|
87 |
+
args.multi_step_model = "flux"
|
88 |
+
|
89 |
+
args, trainer, device, dtype, shape, enable_grad, multi_apply_fn, settings = setup(args)
|
90 |
+
loaded_setup = [args, trainer, device, dtype, shape, enable_grad, multi_apply_fn, settings]
|
91 |
|
92 |
return None, loaded_setup
|
93 |
|
|
|
100 |
dtype = setup_args[3]
|
101 |
shape = setup_args[4]
|
102 |
enable_grad = setup_args[5]
|
103 |
+
multi_apply_fn = setup_args[6]
|
104 |
|
105 |
+
settings = setup_args[7]
|
106 |
print(f"SETTINGS: {settings}")
|
107 |
|
108 |
+
save_dir = f"{args.save_dir}/{args.task}/{settings}/{args.prompt[:150]}"
|
109 |
clean_dir(save_dir)
|
110 |
|
111 |
try:
|
|
|
125 |
thread_status["running"] = True # Mark thread as running
|
126 |
try:
|
127 |
execute_task(
|
128 |
+
args, trainer, device, dtype, shape, enable_grad, multi_apply_fn, settings, progress_callback
|
129 |
)
|
130 |
except torch.cuda.OutOfMemoryError as e:
|
131 |
print(f"CUDA Out of Memory Error: {e}")
|
|
|
160 |
|
161 |
if error_status["error_occurred"]:
|
162 |
torch.cuda.empty_cache() # Free up cached memory
|
163 |
+
yield (None, "CUDA out of memory. Please reduce your batch size or image resolution.", None)
|
164 |
else:
|
165 |
main_thread.join() # Ensure thread completion
|
166 |
final_image_path = os.path.join(save_dir, "best_image.png")
|
|
|
219 |
with gr.Column():
|
220 |
prompt = gr.Textbox(label="Prompt")
|
221 |
with gr.Row():
|
222 |
+
chosen_model = gr.Dropdown(["sd-turbo", "sdxl-turbo", "pixart", "hyper-sd", "flux"], label="Model", value="sd-turbo")
|
223 |
seed = gr.Number(label="seed", value=0)
|
224 |
model_status = gr.Textbox(label="model status", visible=False)
|
225 |
|
arguments.py
CHANGED
@@ -38,36 +38,57 @@ def parse_args():
|
|
38 |
parser.add_argument("--seed", type=int, help="Seed to use", default=0)
|
39 |
|
40 |
# reward losses
|
41 |
-
parser.add_argument(
|
|
|
|
|
42 |
parser.add_argument(
|
43 |
"--hps_weighting", type=float, help="Weighting for HPS", default=5.0
|
44 |
)
|
45 |
-
parser.add_argument(
|
|
|
|
|
|
|
|
|
|
|
46 |
parser.add_argument(
|
47 |
"--imagereward_weighting",
|
48 |
type=float,
|
49 |
help="Weighting for ImageReward",
|
50 |
default=1.0,
|
51 |
)
|
52 |
-
parser.add_argument(
|
|
|
|
|
53 |
parser.add_argument(
|
54 |
"--clip_weighting", type=float, help="Weighting for CLIP", default=0.01
|
55 |
)
|
56 |
-
parser.add_argument(
|
|
|
|
|
|
|
|
|
|
|
57 |
parser.add_argument(
|
58 |
"--pickscore_weighting",
|
59 |
type=float,
|
60 |
help="Weighting for PickScore",
|
61 |
default=0.05,
|
62 |
)
|
63 |
-
parser.add_argument(
|
|
|
|
|
|
|
|
|
|
|
64 |
parser.add_argument(
|
65 |
"--aesthetic_weighting",
|
66 |
type=float,
|
67 |
help="Weighting for Aesthetic",
|
68 |
default=0.0,
|
69 |
)
|
70 |
-
parser.add_argument(
|
|
|
|
|
71 |
parser.add_argument(
|
72 |
"--reg_weight", type=float, help="Regularization weight", default=0.01
|
73 |
)
|
@@ -104,8 +125,20 @@ def parse_args():
|
|
104 |
parser.add_argument("--no_optim", default=False, action="store_true")
|
105 |
parser.add_argument("--imageselect", default=False, action="store_true")
|
106 |
parser.add_argument("--memsave", default=False, action="store_true")
|
107 |
-
parser.add_argument("--
|
108 |
-
parser.add_argument("--device_id", type=
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
109 |
|
110 |
args = parser.parse_args()
|
111 |
-
return args
|
|
|
38 |
parser.add_argument("--seed", type=int, help="Seed to use", default=0)
|
39 |
|
40 |
# reward losses
|
41 |
+
parser.add_argument(
|
42 |
+
"--disable_hps", default=True, action="store_false", dest="enable_hps"
|
43 |
+
)
|
44 |
parser.add_argument(
|
45 |
"--hps_weighting", type=float, help="Weighting for HPS", default=5.0
|
46 |
)
|
47 |
+
parser.add_argument(
|
48 |
+
"--disable_imagereward",
|
49 |
+
default=True,
|
50 |
+
action="store_false",
|
51 |
+
dest="enable_imagereward",
|
52 |
+
)
|
53 |
parser.add_argument(
|
54 |
"--imagereward_weighting",
|
55 |
type=float,
|
56 |
help="Weighting for ImageReward",
|
57 |
default=1.0,
|
58 |
)
|
59 |
+
parser.add_argument(
|
60 |
+
"--disable_clip", default=True, action="store_false", dest="enable_clip"
|
61 |
+
)
|
62 |
parser.add_argument(
|
63 |
"--clip_weighting", type=float, help="Weighting for CLIP", default=0.01
|
64 |
)
|
65 |
+
parser.add_argument(
|
66 |
+
"--disable_pickscore",
|
67 |
+
default=True,
|
68 |
+
action="store_false",
|
69 |
+
dest="enable_pickscore",
|
70 |
+
)
|
71 |
parser.add_argument(
|
72 |
"--pickscore_weighting",
|
73 |
type=float,
|
74 |
help="Weighting for PickScore",
|
75 |
default=0.05,
|
76 |
)
|
77 |
+
parser.add_argument(
|
78 |
+
"--disable_aesthetic",
|
79 |
+
default=False,
|
80 |
+
action="store_false",
|
81 |
+
dest="enable_aesthetic",
|
82 |
+
)
|
83 |
parser.add_argument(
|
84 |
"--aesthetic_weighting",
|
85 |
type=float,
|
86 |
help="Weighting for Aesthetic",
|
87 |
default=0.0,
|
88 |
)
|
89 |
+
parser.add_argument(
|
90 |
+
"--disable_reg", default=True, action="store_false", dest="enable_reg"
|
91 |
+
)
|
92 |
parser.add_argument(
|
93 |
"--reg_weight", type=float, help="Regularization weight", default=0.01
|
94 |
)
|
|
|
125 |
parser.add_argument("--no_optim", default=False, action="store_true")
|
126 |
parser.add_argument("--imageselect", default=False, action="store_true")
|
127 |
parser.add_argument("--memsave", default=False, action="store_true")
|
128 |
+
parser.add_argument("--dtype", type=str, help="Data type to use", default="float16")
|
129 |
+
parser.add_argument("--device_id", type=str, help="Device ID to use", default=None)
|
130 |
+
parser.add_argument(
|
131 |
+
"--cpu_offloading",
|
132 |
+
help="Enable CPU offloading",
|
133 |
+
default=False,
|
134 |
+
action="store_true",
|
135 |
+
)
|
136 |
+
|
137 |
+
# optional multi-step model
|
138 |
+
parser.add_argument("--enable_multi_apply", default=False, action="store_true")
|
139 |
+
parser.add_argument(
|
140 |
+
"--multi_step_model", type=str, help="Model to use", default="flux"
|
141 |
+
)
|
142 |
|
143 |
args = parser.parse_args()
|
144 |
+
return args
|
assets/example_prompts.txt
CHANGED
@@ -12,6 +12,7 @@ High quality photo of a monkey astronaut infront of the Eiffel tower
|
|
12 |
A bird with 8 legs
|
13 |
A brain riding a rocketship towards the moon
|
14 |
A toaster riding a bike
|
|
|
15 |
A blue scooter is parked near a curb in front of a green vintage car
|
16 |
A curious, orange fox and a fluffy, white rabbit, playing together in a lush, green meadow filled with yellow dandelions
|
17 |
An epic oil painting: a red portal infront of a cityscape, a solitary figure, and a colorful sky over snowy mountains
|
@@ -19,6 +20,7 @@ A futuristic painting: Red car escapes giant shark's leap, right; ominous mounta
|
|
19 |
A majestic, resilient sea ship navigates the icy wilderness in the style of Star Wars
|
20 |
Dwayne Johnson depicted as a philosopher king in an academic painting by Greg Rutkowski
|
21 |
Taylor Swift depicted as a prime minister in an academic painting by Kandinsky
|
|
|
22 |
A watercolor painting: a floating island, multiple animals under a majestic tree with golden leaves, and a vibrant rainbow stretching across a pastel sky
|
23 |
A Japanese-style ink painting: a traditional wooden bridge, a pagoda, a lone samurai warrior, and cherry blossom petals over a tranquil river
|
24 |
A retro-futuristic pixel art scene: a flying car, an imperial senate building, a green park, and a purple sunset
|
|
|
12 |
A bird with 8 legs
|
13 |
A brain riding a rocketship towards the moon
|
14 |
A toaster riding a bike
|
15 |
+
An upside-down snowman in a winter scene, with the snowman wearing a smile.
|
16 |
A blue scooter is parked near a curb in front of a green vintage car
|
17 |
A curious, orange fox and a fluffy, white rabbit, playing together in a lush, green meadow filled with yellow dandelions
|
18 |
An epic oil painting: a red portal infront of a cityscape, a solitary figure, and a colorful sky over snowy mountains
|
|
|
20 |
A majestic, resilient sea ship navigates the icy wilderness in the style of Star Wars
|
21 |
Dwayne Johnson depicted as a philosopher king in an academic painting by Greg Rutkowski
|
22 |
Taylor Swift depicted as a prime minister in an academic painting by Kandinsky
|
23 |
+
A swirling, multicolored portal emerges from the depths of an ocean of coffee, with waves of the rich liquid gently rippling outward. The portal engulfs a coffee cup, which serves as a gateway to a fantastical dimension. Digital art.
|
24 |
A watercolor painting: a floating island, multiple animals under a majestic tree with golden leaves, and a vibrant rainbow stretching across a pastel sky
|
25 |
A Japanese-style ink painting: a traditional wooden bridge, a pagoda, a lone samurai warrior, and cherry blossom petals over a tranquil river
|
26 |
A retro-futuristic pixel art scene: a flying car, an imperial senate building, a green park, and a purple sunset
|
main.py
CHANGED
@@ -9,13 +9,13 @@ from pytorch_lightning import seed_everything
|
|
9 |
from tqdm import tqdm
|
10 |
|
11 |
from arguments import parse_args
|
12 |
-
from models import get_model
|
13 |
from rewards import get_reward_losses
|
14 |
from training import LatentNoiseTrainer, get_optimizer
|
15 |
|
16 |
|
17 |
def setup(args):
|
18 |
-
|
19 |
seed_everything(args.seed)
|
20 |
bf.makedirs(f"{args.save_dir}/logs/{args.task}")
|
21 |
# Set up logging and name settings
|
@@ -46,21 +46,22 @@ def setup(args):
|
|
46 |
if args.device_id is not None:
|
47 |
logging.info(f"Using CUDA device {args.device_id}")
|
48 |
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
|
49 |
-
os.environ["
|
50 |
-
|
51 |
-
|
52 |
-
|
53 |
-
|
54 |
-
|
55 |
-
dtype = torch.float16
|
56 |
# Get reward losses
|
57 |
reward_losses = get_reward_losses(args, dtype, device, args.cache_dir)
|
58 |
|
59 |
# Get model and noise trainer
|
60 |
-
|
|
|
|
|
61 |
trainer = LatentNoiseTrainer(
|
62 |
reward_losses=reward_losses,
|
63 |
-
model=
|
64 |
n_iters=args.n_iters,
|
65 |
n_inference_steps=args.n_inference_steps,
|
66 |
seed=args.seed,
|
@@ -75,41 +76,57 @@ def setup(args):
|
|
75 |
)
|
76 |
|
77 |
# Create latents
|
78 |
-
if args.model
|
79 |
-
|
80 |
-
|
|
|
|
|
|
|
81 |
shape = (
|
82 |
1,
|
83 |
-
|
84 |
-
height //
|
85 |
-
width //
|
86 |
)
|
87 |
else:
|
88 |
-
height =
|
89 |
-
width =
|
90 |
shape = (
|
91 |
1,
|
92 |
-
|
93 |
-
height //
|
94 |
-
width //
|
95 |
)
|
96 |
enable_grad = not args.no_optim
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
97 |
|
98 |
-
return args, trainer, device, dtype, shape, enable_grad, settings
|
99 |
|
100 |
-
def execute_task(args, trainer, device, dtype, shape, enable_grad, settings, progress_callback=None):
|
101 |
-
|
102 |
if args.task == "single":
|
103 |
init_latents = torch.randn(shape, device=device, dtype=dtype)
|
104 |
latents = torch.nn.Parameter(init_latents, requires_grad=enable_grad)
|
105 |
optimizer = get_optimizer(args.optim, latents, args.lr, args.nesterov)
|
106 |
-
save_dir = f"{args.save_dir}/{args.task}/{settings}/{args.prompt}"
|
107 |
os.makedirs(f"{save_dir}", exist_ok=True)
|
108 |
-
best_image, total_init_rewards, total_best_rewards = trainer.train(
|
109 |
-
latents, args.prompt, optimizer, save_dir, progress_callback=progress_callback
|
110 |
)
|
111 |
best_image.save(f"{save_dir}/best_image.png")
|
112 |
-
|
|
|
113 |
elif args.task == "example-prompts":
|
114 |
fo = open("assets/example_prompts.txt", "r")
|
115 |
prompts = fo.readlines()
|
@@ -121,11 +138,11 @@ def execute_task(args, trainer, device, dtype, shape, enable_grad, settings, pro
|
|
121 |
optimizer = get_optimizer(args.optim, latents, args.lr, args.nesterov)
|
122 |
|
123 |
prompt = prompt.strip()
|
124 |
-
name = f"{i:03d}_{prompt}.png"
|
125 |
save_dir = f"{args.save_dir}/{args.task}/{settings}/{name}"
|
126 |
os.makedirs(save_dir, exist_ok=True)
|
127 |
-
best_image, init_rewards, best_rewards = trainer.train(
|
128 |
-
latents, prompt, optimizer, save_dir
|
129 |
)
|
130 |
if i == 0:
|
131 |
total_best_rewards = {k: 0.0 for k in best_rewards.keys()}
|
@@ -134,6 +151,7 @@ def execute_task(args, trainer, device, dtype, shape, enable_grad, settings, pro
|
|
134 |
total_best_rewards[k] += best_rewards[k]
|
135 |
total_init_rewards[k] += init_rewards[k]
|
136 |
best_image.save(f"{save_dir}/best_image.png")
|
|
|
137 |
logging.info(f"Initial rewards: {init_rewards}")
|
138 |
logging.info(f"Best rewards: {best_rewards}")
|
139 |
for k in total_best_rewards.keys():
|
@@ -159,8 +177,8 @@ def execute_task(args, trainer, device, dtype, shape, enable_grad, settings, pro
|
|
159 |
optimizer = get_optimizer(args.optim, latents, args.lr, args.nesterov)
|
160 |
|
161 |
prompt = prompt.strip()
|
162 |
-
best_image, init_rewards, best_rewards = trainer.train(
|
163 |
-
latents, prompt, optimizer
|
164 |
)
|
165 |
if i == 0:
|
166 |
total_best_rewards = {k: 0.0 for k in best_rewards.keys()}
|
@@ -186,8 +204,8 @@ def execute_task(args, trainer, device, dtype, shape, enable_grad, settings, pro
|
|
186 |
f"{args.save_dir}/{args.task}/{settings}/{index}", exist_ok=True
|
187 |
)
|
188 |
prompt = sample["Prompt"]
|
189 |
-
best_image, init_rewards, best_rewards = trainer.train(
|
190 |
-
latents, prompt, optimizer
|
191 |
)
|
192 |
best_image.save(
|
193 |
f"{args.save_dir}/{args.task}/{settings}/{index}/best_image.png"
|
@@ -252,8 +270,8 @@ def execute_task(args, trainer, device, dtype, shape, enable_grad, settings, pro
|
|
252 |
optimizer = get_optimizer(args.optim, latents, args.lr, args.nesterov)
|
253 |
|
254 |
prompt = metadata["prompt"]
|
255 |
-
best_image, init_rewards, best_rewards = trainer.train(
|
256 |
-
latents, prompt, optimizer
|
257 |
)
|
258 |
logging.info(f"Initial rewards: {init_rewards}")
|
259 |
logging.info(f"Best rewards: {best_rewards}")
|
@@ -279,9 +297,8 @@ def execute_task(args, trainer, device, dtype, shape, enable_grad, settings, pro
|
|
279 |
|
280 |
def main():
|
281 |
args = parse_args()
|
282 |
-
args, trainer, device, dtype, shape, enable_grad, settings = setup(args)
|
283 |
-
execute_task(args, trainer, device, dtype, shape, enable_grad, settings)
|
284 |
-
|
285 |
|
286 |
if __name__ == "__main__":
|
287 |
main()
|
|
|
9 |
from tqdm import tqdm
|
10 |
|
11 |
from arguments import parse_args
|
12 |
+
from models import get_model, get_multi_apply_fn
|
13 |
from rewards import get_reward_losses
|
14 |
from training import LatentNoiseTrainer, get_optimizer
|
15 |
|
16 |
|
17 |
def setup(args):
|
18 |
+
|
19 |
seed_everything(args.seed)
|
20 |
bf.makedirs(f"{args.save_dir}/logs/{args.task}")
|
21 |
# Set up logging and name settings
|
|
|
46 |
if args.device_id is not None:
|
47 |
logging.info(f"Using CUDA device {args.device_id}")
|
48 |
os.environ["CUDA_DEVICE_ORDER"] = "PCI_BUS_ID"
|
49 |
+
os.environ["CUDA_VISIBLE_DEVICES"] = args.device_id
|
50 |
+
device = torch.device("cuda")
|
51 |
+
if args.dtype == "float32":
|
52 |
+
dtype = torch.float32
|
53 |
+
elif args.dtype == "float16":
|
54 |
+
dtype = torch.float16
|
|
|
55 |
# Get reward losses
|
56 |
reward_losses = get_reward_losses(args, dtype, device, args.cache_dir)
|
57 |
|
58 |
# Get model and noise trainer
|
59 |
+
pipe = get_model(
|
60 |
+
args.model, dtype, device, args.cache_dir, args.memsave, args.cpu_offloading
|
61 |
+
)
|
62 |
trainer = LatentNoiseTrainer(
|
63 |
reward_losses=reward_losses,
|
64 |
+
model=pipe,
|
65 |
n_iters=args.n_iters,
|
66 |
n_inference_steps=args.n_inference_steps,
|
67 |
seed=args.seed,
|
|
|
76 |
)
|
77 |
|
78 |
# Create latents
|
79 |
+
if args.model == "flux":
|
80 |
+
# currently only support 512x512 generation
|
81 |
+
shape = (1, 16 * 64, 64)
|
82 |
+
elif args.model != "pixart":
|
83 |
+
height = pipe.unet.config.sample_size * pipe.vae_scale_factor
|
84 |
+
width = pipe.unet.config.sample_size * pipe.vae_scale_factor
|
85 |
shape = (
|
86 |
1,
|
87 |
+
pipe.unet.in_channels,
|
88 |
+
height // pipe.vae_scale_factor,
|
89 |
+
width // pipe.vae_scale_factor,
|
90 |
)
|
91 |
else:
|
92 |
+
height = pipe.transformer.config.sample_size * pipe.vae_scale_factor
|
93 |
+
width = pipe.transformer.config.sample_size * pipe.vae_scale_factor
|
94 |
shape = (
|
95 |
1,
|
96 |
+
pipe.transformer.config.in_channels,
|
97 |
+
height // pipe.vae_scale_factor,
|
98 |
+
width // pipe.vae_scale_factor,
|
99 |
)
|
100 |
enable_grad = not args.no_optim
|
101 |
+
|
102 |
+
if args.enable_multi_apply:
|
103 |
+
multi_apply_fn = get_multi_apply_fn(
|
104 |
+
model_type=args.multi_step_model,
|
105 |
+
seed=args.seed,
|
106 |
+
pipe=pipe,
|
107 |
+
cache_dir=args.cache_dir,
|
108 |
+
device=device,
|
109 |
+
dtype=dtype,
|
110 |
+
)
|
111 |
+
else:
|
112 |
+
multi_apply_fn = None
|
113 |
|
114 |
+
return args, trainer, device, dtype, shape, enable_grad, multi_apply_fn, settings
|
115 |
|
116 |
+
def execute_task(args, trainer, device, dtype, shape, enable_grad, multi_apply_fn, settings, progress_callback=None):
|
117 |
+
|
118 |
if args.task == "single":
|
119 |
init_latents = torch.randn(shape, device=device, dtype=dtype)
|
120 |
latents = torch.nn.Parameter(init_latents, requires_grad=enable_grad)
|
121 |
optimizer = get_optimizer(args.optim, latents, args.lr, args.nesterov)
|
122 |
+
save_dir = f"{args.save_dir}/{args.task}/{settings}/{args.prompt[:150]}"
|
123 |
os.makedirs(f"{save_dir}", exist_ok=True)
|
124 |
+
init_image, best_image, total_init_rewards, total_best_rewards = trainer.train(
|
125 |
+
latents, args.prompt, optimizer, save_dir, multi_apply_fn, progress_callback=progress_callback
|
126 |
)
|
127 |
best_image.save(f"{save_dir}/best_image.png")
|
128 |
+
#init_image.save(f"{save_dir}/init_image.png")
|
129 |
+
|
130 |
elif args.task == "example-prompts":
|
131 |
fo = open("assets/example_prompts.txt", "r")
|
132 |
prompts = fo.readlines()
|
|
|
138 |
optimizer = get_optimizer(args.optim, latents, args.lr, args.nesterov)
|
139 |
|
140 |
prompt = prompt.strip()
|
141 |
+
name = f"{i:03d}_{prompt[:150]}.png"
|
142 |
save_dir = f"{args.save_dir}/{args.task}/{settings}/{name}"
|
143 |
os.makedirs(save_dir, exist_ok=True)
|
144 |
+
init_image, best_image, init_rewards, best_rewards = trainer.train(
|
145 |
+
latents, prompt, optimizer, save_dir, multi_apply_fn
|
146 |
)
|
147 |
if i == 0:
|
148 |
total_best_rewards = {k: 0.0 for k in best_rewards.keys()}
|
|
|
151 |
total_best_rewards[k] += best_rewards[k]
|
152 |
total_init_rewards[k] += init_rewards[k]
|
153 |
best_image.save(f"{save_dir}/best_image.png")
|
154 |
+
init_image.save(f"{save_dir}/init_image.png")
|
155 |
logging.info(f"Initial rewards: {init_rewards}")
|
156 |
logging.info(f"Best rewards: {best_rewards}")
|
157 |
for k in total_best_rewards.keys():
|
|
|
177 |
optimizer = get_optimizer(args.optim, latents, args.lr, args.nesterov)
|
178 |
|
179 |
prompt = prompt.strip()
|
180 |
+
init_image, best_image, init_rewards, best_rewards = trainer.train(
|
181 |
+
latents, prompt, optimizer, None, multi_apply_fn
|
182 |
)
|
183 |
if i == 0:
|
184 |
total_best_rewards = {k: 0.0 for k in best_rewards.keys()}
|
|
|
204 |
f"{args.save_dir}/{args.task}/{settings}/{index}", exist_ok=True
|
205 |
)
|
206 |
prompt = sample["Prompt"]
|
207 |
+
init_image, best_image, init_rewards, best_rewards = trainer.train(
|
208 |
+
latents, prompt, optimizer, multi_apply_fn
|
209 |
)
|
210 |
best_image.save(
|
211 |
f"{args.save_dir}/{args.task}/{settings}/{index}/best_image.png"
|
|
|
270 |
optimizer = get_optimizer(args.optim, latents, args.lr, args.nesterov)
|
271 |
|
272 |
prompt = metadata["prompt"]
|
273 |
+
init_image, best_image, init_rewards, best_rewards = trainer.train(
|
274 |
+
latents, prompt, optimizer, None, multi_apply_fn
|
275 |
)
|
276 |
logging.info(f"Initial rewards: {init_rewards}")
|
277 |
logging.info(f"Best rewards: {best_rewards}")
|
|
|
297 |
|
298 |
def main():
|
299 |
args = parse_args()
|
300 |
+
args, trainer, device, dtype, shape, enable_grad, multi_apply_fn, settings = setup(args)
|
301 |
+
execute_task(args, trainer, device, dtype, shape, enable_grad, multi_apply_fn, settings)
|
|
|
302 |
|
303 |
if __name__ == "__main__":
|
304 |
main()
|
models/RewardFlux.py
ADDED
@@ -0,0 +1,436 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# Copyright 2024 Black Forest Labs and The HuggingFace Team. All rights reserved.
|
2 |
+
#
|
3 |
+
# Licensed under the Apache License, Version 2.0 (the "License");
|
4 |
+
# you may not use this file except in compliance with the License.
|
5 |
+
# You may obtain a copy of the License at
|
6 |
+
#
|
7 |
+
# http://www.apache.org/licenses/LICENSE-2.0
|
8 |
+
#
|
9 |
+
# Unless required by applicable law or agreed to in writing, software
|
10 |
+
# distributed under the License is distributed on an "AS IS" BASIS,
|
11 |
+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
12 |
+
# See the License for the specific language governing permissions and
|
13 |
+
# limitations under the License.
|
14 |
+
|
15 |
+
import inspect
|
16 |
+
from typing import Any, Callable, Dict, List, Optional, Union
|
17 |
+
|
18 |
+
import numpy as np
|
19 |
+
import torch
|
20 |
+
from transformers import CLIPTextModel, CLIPTokenizer, T5EncoderModel, T5TokenizerFast
|
21 |
+
from diffusers import (
|
22 |
+
FluxPipeline,
|
23 |
+
AutoencoderKL,
|
24 |
+
FluxTransformer2DModel,
|
25 |
+
FlowMatchEulerDiscreteScheduler,
|
26 |
+
)
|
27 |
+
|
28 |
+
EXAMPLE_DOC_STRING = """
|
29 |
+
Examples:
|
30 |
+
```py
|
31 |
+
>>> import torch
|
32 |
+
>>> from diffusers import FluxPipeline
|
33 |
+
|
34 |
+
>>> pipe = FluxPipeline.from_pretrained("black-forest-labs/FLUX.1-schnell", torch_dtype=torch.bfloat16)
|
35 |
+
>>> pipe.to("cuda")
|
36 |
+
>>> prompt = "A cat holding a sign that says hello world"
|
37 |
+
>>> # Depending on the variant being used, the pipeline call will slightly vary.
|
38 |
+
>>> # Refer to the pipeline documentation for more details.
|
39 |
+
>>> image = pipe(prompt, num_inference_steps=4, guidance_scale=0.0).images[0]
|
40 |
+
>>> image.save("flux.png")
|
41 |
+
```
|
42 |
+
"""
|
43 |
+
|
44 |
+
|
45 |
+
def freeze_params(params):
|
46 |
+
for param in params:
|
47 |
+
param.requires_grad = False
|
48 |
+
|
49 |
+
|
50 |
+
def calculate_shift(
|
51 |
+
image_seq_len,
|
52 |
+
base_seq_len: int = 256,
|
53 |
+
max_seq_len: int = 4096,
|
54 |
+
base_shift: float = 0.5,
|
55 |
+
max_shift: float = 1.16,
|
56 |
+
):
|
57 |
+
m = (max_shift - base_shift) / (max_seq_len - base_seq_len)
|
58 |
+
b = base_shift - m * base_seq_len
|
59 |
+
mu = image_seq_len * m + b
|
60 |
+
return mu
|
61 |
+
|
62 |
+
|
63 |
+
# Copied from diffusers.pipelines.stable_diffusion.pipeline_stable_diffusion.retrieve_timesteps
|
64 |
+
def retrieve_timesteps(
|
65 |
+
scheduler,
|
66 |
+
num_inference_steps: Optional[int] = None,
|
67 |
+
device: Optional[Union[str, torch.device]] = None,
|
68 |
+
timesteps: Optional[List[int]] = None,
|
69 |
+
sigmas: Optional[List[float]] = None,
|
70 |
+
**kwargs,
|
71 |
+
):
|
72 |
+
"""
|
73 |
+
Calls the scheduler's `set_timesteps` method and retrieves timesteps from the scheduler after the call. Handles
|
74 |
+
custom timesteps. Any kwargs will be supplied to `scheduler.set_timesteps`.
|
75 |
+
|
76 |
+
Args:
|
77 |
+
scheduler (`SchedulerMixin`):
|
78 |
+
The scheduler to get timesteps from.
|
79 |
+
num_inference_steps (`int`):
|
80 |
+
The number of diffusion steps used when generating samples with a pre-trained model. If used, `timesteps`
|
81 |
+
must be `None`.
|
82 |
+
device (`str` or `torch.device`, *optional*):
|
83 |
+
The device to which the timesteps should be moved to. If `None`, the timesteps are not moved.
|
84 |
+
timesteps (`List[int]`, *optional*):
|
85 |
+
Custom timesteps used to override the timestep spacing strategy of the scheduler. If `timesteps` is passed,
|
86 |
+
`num_inference_steps` and `sigmas` must be `None`.
|
87 |
+
sigmas (`List[float]`, *optional*):
|
88 |
+
Custom sigmas used to override the timestep spacing strategy of the scheduler. If `sigmas` is passed,
|
89 |
+
`num_inference_steps` and `timesteps` must be `None`.
|
90 |
+
|
91 |
+
Returns:
|
92 |
+
`Tuple[torch.Tensor, int]`: A tuple where the first element is the timestep schedule from the scheduler and the
|
93 |
+
second element is the number of inference steps.
|
94 |
+
"""
|
95 |
+
if timesteps is not None and sigmas is not None:
|
96 |
+
raise ValueError(
|
97 |
+
"Only one of `timesteps` or `sigmas` can be passed. Please choose one to set custom values"
|
98 |
+
)
|
99 |
+
if timesteps is not None:
|
100 |
+
accepts_timesteps = "timesteps" in set(
|
101 |
+
inspect.signature(scheduler.set_timesteps).parameters.keys()
|
102 |
+
)
|
103 |
+
if not accepts_timesteps:
|
104 |
+
raise ValueError(
|
105 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
106 |
+
f" timestep schedules. Please check whether you are using the correct scheduler."
|
107 |
+
)
|
108 |
+
scheduler.set_timesteps(timesteps=timesteps, device=device, **kwargs)
|
109 |
+
timesteps = scheduler.timesteps
|
110 |
+
num_inference_steps = len(timesteps)
|
111 |
+
elif sigmas is not None:
|
112 |
+
accept_sigmas = "sigmas" in set(
|
113 |
+
inspect.signature(scheduler.set_timesteps).parameters.keys()
|
114 |
+
)
|
115 |
+
if not accept_sigmas:
|
116 |
+
raise ValueError(
|
117 |
+
f"The current scheduler class {scheduler.__class__}'s `set_timesteps` does not support custom"
|
118 |
+
f" sigmas schedules. Please check whether you are using the correct scheduler."
|
119 |
+
)
|
120 |
+
scheduler.set_timesteps(sigmas=sigmas, device=device, **kwargs)
|
121 |
+
timesteps = scheduler.timesteps
|
122 |
+
num_inference_steps = len(timesteps)
|
123 |
+
else:
|
124 |
+
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
125 |
+
timesteps = scheduler.timesteps
|
126 |
+
return timesteps, num_inference_steps
|
127 |
+
|
128 |
+
|
129 |
+
class RewardFluxPipeline(FluxPipeline):
|
130 |
+
r"""
|
131 |
+
The Flux pipeline for text-to-image generation.
|
132 |
+
|
133 |
+
Reference: https://blackforestlabs.ai/announcing-black-forest-labs/
|
134 |
+
|
135 |
+
Args:
|
136 |
+
transformer ([`FluxTransformer2DModel`]):
|
137 |
+
Conditional Transformer (MMDiT) architecture to denoise the encoded image latents.
|
138 |
+
scheduler ([`FlowMatchEulerDiscreteScheduler`]):
|
139 |
+
A scheduler to be used in combination with `transformer` to denoise the encoded image latents.
|
140 |
+
vae ([`AutoencoderKL`]):
|
141 |
+
Variational Auto-Encoder (VAE) Model to encode and decode images to and from latent representations.
|
142 |
+
text_encoder ([`CLIPTextModel`]):
|
143 |
+
[CLIP](https://huggingface.co/docs/transformers/model_doc/clip#transformers.CLIPTextModel), specifically
|
144 |
+
the [clip-vit-large-patch14](https://huggingface.co/openai/clip-vit-large-patch14) variant.
|
145 |
+
text_encoder_2 ([`T5EncoderModel`]):
|
146 |
+
[T5](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5EncoderModel), specifically
|
147 |
+
the [google/t5-v1_1-xxl](https://huggingface.co/google/t5-v1_1-xxl) variant.
|
148 |
+
tokenizer (`CLIPTokenizer`):
|
149 |
+
Tokenizer of class
|
150 |
+
[CLIPTokenizer](https://huggingface.co/docs/transformers/en/model_doc/clip#transformers.CLIPTokenizer).
|
151 |
+
tokenizer_2 (`T5TokenizerFast`):
|
152 |
+
Second Tokenizer of class
|
153 |
+
[T5TokenizerFast](https://huggingface.co/docs/transformers/en/model_doc/t5#transformers.T5TokenizerFast).
|
154 |
+
"""
|
155 |
+
|
156 |
+
model_cpu_offload_seq = "text_encoder->text_encoder_2->transformer->vae"
|
157 |
+
_optional_components = []
|
158 |
+
_callback_tensor_inputs = ["latents", "prompt_embeds"]
|
159 |
+
|
160 |
+
def __init__(
|
161 |
+
self,
|
162 |
+
scheduler: FlowMatchEulerDiscreteScheduler,
|
163 |
+
vae: AutoencoderKL,
|
164 |
+
text_encoder: CLIPTextModel,
|
165 |
+
tokenizer: CLIPTokenizer,
|
166 |
+
text_encoder_2: T5EncoderModel,
|
167 |
+
tokenizer_2: T5TokenizerFast,
|
168 |
+
transformer: FluxTransformer2DModel,
|
169 |
+
memsave: bool = False,
|
170 |
+
):
|
171 |
+
# optionally enable memsave_torch
|
172 |
+
if memsave:
|
173 |
+
import memsave_torch.nn
|
174 |
+
|
175 |
+
vae = memsave_torch.nn.convert_to_memory_saving(vae)
|
176 |
+
transformer = memsave_torch.nn.convert_to_memory_saving(transformer)
|
177 |
+
text_encoder = memsave_torch.nn.convert_to_memory_saving(text_encoder)
|
178 |
+
text_encoder_2 = memsave_torch.nn.convert_to_memory_saving(text_encoder_2)
|
179 |
+
# enable checkpointing
|
180 |
+
text_encoder.gradient_checkpointing_enable()
|
181 |
+
text_encoder_2.gradient_checkpointing_enable()
|
182 |
+
transformer.enable_gradient_checkpointing()
|
183 |
+
vae.eval()
|
184 |
+
text_encoder.eval()
|
185 |
+
text_encoder_2.eval()
|
186 |
+
transformer.eval()
|
187 |
+
|
188 |
+
# freeze diffusion parameters
|
189 |
+
freeze_params(vae.parameters())
|
190 |
+
freeze_params(transformer.parameters())
|
191 |
+
freeze_params(text_encoder.parameters())
|
192 |
+
freeze_params(text_encoder_2.parameters())
|
193 |
+
super().__init__(
|
194 |
+
scheduler,
|
195 |
+
vae,
|
196 |
+
text_encoder,
|
197 |
+
tokenizer,
|
198 |
+
text_encoder_2,
|
199 |
+
tokenizer_2,
|
200 |
+
transformer,
|
201 |
+
)
|
202 |
+
|
203 |
+
def apply(
|
204 |
+
self,
|
205 |
+
prompt: Union[str, List[str]] = None,
|
206 |
+
prompt_2: Optional[Union[str, List[str]]] = None,
|
207 |
+
height: Optional[int] = 512,
|
208 |
+
width: Optional[int] = 512,
|
209 |
+
num_inference_steps: int = 1,
|
210 |
+
timesteps: List[int] = None,
|
211 |
+
guidance_scale: float = 0.0,
|
212 |
+
num_images_per_prompt: Optional[int] = 1,
|
213 |
+
generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
|
214 |
+
latents: Optional[torch.FloatTensor] = None,
|
215 |
+
prompt_embeds: Optional[torch.FloatTensor] = None,
|
216 |
+
pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
|
217 |
+
output_type: Optional[str] = "pil",
|
218 |
+
return_dict: bool = True,
|
219 |
+
joint_attention_kwargs: Optional[Dict[str, Any]] = None,
|
220 |
+
callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
|
221 |
+
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
|
222 |
+
max_sequence_length: int = 256,
|
223 |
+
):
|
224 |
+
r"""
|
225 |
+
Function invoked when calling the pipeline for generation.
|
226 |
+
|
227 |
+
Args:
|
228 |
+
prompt (`str` or `List[str]`, *optional*):
|
229 |
+
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
|
230 |
+
instead.
|
231 |
+
prompt_2 (`str` or `List[str]`, *optional*):
|
232 |
+
The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
|
233 |
+
will be used instead
|
234 |
+
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
235 |
+
The height in pixels of the generated image. This is set to 1024 by default for the best results.
|
236 |
+
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
|
237 |
+
The width in pixels of the generated image. This is set to 1024 by default for the best results.
|
238 |
+
num_inference_steps (`int`, *optional*, defaults to 50):
|
239 |
+
The number of denoising steps. More denoising steps usually lead to a higher quality image at the
|
240 |
+
expense of slower inference.
|
241 |
+
timesteps (`List[int]`, *optional*):
|
242 |
+
Custom timesteps to use for the denoising process with schedulers which support a `timesteps` argument
|
243 |
+
in their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is
|
244 |
+
passed will be used. Must be in descending order.
|
245 |
+
guidance_scale (`float`, *optional*, defaults to 7.0):
|
246 |
+
Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
|
247 |
+
`guidance_scale` is defined as `w` of equation 2. of [Imagen
|
248 |
+
Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
|
249 |
+
1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
|
250 |
+
usually at the expense of lower image quality.
|
251 |
+
num_images_per_prompt (`int`, *optional*, defaults to 1):
|
252 |
+
The number of images to generate per prompt.
|
253 |
+
generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
|
254 |
+
One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
|
255 |
+
to make generation deterministic.
|
256 |
+
latents (`torch.FloatTensor`, *optional*):
|
257 |
+
Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
|
258 |
+
generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
|
259 |
+
tensor will ge generated by sampling using the supplied random `generator`.
|
260 |
+
prompt_embeds (`torch.FloatTensor`, *optional*):
|
261 |
+
Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
|
262 |
+
provided, text embeddings will be generated from `prompt` input argument.
|
263 |
+
pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
|
264 |
+
Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
|
265 |
+
If not provided, pooled text embeddings will be generated from `prompt` input argument.
|
266 |
+
output_type (`str`, *optional*, defaults to `"pil"`):
|
267 |
+
The output format of the generate image. Choose between
|
268 |
+
[PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
|
269 |
+
return_dict (`bool`, *optional*, defaults to `True`):
|
270 |
+
Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
|
271 |
+
joint_attention_kwargs (`dict`, *optional*):
|
272 |
+
A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
|
273 |
+
`self.processor` in
|
274 |
+
[diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
|
275 |
+
callback_on_step_end (`Callable`, *optional*):
|
276 |
+
A function that calls at the end of each denoising steps during the inference. The function is called
|
277 |
+
with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
|
278 |
+
callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
|
279 |
+
`callback_on_step_end_tensor_inputs`.
|
280 |
+
callback_on_step_end_tensor_inputs (`List`, *optional*):
|
281 |
+
The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
|
282 |
+
will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
|
283 |
+
`._callback_tensor_inputs` attribute of your pipeline class.
|
284 |
+
max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
|
285 |
+
|
286 |
+
Examples:
|
287 |
+
|
288 |
+
Returns:
|
289 |
+
[`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
|
290 |
+
is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
|
291 |
+
images.
|
292 |
+
"""
|
293 |
+
|
294 |
+
height = height or self.default_sample_size * self.vae_scale_factor
|
295 |
+
width = width or self.default_sample_size * self.vae_scale_factor
|
296 |
+
|
297 |
+
# 1. Check inputs. Raise error if not correct
|
298 |
+
self.check_inputs(
|
299 |
+
prompt,
|
300 |
+
prompt_2,
|
301 |
+
height,
|
302 |
+
width,
|
303 |
+
prompt_embeds=prompt_embeds,
|
304 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
305 |
+
callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
|
306 |
+
max_sequence_length=max_sequence_length,
|
307 |
+
)
|
308 |
+
|
309 |
+
self._guidance_scale = guidance_scale
|
310 |
+
self._joint_attention_kwargs = joint_attention_kwargs
|
311 |
+
self._interrupt = False
|
312 |
+
|
313 |
+
# 2. Define call parameters
|
314 |
+
if prompt is not None and isinstance(prompt, str):
|
315 |
+
batch_size = 1
|
316 |
+
elif prompt is not None and isinstance(prompt, list):
|
317 |
+
batch_size = len(prompt)
|
318 |
+
else:
|
319 |
+
batch_size = prompt_embeds.shape[0]
|
320 |
+
|
321 |
+
device = self._execution_device
|
322 |
+
|
323 |
+
lora_scale = (
|
324 |
+
self.joint_attention_kwargs.get("scale", None)
|
325 |
+
if self.joint_attention_kwargs is not None
|
326 |
+
else None
|
327 |
+
)
|
328 |
+
(
|
329 |
+
prompt_embeds,
|
330 |
+
pooled_prompt_embeds,
|
331 |
+
text_ids,
|
332 |
+
) = self.encode_prompt(
|
333 |
+
prompt=prompt,
|
334 |
+
prompt_2=prompt_2,
|
335 |
+
prompt_embeds=prompt_embeds,
|
336 |
+
pooled_prompt_embeds=pooled_prompt_embeds,
|
337 |
+
device=device,
|
338 |
+
num_images_per_prompt=num_images_per_prompt,
|
339 |
+
max_sequence_length=max_sequence_length,
|
340 |
+
lora_scale=lora_scale,
|
341 |
+
)
|
342 |
+
|
343 |
+
# 4. Prepare latent variables
|
344 |
+
num_channels_latents = self.transformer.config.in_channels // 4
|
345 |
+
latents, latent_image_ids = self.prepare_latents(
|
346 |
+
batch_size * num_images_per_prompt,
|
347 |
+
num_channels_latents,
|
348 |
+
height,
|
349 |
+
width,
|
350 |
+
prompt_embeds.dtype,
|
351 |
+
device,
|
352 |
+
generator,
|
353 |
+
latents,
|
354 |
+
)
|
355 |
+
|
356 |
+
# 5. Prepare timesteps
|
357 |
+
sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps)
|
358 |
+
image_seq_len = latents.shape[1]
|
359 |
+
mu = calculate_shift(
|
360 |
+
image_seq_len,
|
361 |
+
self.scheduler.config.base_image_seq_len,
|
362 |
+
self.scheduler.config.max_image_seq_len,
|
363 |
+
self.scheduler.config.base_shift,
|
364 |
+
self.scheduler.config.max_shift,
|
365 |
+
)
|
366 |
+
timesteps, num_inference_steps = retrieve_timesteps(
|
367 |
+
self.scheduler,
|
368 |
+
num_inference_steps,
|
369 |
+
device,
|
370 |
+
timesteps,
|
371 |
+
sigmas,
|
372 |
+
mu=mu,
|
373 |
+
)
|
374 |
+
self._num_timesteps = len(timesteps)
|
375 |
+
|
376 |
+
# 6. Denoising loop:
|
377 |
+
for i, t in enumerate(timesteps):
|
378 |
+
if self.interrupt:
|
379 |
+
continue
|
380 |
+
|
381 |
+
# broadcast to batch dimension in a way that's compatible with ONNX/Core ML
|
382 |
+
timestep = t.expand(latents.shape[0]).to(latents.dtype)
|
383 |
+
|
384 |
+
# handle guidance
|
385 |
+
if self.transformer.config.guidance_embeds:
|
386 |
+
guidance = torch.tensor([guidance_scale], device=device)
|
387 |
+
guidance = guidance.expand(latents.shape[0])
|
388 |
+
else:
|
389 |
+
guidance = None
|
390 |
+
|
391 |
+
noise_pred = self.transformer(
|
392 |
+
hidden_states=latents,
|
393 |
+
# YiYi notes: divide it by 1000 for now because we scale it by 1000 in the transforme rmodel (we should not keep it but I want to keep the inputs same for the model for testing)
|
394 |
+
timestep=timestep / 1000,
|
395 |
+
guidance=guidance,
|
396 |
+
pooled_projections=pooled_prompt_embeds,
|
397 |
+
encoder_hidden_states=prompt_embeds,
|
398 |
+
txt_ids=text_ids,
|
399 |
+
img_ids=latent_image_ids,
|
400 |
+
joint_attention_kwargs=self.joint_attention_kwargs,
|
401 |
+
return_dict=False,
|
402 |
+
)[0]
|
403 |
+
|
404 |
+
# compute the previous noisy sample x_t -> x_t-1
|
405 |
+
latents_dtype = latents.dtype
|
406 |
+
latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
|
407 |
+
|
408 |
+
if latents.dtype != latents_dtype:
|
409 |
+
if torch.backends.mps.is_available():
|
410 |
+
# some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
|
411 |
+
latents = latents.to(latents_dtype)
|
412 |
+
|
413 |
+
if callback_on_step_end is not None:
|
414 |
+
callback_kwargs = {}
|
415 |
+
for k in callback_on_step_end_tensor_inputs:
|
416 |
+
callback_kwargs[k] = locals()[k]
|
417 |
+
callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
|
418 |
+
|
419 |
+
latents = callback_outputs.pop("latents", latents)
|
420 |
+
prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
|
421 |
+
|
422 |
+
if output_type == "latent":
|
423 |
+
image = latents
|
424 |
+
|
425 |
+
else:
|
426 |
+
latents = self._unpack_latents(
|
427 |
+
latents, height, width, self.vae_scale_factor
|
428 |
+
)
|
429 |
+
latents = (
|
430 |
+
latents / self.vae.config.scaling_factor
|
431 |
+
) + self.vae.config.shift_factor
|
432 |
+
image = self.vae.decode(latents, return_dict=False)[0]
|
433 |
+
image = (image / 2 + 0.5).clamp(0, 1)
|
434 |
+
# image = self.image_processor.postprocess(image, output_type=output_type)
|
435 |
+
|
436 |
+
return image
|
models/RewardPixart.py
CHANGED
@@ -2,8 +2,7 @@ from typing import List, Optional, Union
|
|
2 |
|
3 |
import torch
|
4 |
from diffusers import PixArtAlphaPipeline
|
5 |
-
from diffusers.pipelines.pixart_alpha.pipeline_pixart_alpha import
|
6 |
-
retrieve_timesteps
|
7 |
|
8 |
|
9 |
def freeze_params(params):
|
@@ -391,4 +390,4 @@ ASPECT_RATIO_512_BIN = {
|
|
391 |
"2.5": [800.0, 320.0],
|
392 |
"3.0": [864.0, 288.0],
|
393 |
"4.0": [1024.0, 256.0],
|
394 |
-
}
|
|
|
2 |
|
3 |
import torch
|
4 |
from diffusers import PixArtAlphaPipeline
|
5 |
+
from diffusers.pipelines.pixart_alpha.pipeline_pixart_alpha import retrieve_timesteps
|
|
|
6 |
|
7 |
|
8 |
def freeze_params(params):
|
|
|
390 |
"2.5": [800.0, 320.0],
|
391 |
"3.0": [864.0, 288.0],
|
392 |
"4.0": [1024.0, 256.0],
|
393 |
+
}
|
models/RewardStableDiffusion.py
CHANGED
@@ -274,4 +274,4 @@ def retrieve_timesteps(
|
|
274 |
else:
|
275 |
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
276 |
timesteps = scheduler.timesteps
|
277 |
-
return timesteps, num_inference_steps
|
|
|
274 |
else:
|
275 |
scheduler.set_timesteps(num_inference_steps, device=device, **kwargs)
|
276 |
timesteps = scheduler.timesteps
|
277 |
+
return timesteps, num_inference_steps
|
models/RewardStableDiffusionXL.py
CHANGED
@@ -1,14 +1,18 @@
|
|
1 |
from typing import List, Optional, Union
|
2 |
|
3 |
import torch
|
4 |
-
from diffusers import
|
5 |
-
|
6 |
-
|
7 |
-
|
8 |
from diffusers.schedulers import KarrasDiffusionSchedulers
|
9 |
-
from transformers import (
|
10 |
-
|
11 |
-
|
|
|
|
|
|
|
|
|
12 |
|
13 |
|
14 |
def freeze_params(params):
|
@@ -317,4 +321,4 @@ class RewardStableDiffusionXL(StableDiffusionXLPipeline):
|
|
317 |
# Offload all models
|
318 |
self.maybe_free_model_hooks()
|
319 |
|
320 |
-
return image
|
|
|
1 |
from typing import List, Optional, Union
|
2 |
|
3 |
import torch
|
4 |
+
from diffusers import AutoencoderKL, StableDiffusionXLPipeline, UNet2DConditionModel
|
5 |
+
from diffusers.pipelines.stable_diffusion_xl.pipeline_stable_diffusion_xl import (
|
6 |
+
retrieve_timesteps,
|
7 |
+
)
|
8 |
from diffusers.schedulers import KarrasDiffusionSchedulers
|
9 |
+
from transformers import (
|
10 |
+
CLIPImageProcessor,
|
11 |
+
CLIPTextModel,
|
12 |
+
CLIPTextModelWithProjection,
|
13 |
+
CLIPTokenizer,
|
14 |
+
CLIPVisionModelWithProjection,
|
15 |
+
)
|
16 |
|
17 |
|
18 |
def freeze_params(params):
|
|
|
321 |
# Offload all models
|
322 |
self.maybe_free_model_hooks()
|
323 |
|
324 |
+
return image
|
models/__init__.py
CHANGED
@@ -1 +1 @@
|
|
1 |
-
from .utils import get_model
|
|
|
1 |
+
from .utils import get_model, get_multi_apply_fn
|
models/__pycache__/RewardPixart.cpython-310.pyc
ADDED
Binary file (7.57 kB). View file
|
|
models/__pycache__/RewardStableDiffusion.cpython-310.pyc
ADDED
Binary file (6.21 kB). View file
|
|
models/__pycache__/RewardStableDiffusionXL.cpython-310.pyc
ADDED
Binary file (6.2 kB). View file
|
|
models/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (165 Bytes). View file
|
|
models/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (2.47 kB). View file
|
|
models/utils.py
CHANGED
@@ -1,15 +1,22 @@
|
|
1 |
import logging
|
2 |
-
|
3 |
import torch
|
4 |
-
from diffusers import (
|
5 |
-
|
6 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
7 |
from huggingface_hub import hf_hub_download
|
8 |
from safetensors.torch import load_file
|
9 |
|
10 |
from models.RewardPixart import RewardPixartPipeline, freeze_params
|
11 |
from models.RewardStableDiffusion import RewardStableDiffusion
|
12 |
from models.RewardStableDiffusionXL import RewardStableDiffusionXL
|
|
|
13 |
|
14 |
|
15 |
def get_model(
|
@@ -18,6 +25,7 @@ def get_model(
|
|
18 |
device: torch.device,
|
19 |
cache_dir: str,
|
20 |
memsave: bool = False,
|
|
|
21 |
):
|
22 |
logging.info(f"Loading model: {model_name}")
|
23 |
if model_name == "sd-turbo":
|
@@ -103,7 +111,80 @@ def get_model(
|
|
103 |
pipe = pipe.to(device, dtype)
|
104 |
# upcast vae
|
105 |
pipe.vae = pipe.vae.to(dtype=torch.float32)
|
106 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
107 |
else:
|
108 |
raise ValueError(f"Unknown model name: {model_name}")
|
|
|
|
|
109 |
return pipe
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
import logging
|
2 |
+
from typing import Any, Optional
|
3 |
import torch
|
4 |
+
from diffusers import (
|
5 |
+
AutoencoderKL,
|
6 |
+
DDPMScheduler,
|
7 |
+
EulerDiscreteScheduler,
|
8 |
+
EulerAncestralDiscreteScheduler,
|
9 |
+
LCMScheduler,
|
10 |
+
Transformer2DModel,
|
11 |
+
UNet2DConditionModel,
|
12 |
+
)
|
13 |
from huggingface_hub import hf_hub_download
|
14 |
from safetensors.torch import load_file
|
15 |
|
16 |
from models.RewardPixart import RewardPixartPipeline, freeze_params
|
17 |
from models.RewardStableDiffusion import RewardStableDiffusion
|
18 |
from models.RewardStableDiffusionXL import RewardStableDiffusionXL
|
19 |
+
from models.RewardFlux import RewardFluxPipeline
|
20 |
|
21 |
|
22 |
def get_model(
|
|
|
25 |
device: torch.device,
|
26 |
cache_dir: str,
|
27 |
memsave: bool = False,
|
28 |
+
enable_sequential_cpu_offload: bool = False,
|
29 |
):
|
30 |
logging.info(f"Loading model: {model_name}")
|
31 |
if model_name == "sd-turbo":
|
|
|
111 |
pipe = pipe.to(device, dtype)
|
112 |
# upcast vae
|
113 |
pipe.vae = pipe.vae.to(dtype=torch.float32)
|
114 |
+
elif model_name == "flux":
|
115 |
+
pipe = RewardFluxPipeline.from_pretrained(
|
116 |
+
"black-forest-labs/FLUX.1-schnell",
|
117 |
+
torch_dtype=torch.bfloat16,
|
118 |
+
cache_dir=cache_dir,
|
119 |
+
)
|
120 |
+
pipe.to(device, dtype)
|
121 |
else:
|
122 |
raise ValueError(f"Unknown model name: {model_name}")
|
123 |
+
if enable_sequential_cpu_offload:
|
124 |
+
pipe.enable_sequential_cpu_offload()
|
125 |
return pipe
|
126 |
+
|
127 |
+
|
128 |
+
def get_multi_apply_fn(
|
129 |
+
model_type: str,
|
130 |
+
seed: int,
|
131 |
+
pipe: Optional[Any] = None,
|
132 |
+
cache_dir: Optional[str] = None,
|
133 |
+
device: Optional[torch.device] = None,
|
134 |
+
dtype: Optional[torch.dtype] = None,
|
135 |
+
):
|
136 |
+
generator = torch.Generator("cuda").manual_seed(seed)
|
137 |
+
if model_type == "flux":
|
138 |
+
return lambda latents, prompt: torch.no_grad(pipe.apply)(
|
139 |
+
latents=latents,
|
140 |
+
prompt=prompt,
|
141 |
+
num_inference_steps=4,
|
142 |
+
generator=generator,
|
143 |
+
)
|
144 |
+
elif model_type == "sdxl":
|
145 |
+
vae = AutoencoderKL.from_pretrained(
|
146 |
+
"madebyollin/sdxl-vae-fp16-fix",
|
147 |
+
torch_dtype=torch.float16,
|
148 |
+
cache_dir=cache_dir,
|
149 |
+
)
|
150 |
+
pipe = RewardStableDiffusionXL.from_pretrained(
|
151 |
+
"stabilityai/stable-diffusion-xl-base-1.0",
|
152 |
+
torch_dtype=torch.float16,
|
153 |
+
variant="fp16",
|
154 |
+
vae=vae,
|
155 |
+
use_safetensors=True,
|
156 |
+
cache_dir=cache_dir,
|
157 |
+
)
|
158 |
+
pipe = pipe.to(device, dtype)
|
159 |
+
pipe.enable_sequential_cpu_offload()
|
160 |
+
return lambda latents, prompt: torch.no_grad(pipe.apply)(
|
161 |
+
latents=latents,
|
162 |
+
prompt=prompt,
|
163 |
+
guidance_scale=5.0,
|
164 |
+
num_inference_steps=50,
|
165 |
+
generator=generator,
|
166 |
+
)
|
167 |
+
elif model_type == "sd2":
|
168 |
+
sd2_base = "stabilityai/stable-diffusion-2-1-base"
|
169 |
+
scheduler = EulerDiscreteScheduler.from_pretrained(
|
170 |
+
sd2_base,
|
171 |
+
subfolder="scheduler",
|
172 |
+
cache_dir=cache_dir,
|
173 |
+
)
|
174 |
+
pipe = RewardStableDiffusion.from_pretrained(
|
175 |
+
sd2_base,
|
176 |
+
torch_dtype=dtype,
|
177 |
+
cache_dir=cache_dir,
|
178 |
+
scheduler=scheduler,
|
179 |
+
)
|
180 |
+
pipe = pipe.to(device, dtype)
|
181 |
+
pipe.enable_sequential_cpu_offload()
|
182 |
+
return lambda latents, prompt: torch.no_grad(pipe.apply)(
|
183 |
+
latents=latents,
|
184 |
+
prompt=prompt,
|
185 |
+
guidance_scale=7.5,
|
186 |
+
num_inference_steps=50,
|
187 |
+
generator=generator,
|
188 |
+
)
|
189 |
+
else:
|
190 |
+
raise ValueError(f"Unknown model type: {model_type}")
|
requirements.txt
CHANGED
@@ -3,7 +3,7 @@ torchvision==0.18.0
|
|
3 |
pytorch-lightning==2.2
|
4 |
datasets==2.18
|
5 |
transformers==4.38.2
|
6 |
-
diffusers
|
7 |
hpsv2==1.2
|
8 |
hpsv2x==1.2.0
|
9 |
image-reward==1.5
|
|
|
3 |
pytorch-lightning==2.2
|
4 |
datasets==2.18
|
5 |
transformers==4.38.2
|
6 |
+
diffusers
|
7 |
hpsv2==1.2
|
8 |
hpsv2x==1.2.0
|
9 |
image-reward==1.5
|
rewards/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (203 Bytes). View file
|
|
rewards/__pycache__/aesthetic.cpython-310.pyc
ADDED
Binary file (3.9 kB). View file
|
|
rewards/__pycache__/base_reward.cpython-310.pyc
ADDED
Binary file (2.04 kB). View file
|
|
rewards/__pycache__/clip.cpython-310.pyc
ADDED
Binary file (2.02 kB). View file
|
|
rewards/__pycache__/hps.cpython-310.pyc
ADDED
Binary file (2.19 kB). View file
|
|
rewards/__pycache__/imagereward.cpython-310.pyc
ADDED
Binary file (1.96 kB). View file
|
|
rewards/__pycache__/pickscore.cpython-310.pyc
ADDED
Binary file (2.05 kB). View file
|
|
rewards/__pycache__/utils.cpython-310.pyc
ADDED
Binary file (1.84 kB). View file
|
|
training/__pycache__/__init__.cpython-310.pyc
ADDED
Binary file (221 Bytes). View file
|
|
training/__pycache__/optim.cpython-310.pyc
ADDED
Binary file (721 Bytes). View file
|
|
training/__pycache__/trainer.cpython-310.pyc
ADDED
Binary file (3.45 kB). View file
|
|
training/trainer.py
CHANGED
@@ -51,13 +51,16 @@ class LatentNoiseTrainer:
|
|
51 |
prompt: str,
|
52 |
optimizer: torch.optim.Optimizer,
|
53 |
save_dir: Optional[str] = None,
|
|
|
54 |
progress_callback=None,
|
55 |
) -> Tuple[PIL.Image.Image, Dict[str, float], Dict[str, float]]:
|
56 |
logging.info(f"Optimizing latents for prompt '{prompt}'.")
|
57 |
best_loss = torch.inf
|
58 |
best_image = None
|
|
|
59 |
initial_rewards = None
|
60 |
best_rewards = None
|
|
|
61 |
latent_dim = math.prod(latents.shape[1:])
|
62 |
for iteration in range(self.n_iters):
|
63 |
to_log = ""
|
@@ -76,11 +79,17 @@ class LatentNoiseTrainer:
|
|
76 |
)
|
77 |
else:
|
78 |
image = self.model.apply(
|
79 |
-
latents,
|
80 |
-
prompt,
|
81 |
generator=generator,
|
82 |
num_inference_steps=self.n_inference_steps,
|
83 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
84 |
if self.no_optim:
|
85 |
best_image = image
|
86 |
break
|
@@ -107,12 +116,11 @@ class LatentNoiseTrainer:
|
|
107 |
total_loss += regularization.to(total_loss.dtype)
|
108 |
if self.log_metrics:
|
109 |
logging.info(f"Iteration {iteration}: {to_log}")
|
110 |
-
if initial_rewards is None:
|
111 |
-
initial_rewards = rewards
|
112 |
if total_reward_loss < best_loss:
|
113 |
best_loss = total_reward_loss
|
114 |
best_image = image
|
115 |
best_rewards = rewards
|
|
|
116 |
if iteration != self.n_iters - 1 and not self.imageselect:
|
117 |
total_loss.backward()
|
118 |
torch.nn.utils.clip_grad_norm_(latents, self.grad_clip)
|
@@ -121,8 +129,16 @@ class LatentNoiseTrainer:
|
|
121 |
image_numpy = image.detach().cpu().permute(0, 2, 3, 1).float().numpy()
|
122 |
image_pil = DiffusionPipeline.numpy_to_pil(image_numpy)[0]
|
123 |
image_pil.save(f"{save_dir}/{iteration}.png")
|
|
|
|
|
124 |
if progress_callback:
|
125 |
progress_callback(iteration + 1)
|
126 |
image_numpy = best_image.detach().cpu().permute(0, 2, 3, 1).float().numpy()
|
127 |
-
|
128 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
51 |
prompt: str,
|
52 |
optimizer: torch.optim.Optimizer,
|
53 |
save_dir: Optional[str] = None,
|
54 |
+
multi_apply_fn=None,
|
55 |
progress_callback=None,
|
56 |
) -> Tuple[PIL.Image.Image, Dict[str, float], Dict[str, float]]:
|
57 |
logging.info(f"Optimizing latents for prompt '{prompt}'.")
|
58 |
best_loss = torch.inf
|
59 |
best_image = None
|
60 |
+
initial_image = None
|
61 |
initial_rewards = None
|
62 |
best_rewards = None
|
63 |
+
best_latents = None
|
64 |
latent_dim = math.prod(latents.shape[1:])
|
65 |
for iteration in range(self.n_iters):
|
66 |
to_log = ""
|
|
|
79 |
)
|
80 |
else:
|
81 |
image = self.model.apply(
|
82 |
+
latents=latents,
|
83 |
+
prompt=prompt,
|
84 |
generator=generator,
|
85 |
num_inference_steps=self.n_inference_steps,
|
86 |
)
|
87 |
+
if initial_image is None and multi_apply_fn is not None:
|
88 |
+
multi_step_image = multi_apply_fn(latents.detach(), prompt)
|
89 |
+
image_numpy = (
|
90 |
+
multi_step_image.detach().cpu().permute(0, 2, 3, 1).float().numpy()
|
91 |
+
)
|
92 |
+
initial_image = DiffusionPipeline.numpy_to_pil(image_numpy)[0]
|
93 |
if self.no_optim:
|
94 |
best_image = image
|
95 |
break
|
|
|
116 |
total_loss += regularization.to(total_loss.dtype)
|
117 |
if self.log_metrics:
|
118 |
logging.info(f"Iteration {iteration}: {to_log}")
|
|
|
|
|
119 |
if total_reward_loss < best_loss:
|
120 |
best_loss = total_reward_loss
|
121 |
best_image = image
|
122 |
best_rewards = rewards
|
123 |
+
best_latents = latents.detach().cpu()
|
124 |
if iteration != self.n_iters - 1 and not self.imageselect:
|
125 |
total_loss.backward()
|
126 |
torch.nn.utils.clip_grad_norm_(latents, self.grad_clip)
|
|
|
129 |
image_numpy = image.detach().cpu().permute(0, 2, 3, 1).float().numpy()
|
130 |
image_pil = DiffusionPipeline.numpy_to_pil(image_numpy)[0]
|
131 |
image_pil.save(f"{save_dir}/{iteration}.png")
|
132 |
+
if initial_rewards is None:
|
133 |
+
initial_rewards = rewards
|
134 |
if progress_callback:
|
135 |
progress_callback(iteration + 1)
|
136 |
image_numpy = best_image.detach().cpu().permute(0, 2, 3, 1).float().numpy()
|
137 |
+
best_image_pil = DiffusionPipeline.numpy_to_pil(image_numpy)[0]
|
138 |
+
if multi_apply_fn is not None:
|
139 |
+
multi_step_image = multi_apply_fn(best_latents.to("cuda"), prompt)
|
140 |
+
image_numpy = (
|
141 |
+
multi_step_image.detach().cpu().permute(0, 2, 3, 1).float().numpy()
|
142 |
+
)
|
143 |
+
best_image_pil = DiffusionPipeline.numpy_to_pil(image_numpy)[0]
|
144 |
+
return initial_image, best_image_pil, initial_rewards, best_rewards
|