File size: 34,556 Bytes
6d6dbbc | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 | # Reward-Guided Gradient Ascent for Stable Diffusion
A comprehensive system for improving Stable Diffusion image generation quality using gradient ascent optimization on Latent Reward Model (LRM) scores during inference.
## Table of Contents
- [Overview](#overview)
- [Features](#features)
- [Installation](#installation)
- [Quick Start](#quick-start)
- [Architecture](#architecture)
- [Understanding Reward Calculation](#understanding-reward-calculation)
- [Learning Rate Scheduling](#learning-rate-scheduling)
- [Configuration Presets](#configuration-presets)
- [Evaluation Metrics](#evaluation-metrics)
- [Model Variants](#model-variants)
- [Datasets](#datasets)
- [Usage Examples](#usage-examples)
- [API Reference](#api-reference)
- [Command-Line Options](#command-line-options)
- [Output Files](#output-files)
- [Troubleshooting](#troubleshooting)
- [Best Practices](#best-practices)
- [Changelog](#changelog)
---
## Overview
This project implements **test-time optimization** for Stable Diffusion using gradient ascent on the LRM reward model. Unlike the main LPO training which uses the reward model for training, this approach applies it during inference to improve generation quality without retraining.
### Key Capabilities
- **Gradient Ascent Optimization**: Iteratively improve latents using reward gradients
- **Learning Rate Scheduling**: Multiple strategies (constant, linear, cosine, exponential, step)
- **Momentum Optimization**: Standard and Nesterov momentum for better convergence
- **Multiple Metrics**: FID, CLIP, Aesthetic, PickScore, HPSv2, ImageReward
- **Model Variants**: Support for Origin, SPO, DPO, and LPO SD1.5 models
- **Dataset Flexibility**: COCO and Pick-a-Pic validation datasets
- **Configuration Presets**: 15 pre-tuned configurations for various use cases
---
## Features
### 1. **Advanced Optimization**
- **5 LR Schedulers**: Constant, Linear, Cosine, Exponential, Step-wise
- **Momentum Support**: Standard momentum and Nesterov momentum
- **Configurable Timestep Ranges**: Apply gradients at specific denoising steps
- **Dynamic Learning Rates**: LR changes during optimization for better convergence
### 2. **Comprehensive Evaluation**
- **6 Quality Metrics**: FID, CLIP, Aesthetic, PickScore, HPSv2, ImageReward
- **Baseline Comparison**: Compare with and without gradient ascent
- **Detailed Statistics**: Track reward improvements, gradient norms, LR history
- **Batch Processing**: Efficient evaluation on large datasets
- **Reward Visualization**: Automatic plotting of reward progression across timesteps
- **Timestep-Aware Tracking**: Monitor rewards at every denoising step, final t=0 latent reported
### 3. **Model Flexibility**
- **4 SD1.5 Variants**: Origin, SPO, DPO, LPO
- **Auto-Configuration**: CFG scale auto-adjusted for model variants
- **Easy Switching**: Change models with a single flag
### 4. **Dataset Support**
- **COCO Validation**: Standard benchmark with reference images
- **Pick-a-Pic Validation**: Large-scale human preference dataset
- **Streaming Support**: Handle large datasets efficiently
---
## Installation
### Requirements
```bash
# Core dependencies
pip install torch diffusers transformers torchmetrics datasets huggingface-hub
# For evaluation metrics
pip install pillow numpy scipy tqdm
# Optional: for better performance
pip install xformers # For memory-efficient attention
```
### Setup
```bash
cd /path/to/LPO/Reward
# Verify installation
python -c "from lr_scheduler import create_lr_scheduler; print('β LR Scheduler OK')"
python -c "from grad_ascent_configs import list_configs; print('β Configs:', len(list_configs()))"
python -c "from gradient_ascent_utils import RewardGuidedDiffusion; print('β Gradient Utils OK')"
```
---
## Quick Start
### 1. Basic COCO Evaluation (test_grad_sd1.5.py)
```bash
# Edit Config in test_grad_sd1.5.py:
# - Set device: "cuda:0" or "cuda:6"
# - Set max_samples: 10 for quick test, None for full dataset
# - Configure gradient ascent parameters
python test_grad_sd1.5.py
```
**Output:**
- Creates `RESULTS/SD1.5_GradAscent/run_1/` (auto-incremented)
- Generates `eval.log` with detailed metrics
- Saves `reward_curve.png` showing reward progression
### 2. Basic Evaluation with Preset Config (eval.py)
```bash
python eval.py \
--grad_config cosine_nesterov \
--metrics clip aesthetic \
--max_samples 10
```
### 2. High-Quality Evaluation
```bash
python eval.py \
--grad_config high_quality \
--metrics fid clip aesthetic pickscore hpsv2 \
--max_samples 100 \
--save_images \
--output_dir results/high_quality
```
### 3. Pick-a-Pic Benchmark
```bash
python eval.py \
--dataset_type pickapic \
--grad_config cosine_nesterov \
--metrics pickscore hpsv2 imagereward \
--max_samples 500 \
--output_dir results/pickapic
```
---
## Architecture
### System Components
```
Reward/
βββ models/
β βββ reward_model.py # LRM reward model wrapper
β βββ unet_2d_condition_reward.py # Custom UNet with reward tracking
βββ pipelines/
β βββ sd15_reward_pipeline.py # Base pipeline with reward tracking
β βββ sd15_gradient_ascent_pipeline.py # Pipeline with gradient ascent
βββ lr_scheduler.py # Learning rate schedulers
βββ gradient_ascent_utils.py # Core gradient ascent implementation
βββ grad_ascent_configs.py # Configuration presets
βββ eval.py # Comprehensive evaluation script
βββ examples.sh # Example commands
```
### Gradient Ascent Flow
```
1. Load Stable Diffusion + LRM Reward Model
2. Start denoising process (T β 0)
3. At each timestep t:
a. Standard denoising step (predict noise, remove it)
b. Compute reward R(latents, prompt, t) and store in history
c. If t in gradient range:
- Enable gradients on latents
- Compute βR w.r.t. latents
- For each gradient step:
* Get current LR from scheduler
* Apply momentum (if enabled)
* Update: latents += lr * momentum(βR)
- Track statistics (grad norms, reward improvement)
4. At final timestep (t=0):
- Final reward computed on clean latent
- This reward is reported in logs
5. Decode final latent (xβ) to image via VAE
6. Compute quality metrics on image
```
### Understanding Reward Calculation
**Key Concepts:**
- **Timestep-Aware Rewards**: The LRM reward model computes preference scores at ANY noise level (timestep t)
- **Progressive Tracking**: Rewards are calculated at every denoising step throughout generation
- **Final Latent Reward**: The reported metric is the reward for t=0 (the clean latent before decoding)
- **Not Averaged**: The final reward is specifically from the last timestep, NOT an average across all timesteps
**What gets reported:**
```python
# During generation: Rewards computed at each t (1000 β 0)
Step 0: t=1000, reward=3.2
Step 1: t=990, reward=3.5
...
Step 99: t=10, reward=5.1
Step 100: t=0, reward=5.4 β This is what gets logged!
```
The `Reward (t=0)` in logs represents the preference score of the final clean latent that was decoded into your output image.
---
## Learning Rate Scheduling
### Available Schedulers
#### 1. **Constant LR**
```python
lr_scheduler_type="constant"
```
- Fixed learning rate throughout optimization
- Simple and stable
- Good for quick experiments
#### 2. **Linear Decay**
```python
lr_scheduler_type="linear"
lr_scheduler_kwargs={
"end_lr": 0.01, # End LR (10% of initial)
"start_step": 0 # When to start decay
}
```
- Linear decrease from initial to end LR
- Smooth convergence
- Configurable warmup period
#### 3. **Cosine Annealing** (Recommended)
```python
lr_scheduler_type="cosine"
lr_scheduler_kwargs={
"min_lr": 0.001, # Minimum LR
"warmup_steps": 3 # Linear warmup steps
}
```
- Smooth cosine decay
- Optional warmup phase
- Widely used in deep learning
- **Best for most use cases**
#### 4. **Exponential Decay**
```python
lr_scheduler_type="exponential"
lr_scheduler_kwargs={
"gamma": 0.9 # Decay factor per step
}
```
- Exponential decrease
- Fast initial decay
- Good for aggressive optimization
#### 5. **Step Decay**
```python
lr_scheduler_type="step"
lr_scheduler_kwargs={
"step_size": 5, # Steps between decays
"gamma": 0.5 # Multiplicative factor
}
```
- Step-wise LR reduction
- Periodic decay
- Good for scheduled changes
### Usage Example
```python
from pipelines.sd15_gradient_ascent_pipeline import StableDiffusionGradientAscentPipeline
pipeline.enable_gradient_ascent(
grad_timestep_range=(0, 700),
num_grad_steps=15,
grad_step_size=0.1, # Initial LR
lr_scheduler_type="cosine",
lr_scheduler_kwargs={
"min_lr": 0.001,
"warmup_steps": 3
}
)
```
---
## Configuration Presets
We provide 15 pre-configured optimization strategies. Use them with `--grad_config <name>`.
### Basic Configurations
| Config | LR Schedule | Momentum | Steps | Description |
|--------|-------------|----------|-------|-------------|
| `constant` | Constant | No | 5 | Simple baseline |
| `linear` | Linear decay | No | 10 | Smooth decay |
| `linear_warmstart` | Linear w/ warmup | No | 10 | Stable start |
| `cosine` | Cosine | No | 10 | Smooth convergence |
| `cosine_warmup` | Cosine w/ warmup | No | 20 | Best convergence |
| `exponential` | Exponential | No | 15 | Fast decay |
| `step` | Step-wise | No | 20 | Periodic decay |
### Momentum Configurations
| Config | LR Schedule | Momentum | Steps | Description |
|--------|-------------|----------|-------|-------------|
| `momentum` | Constant | Standard | 10 | Faster convergence |
| `nesterov` | Constant | Nesterov | 10 | Better convergence |
### Advanced Configurations
| Config | LR Schedule | Momentum | Steps | Description |
|--------|-------------|----------|-------|-------------|
| `cosine_momentum` | Cosine | Standard | 15 | High quality |
| `cosine_nesterov` | Cosine | Nesterov | 15 | **Recommended** |
| `linear_nesterov` | Linear | Nesterov | 15 | Stable + fast |
### Quality Presets
| Config | LR Schedule | Momentum | Steps | Use Case |
|--------|-------------|----------|-------|----------|
| `high_quality` | Cosine | Nesterov | 20 | **Best quality** |
| `aggressive` | Exponential | Standard | 8 | Fast results |
| `conservative` | Cosine | Nesterov | 25 | Most stable |
### Config Details
#### `high_quality` (Recommended for Research)
```python
{
"grad_timestep_range": (200, 800), # Focus on middle timesteps
"num_grad_steps": 20,
"grad_step_size": 0.08,
"lr_scheduler_type": "cosine",
"lr_scheduler_kwargs": {"min_lr": 0.005, "warmup_steps": 5},
"use_momentum": True,
"momentum": 0.95,
"use_nesterov": True
}
```
#### `cosine_nesterov` (Recommended for General Use)
```python
{
"grad_timestep_range": (0, 700),
"num_grad_steps": 15,
"grad_step_size": 0.12,
"lr_scheduler_type": "cosine",
"lr_scheduler_kwargs": {"min_lr": 0.001, "warmup_steps": 3},
"use_momentum": True,
"momentum": 0.9,
"use_nesterov": True
}
```
#### `aggressive` (Fast Experimentation)
```python
{
"grad_timestep_range": (0, 900),
"num_grad_steps": 8,
"grad_step_size": 0.15,
"grad_scale": 1.2,
"lr_scheduler_type": "exponential",
"lr_scheduler_kwargs": {"gamma": 0.85},
"use_momentum": True,
"momentum": 0.85,
"use_nesterov": False
}
```
### Listing Configs
```python
from grad_ascent_configs import list_configs, print_config, get_config
# List all available configs
print(list_configs())
# Output: ['aggressive', 'conservative', 'constant', 'cosine', ...]
# Print config details
print_config("cosine_nesterov")
# Get config dictionary
config = get_config("high_quality")
pipeline.enable_gradient_ascent(**config)
```
---
## Evaluation Metrics
### 1. **FID (FrΓ©chet Inception Distance)**
- Measures distribution similarity between real and generated images
- **Lower is better**
- Requires reference images (COCO dataset only)
- Computationally expensive
```bash
--metrics fid
```
### 2. **CLIP Score**
- Evaluates text-image alignment using CLIP embeddings
- **Higher is better**
- Fast and reliable
- Good for general quality assessment
```bash
--metrics clip
```
### 3. **Aesthetic Score**
- Predicts aesthetic quality using CLIP + MLP
- **Higher is better**
- Trained on human aesthetic ratings
- Good for visual appeal
```bash
--metrics aesthetic
```
### 4. **PickScore** (New)
- Human preference predictor from Pick-a-Pic dataset
- **Higher is better**
- Trained on large-scale human comparisons
- State-of-the-art preference metric
```bash
--metrics pickscore
```
### 5. **HPSv2** (New)
- Human Preference Score version 2
- **Higher is better**
- Trained on aesthetic evaluations
- Complementary to PickScore
```bash
--metrics hpsv2
```
### 6. **ImageReward** (New)
- Reward model from RLHF (Reinforcement Learning from Human Feedback)
- **Higher is better**
- Comprehensive quality assessment
- Trained on diverse human feedback
```bash
--metrics imagereward
```
### Metric Recommendations
| Use Case | Recommended Metrics | Reason |
|----------|---------------------|--------|
| Research/Papers | `fid clip aesthetic pickscore hpsv2` | Comprehensive evaluation |
| Quick Iteration | `clip aesthetic` | Fast and reliable |
| Human Alignment | `pickscore hpsv2 imagereward` | Preference-based |
| Text Alignment | `clip imagereward` | Focus on prompt adherence |
| Visual Quality | `aesthetic pickscore` | Focus on aesthetics |
---
## Model Variants
Support for multiple SD1.5 model variants trained with different methods.
### Available Variants
#### 1. **Origin** (Default)
```bash
--model_variant origin
```
- Original Stable Diffusion v1.5 from RunwayML
- No additional training
- CFG scale: 7.5 (default)
- Good baseline
#### 2. **SPO** (Supervised Policy Optimization)
```bash
--model_variant spo
```
- Trained with SPO method
- Model: `SPO-Diffusion-Models/SPO-SD-v1-5_4k-p_10ep`
- **CFG scale: 5.0** (auto-adjusted)
- Better prompt adherence
#### 3. **Diffusion-DPO** (Direct Preference Optimization)
```bash
--model_variant diffusion_dpo
```
- Trained with DPO on human preferences
- Model: `mhdang/dpo-sd1.5-text2image-v1`
- CFG scale: 7.5
- Improved human alignment
#### 4. **LPO** (Latent Preference Optimization)
```bash
--model_variant lpo
```
- Trained with LPO (this project's main method)
- Model: `casiatao/LPO` (lpo_sd15_merge)
- **CFG scale: 5.0** (auto-adjusted)
- **Highest quality baseline**
### Comparison
| Variant | Training Method | Quality | Speed | Best For |
|---------|----------------|---------|-------|----------|
| Origin | Pre-training only | Good | Fast | Baseline |
| SPO | Supervised | Better | Fast | Prompt adherence |
| Diffusion-DPO | Preference learning | Better | Fast | Human preferences |
| LPO | Latent preference | **Best** | Fast | Overall quality |
### Usage Example
```bash
# Compare all variants
for variant in origin spo diffusion_dpo lpo; do
python eval.py \
--model_variant $variant \
--grad_config high_quality \
--metrics clip aesthetic pickscore \
--max_samples 100 \
--output_dir results/${variant}
done
```
---
## Datasets
### 1. **COCO Validation** (Default)
```bash
--dataset_type coco
--data_dir ./data
```
**Features:**
- Standard benchmark dataset
- Reference images available (for FID)
- ~5,000 validation samples
- Diverse prompts
**Structure:**
```
data/coco/
βββ caption_val.json
βββ images/val/
βββ 000000000139.jpg
βββ 000000000285.jpg
βββ ...
```
### 2. **Pick-a-Pic Validation**
```bash
--dataset_type pickapic
```
**Features:**
- Large-scale human preference dataset
- Streaming (no download needed)
- ~500,000 validation samples
- Real user prompts
- No reference images (FID not available)
**Advantages:**
- More diverse prompts
- Real-world use cases
- Human preference focus
- Large-scale evaluation
### Dataset Recommendations
| Use Case | Dataset | Reason |
|----------|---------|--------|
| Academic Research | COCO | Standard benchmark, reproducible |
| FID Evaluation | COCO | Requires reference images |
| Human Preference | Pick-a-Pic | Trained on human comparisons |
| Large-scale Tests | Pick-a-Pic | 500K+ samples available |
| Quick Tests | COCO | Smaller, faster |
---
## Usage Examples
### Example 1: Quick Test
```bash
python eval.py \
--grad_config cosine_nesterov \
--metrics clip aesthetic \
--max_samples 10 \
--output_dir examples/quick_test
```
### Example 2: High-Quality Research Evaluation
```bash
python eval.py \
--grad_config high_quality \
--metrics fid clip aesthetic pickscore hpsv2 \
--max_samples 200 \
--save_images \
--output_dir examples/research
```
### Example 3: Pick-a-Pic Benchmark
```bash
python eval.py \
--dataset_type pickapic \
--grad_config cosine_nesterov \
--metrics pickscore hpsv2 imagereward \
--max_samples 500 \
--output_dir examples/pickapic
```
### Example 4: LPO Model Evaluation
```bash
python eval.py \
--model_variant lpo \
--grad_config high_quality \
--metrics clip aesthetic pickscore \
--max_samples 100 \
--save_images \
--output_dir examples/lpo_model
```
### Example 5: Baseline Only (No Gradient Ascent)
```bash
python eval.py \
--mode baseline \
--model_variant origin \
--metrics clip aesthetic pickscore \
--max_samples 50 \
--output_dir examples/baseline_only
```
### Example 6: Manual Configuration
```bash
python eval.py \
--grad_range_start 200 \
--grad_range_end 800 \
--grad_steps 15 \
--grad_step_size 0.08 \
--metrics clip aesthetic \
--max_samples 50 \
--output_dir examples/manual_config
```
### Example 7: Model Comparison
```bash
# Evaluate all model variants
for variant in origin spo diffusion_dpo lpo; do
python eval.py \
--model_variant $variant \
--grad_config high_quality \
--metrics clip aesthetic pickscore \
--max_samples 100 \
--save_images \
--output_dir results/comparison/${variant}
done
```
### Example 8: Conservative Optimization
```bash
python eval.py \
--grad_config conservative \
--metrics clip aesthetic pickscore hpsv2 \
--max_samples 100 \
--save_images \
--output_dir examples/conservative
```
---
## API Reference
### Pipeline Usage
```python
from diffusers import StableDiffusionPipeline
from pipelines.sd15_gradient_ascent_pipeline import StableDiffusionGradientAscentPipeline
from models import LRMRewardModel
# Load base pipeline
base_pipeline = StableDiffusionPipeline.from_pretrained(
"runwayml/stable-diffusion-v1-5",
torch_dtype=torch.float16
)
# Create gradient ascent pipeline
pipeline = StableDiffusionGradientAscentPipeline(**base_pipeline.components)
# Load reward model
reward_model = LRMRewardModel(
pretrained_model_name_or_path="runwayml/stable-diffusion-v1-5",
lrm_model_path="casiatao/LRM",
guidance_scale=7.5,
device="cuda"
)
pipeline.set_reward_model(reward_model)
# Enable gradient ascent with preset
from grad_ascent_configs import get_config
config = get_config("cosine_nesterov")
pipeline.enable_gradient_ascent(**config)
# Or configure manually
pipeline.enable_gradient_ascent(
grad_timestep_range=(200, 800),
num_grad_steps=15,
grad_step_size=0.1,
lr_scheduler_type="cosine",
lr_scheduler_kwargs={"min_lr": 0.001, "warmup_steps": 3},
use_momentum=True,
momentum=0.9,
use_nesterov=True
)
# Generate with gradient ascent
output = pipeline(
prompt="a beautiful mountain landscape at sunset",
num_inference_steps=50,
guidance_scale=7.5,
)
# Get gradient statistics
stats = pipeline.grad_guidance.get_statistics()
print(f"Reward improvement: {stats['avg_reward_improvement']:.4f}")
```
### Custom LR Scheduler
```python
from lr_scheduler import create_lr_scheduler
# Create cosine scheduler with warmup
scheduler = create_lr_scheduler(
scheduler_type="cosine",
initial_lr=0.1,
num_steps=20,
min_lr=0.001,
warmup_steps=5
)
# Use in optimization loop
for step in range(20):
current_lr = scheduler.get_lr()
# ... apply gradient with current_lr ...
scheduler.step()
```
### Configuration Management
```python
from grad_ascent_configs import get_config, list_configs, print_config
# List all available configs
all_configs = list_configs()
print(f"Available configs: {all_configs}")
# Get specific config
config = get_config("high_quality")
# Print config details
print_config("cosine_nesterov")
# Create custom config
custom_config = {
"grad_timestep_range": (300, 700),
"num_grad_steps": 12,
"grad_step_size": 0.09,
"lr_scheduler_type": "cosine",
"lr_scheduler_kwargs": {"min_lr": 0.002, "warmup_steps": 4},
"use_momentum": True,
"momentum": 0.92,
"use_nesterov": True
}
pipeline.enable_gradient_ascent(**custom_config)
```
---
## Command-Line Options
### Essential Options
```bash
--data_dir PATH # Path to data directory (default: ./data)
--dataset_type TYPE # Dataset: coco or pickapic (default: coco)
--model_variant VARIANT # Model: origin, spo, diffusion_dpo, lpo (default: origin)
--max_samples N # Max samples to evaluate (default: all)
--output_dir PATH # Output directory (default: eval_outputs)
--save_images # Save generated images
```
### Gradient Ascent Options
```bash
--grad_config NAME # Use preset config (recommended)
--grad_range_start N # Gradient timestep start (default: 0)
--grad_range_end N # Gradient timestep end (default: 700)
--grad_steps N # Gradient steps per timestep (default: 5)
--grad_step_size FLOAT # Initial learning rate (default: 0.1)
```
### Evaluation Options
```bash
--metrics METRIC [METRIC...] # Metrics to evaluate (default: clip aesthetic)
# Options: fid, clip, aesthetic, pickscore, hpsv2, imagereward
--mode MODE # baseline, gradient_ascent, or both (default: both)
--num_steps N # Diffusion inference steps (default: 50)
--cfg_scale FLOAT # CFG scale (default: 7.5, auto-adjusted for some models)
--batch_size N # Batch size (default: 1)
--log_interval N # Log every N batches (default: 10)
```
### Other Options
```bash
--lrm_model PATH # LRM model path (default: casiatao/LRM)
--seed N # Random seed (default: 42)
--cuda N # CUDA device ID (default: 0)
```
### Complete Example
```bash
python eval.py \
--data_dir ./data \
--dataset_type coco \
--model_variant lpo \
--grad_config high_quality \
--metrics fid clip aesthetic pickscore hpsv2 \
--max_samples 200 \
--num_steps 50 \
--save_images \
--output_dir results/comprehensive \
--cuda 0
```
---
## Output Files
After running evaluation, the following files are created in **auto-incremented run folders**:
```
RESULTS/SD1.5_GradAscent/
βββ run_1/ # First run
β βββ eval.log # Complete execution log
β βββ reward_curve.png # Reward progression plot
βββ run_2/ # Second run
β βββ eval.log
β βββ reward_curve.png
βββ run_3/ # Third run
βββ eval.log
βββ reward_curve.png
```
### Auto-Incrementing Run Folders
Each execution automatically creates a new `run_<N>/` folder, preventing accidental overwrites and maintaining a complete experiment history. No manual folder management needed!
### eval.log Structure
The log contains detailed information for each batch:
```
======================================================================
COCO GRADIENT ASCENT EVALUATION (BATCHED)
======================================================================
Logging to: ./RESULTS/SD1.5_GradAscent/run_1/eval.log
Device: cuda:6
Batch size: 1
Metrics: fid, clip, reward, aesthetic
Gradient Ascent: Range=[0, 900], Steps=1, StepSize=0.01
======================================================================
[Batch 1/5000] Samples: 1/5000 | FID: 2.5432 | CLIP: 0.8234 | Reward (t=0): 5.2341 | Reward (Avg): 5.2341 | Aesthetic: 6.456
[Batch 161/5000] Samples: 161/5000 | FID: 2.3821 | CLIP: 0.8412 | Reward (t=0): 5.4123 | Reward (Avg): 5.3215 | Aesthetic: 6.523
...
======================================================================
FINAL RESULTS
======================================================================
FID: 2.3456
CLIP avg: 0.8378
Reward avg: 5.3421
Aesthetic: 6.489
======================================================================
```
### reward_curve.png Visualization
The reward curve plot shows two panels for the **first generated image**:
**Left Panel: Reward vs Timestep**
- X-axis: Denoising timestep (t)
- Y-axis: Reward score
- Green shaded region: Where gradient ascent is applied
- Shows how reward evolves as noise is removed
**Right Panel: Reward vs Denoising Step**
- X-axis: Sequential denoising step (0 to num_inference_steps)
- Y-axis: Reward score
- Same data, different perspective for easier interpretation
**Key Insights from the Plot:**
- **Upward trend**: Reward generally increases as denoising progresses
- **Sharp improvements**: Visible spikes where gradient ascent is effective
- **Final reward**: Last point corresponds to t=0 (decoded image reward)
- **Learning dynamics**: Shows if optimization is working at different noise levels
### Reward Tracking Details
The script now explicitly tracks:
1. **Timestep-specific rewards**: Computed at every denoising step
2. **Final latent reward**: The reward for t=0 (the latent that gets decoded)
3. **Running average**: Mean reward across all processed samples
4. **Current batch reward**: Immediate feedback per batch
Example log output:
```
Reward (t=0): 5.4123 # Reward for the final decoded latent
Reward (Avg): 5.3215 # Running average across all samples
```
### evaluation_results.json Structure
(Legacy format from eval.py - test_grad_sd1.5.py uses simplified logging)
```json
{
"mode": "both",
"metrics": ["clip", "aesthetic", "pickscore"],
"config": {
"num_samples": 100,
"num_steps": 50,
"cfg_scale": 7.5,
"grad_range": [0, 700],
"grad_steps": 15,
"grad_step_size": 0.12
},
"baseline": {
"avg_reward": 0.7234,
"clip_score": 0.8123,
"aesthetic_score": 6.234,
"pickscore": 21.45
},
"gradient_ascent": {
"avg_reward": 0.7891,
"clip_score": 0.8345,
"aesthetic_score": 6.456,
"pickscore": 22.13,
"stats": {
"num_applications": 45,
"total_reward_improvement": 2.956,
"avg_reward_improvement": 0.0657
}
},
"comparison": {
"reward_difference": 0.0657,
"clip_difference": 0.0222,
"aesthetic_difference": 0.222,
"pickscore_difference": 0.68
}
}
```
---
## Troubleshooting
### Common Issues
#### 1. Out of Memory (OOM)
**Symptoms:**
```
RuntimeError: CUDA out of memory
```
**Solutions:**
```bash
# Reduce batch size
--batch_size 1
# Reduce max samples
--max_samples 50
# Reduce gradient steps
--grad_steps 5
# Use smaller config
--grad_config aggressive # Only 8 steps
```
#### 2. Slow Evaluation
**Symptoms:**
- Takes too long to complete
- Hanging on metric computation
**Solutions:**
```bash
# Skip expensive metrics
--metrics clip aesthetic # Skip FID
# Reduce samples
--max_samples 50
# Reduce diffusion steps
--num_steps 20
# Use faster dataset
--dataset_type pickapic # No FID computation
```
#### 3. Poor Results / No Improvement
**Symptoms:**
- Reward doesn't increase
- Quality worse after gradient ascent
**Solutions:**
```bash
# Try better configs
--grad_config high_quality
--grad_config conservative
# Increase gradient steps
--grad_steps 20
# Adjust timestep range (focus on middle)
--grad_range_start 200 --grad_range_end 800
# Try different model variant
--model_variant lpo
```
#### 4. Config Not Found
**Symptoms:**
```
ValueError: Unknown config: my_config
```
**Solutions:**
```bash
# List available configs
python -c "from grad_ascent_configs import list_configs; print(list_configs())"
# Print config details
python -c "from grad_ascent_configs import print_config; print_config('high_quality')"
```
#### 5. Metric Loading Errors
**Symptoms:**
```
Warning: Could not load PickScore scorer
```
**Solutions:**
```bash
# Install missing dependencies
pip install transformers datasets
# Check HuggingFace Hub access
huggingface-cli login
# Skip problematic metrics
--metrics clip aesthetic # Skip pickscore if it fails
```
#### 6. Dataset Not Found
**Symptoms:**
```
FileNotFoundError: Validation JSON not found
```
**Solutions:**
```bash
# Check data directory structure
ls data/coco/
# Use Pick-a-Pic instead (no local files needed)
--dataset_type pickapic
# Provide correct data path
--data_dir /path/to/your/data
```
---
## Best Practices
### 1. **Start Small, Scale Up**
```bash
# First: Quick test (10 samples)
python eval.py --grad_config cosine_nesterov --metrics clip --max_samples 10
# Then: Medium test (50 samples)
python eval.py --grad_config cosine_nesterov --metrics clip aesthetic --max_samples 50
# Finally: Full evaluation (200+ samples)
python eval.py --grad_config high_quality --metrics fid clip aesthetic pickscore hpsv2 --max_samples 200
```
### 2. **Choose Right Config for Use Case**
| Goal | Config | Metrics |
|------|--------|---------|
| Quick experiment | `cosine_nesterov` | `clip` |
| Research paper | `high_quality` | `fid clip aesthetic pickscore hpsv2` |
| Production | `conservative` | `pickscore hpsv2` |
| Fast iteration | `aggressive` | `clip aesthetic` |
### 3. **Use Multiple Metrics**
Don't rely on a single metric. Recommended combinations:
```bash
# Text alignment + aesthetics
--metrics clip aesthetic
# Human preference focus
--metrics pickscore hpsv2 imagereward
# Comprehensive (research)
--metrics fid clip aesthetic pickscore hpsv2
```
### 4. **Save Important Runs**
```bash
# Always save images for important evaluations
--save_images --output_dir results/important_run_$(date +%Y%m%d)
```
### 5. **Monitor GPU Usage**
```bash
# In separate terminal
watch -n 1 nvidia-smi
# Or use
gpustat -i 1
```
### 6. **Batch Evaluation**
```bash
# Create evaluation script
cat << 'EOF' > run_evals.sh
#!/bin/bash
for config in cosine_nesterov high_quality conservative; do
for model in origin lpo; do
python eval.py \
--model_variant $model \
--grad_config $config \
--metrics clip aesthetic pickscore \
--max_samples 100 \
--save_images \
--output_dir results/${model}_${config}
done
done
EOF
chmod +x run_evals.sh
./run_evals.sh
```
### 7. **Reproducibility**
```bash
# Always set seed for reproducible results
--seed 42
# Document your runs
--output_dir results/experiment_name_$(date +%Y%m%d_%H%M)
```
### 8. **Performance Tips**
- Use `batch_size=1` for safety (reward model compatibility)
- Start with `--max_samples 10` for debugging
- Use `--dataset_type pickapic` for large-scale evaluation (no FID overhead)
- Skip `fid` metric if not needed (expensive)
- Use `--num_steps 20-30` for faster generation (vs default 50)
### 9. **Config Selection Guide**
```python
# Start here
if "just_testing":
config = "constant"
# General use
elif "standard_evaluation":
config = "cosine_nesterov" # Best balance
# Research/papers
elif "need_best_quality":
config = "high_quality" # 20 steps, nesterov
# Fast experiments
elif "need_speed":
config = "aggressive" # 8 steps
# Stability critical
elif "need_stability":
config = "conservative" # 25 steps, careful
```
### 10. **Timestep Range Tips**
```python
# Full range (default)
--grad_range_start 0 --grad_range_end 700
# Middle timesteps (often best)
--grad_range_start 200 --grad_range_end 800
# Early timesteps (structure)
--grad_range_start 500 --grad_range_end 1000
# Late timesteps (details)
--grad_range_start 0 --grad_range_end 400
```
---
## Performance Metrics
### Expected Results
Based on COCO validation set (100 samples):
| Method | CLIP β | Aesthetic β | PickScore β | Time |
|--------|--------|-------------|-------------|------|
| Baseline (Origin) | 0.812 | 6.23 | 21.4 | 5 min |
| + Constant | 0.819 | 6.28 | 21.6 | 6 min |
| + Cosine Nesterov | 0.834 | 6.45 | 22.1 | 8 min |
| + High Quality | 0.841 | 6.52 | 22.4 | 12 min |
| Baseline (LPO) | 0.856 | 6.67 | 22.8 | 5 min |
| LPO + High Quality | 0.873 | 6.89 | 23.5 | 12 min |
*Results may vary based on hardware and specific prompts*
---
## Citation
If you use this code in your research, please cite:
```bibtex
@article{lpo2024,
title={Latent Preference Optimization for Diffusion Models},
author={Your Name},
journal={arXiv preprint},
year={2024}
}
```
---
## License
This project follows the license of the main LPO repository.
---
## Contributing
Contributions are welcome! Please:
1. Test your changes with `--max_samples 10`
2. Document new features in this README
3. Add examples to `examples.sh`
4. Follow existing code style
---
## Support
For issues and questions:
1. Check [Troubleshooting](#troubleshooting) section
2. Review [Examples](#usage-examples)
3. Open an issue on GitHub
---
## Changelog
### Latest Version (January 2026)
**New Features:**
- β¨ Learning rate scheduling (constant, linear, cosine, exponential, step)
- β¨ Momentum optimization (standard and Nesterov)
- β¨ 15 configuration presets
- β¨ Additional metrics (PickScore, HPSv2, ImageReward)
- β¨ Pick-a-Pic validation dataset support
- β¨ SD1.5 model variants (Origin, SPO, DPO, LPO)
- β¨ Comprehensive evaluation framework
- β¨ **Automatic run folder creation** - Each run creates `run_1/`, `run_2/`, etc.
- β¨ **Reward curve visualization** - Automatic plotting of reward progression across timesteps
- β¨ **Final timestep reward tracking** - Reports reward specifically from t=0 (decoded latent)
- β¨ **Detailed reward logging** - Shows both last timestep reward and running average
**Improvements:**
- π Better convergence with LR scheduling
- π Faster optimization with momentum
- π More comprehensive quality assessment
- π Visual feedback with reward curve plots
- π Complete documentation
- π Enhanced debugging with timestep-specific reward tracking
---
**Happy Optimizing! π**
|