Install HPSv3 for inference via PyPI
mainTo use HPSv3 for simple inference tasks, install the package directly from PyPI using pip.
pip install hpsv3repository·main·Indexed 43 days ago
https://github.com/mizzenai/hpsv3A VLM-based preference model for image quality assessment and prompt alignment, trained on the HPDv3 dataset. It provides tools for evaluating model performance via pairwise and ranking accuracy, reward benchmarking, and iterative image refinement using Chain-of-Human-Preference (CoHP). The package includes the HPSv3RewardInferencer class for scoring text-image pairs and supports training with 7B models using DeepSpeed.
To use HPSv3 for simple inference tasks, install the package directly from PyPI using pip.
pip install hpsv3To develop on the codebase or perform training, clone the repository and set up the environment using Conda. It is recommended to install flash-attn for optimized performance.
git clone https://github.com/MizzenAI/HPSv3.git
cd HPSv3
conda env create -f environment.yaml
conda activate hpsv3
# Recommend: Install flash-attn
pip install flash-attn==2.7.4.post1
pip install -e .The Human Preference Dataset v3 (HPDv3) can be downloaded from Hugging Face using the huggingface-cli.
huggingface-cli download --repo-type dataset MizzenAI/HPDv3 --local-dir /your-local-dataset-pathUse the evaluate/benchmark.py script to run inference across one or more image folders. For each image, the script expects a corresponding .txt file with the same name containing the text prompt.
The script calculates reward scores and outputs statistics (mean, std, min, max) for each folder, saving the full results to a JSON file.
python evaluate/benchmark.py \
--config_path config/HPSv3_7B.yaml \
--checkpoint_path checkpoints/HPSv3_7B/model.pth \
--model_type hpsv3 \
--image_folders /path/to/images/folder1 /path/to/images/folder2 \
--output_path ./benchmark_results.json \
--batch_size 16 \
--num_processes 8Use the evaluate/evaluate.py script to assess model performance on a test set. The script supports two evaluation modes:
pair mode: Calculates pairwise accuracy. The input JSON must provide a path1 (assumed better) and a path2 for each prompt.ranking mode: Calculates ranking accuracy. The input JSON must provide a list of image paths in generations and their corresponding ground-truth order in ranking.Pair-wise JSON format (--mode pair):
[
{
"prompt": ".....",
"path1": ".....",
"path2": "....."
}
]Rank-wise JSON format (--mode ranking):
[
{
"id": "005658-0040",
"prompt": ".....",
"generations": [
"path/to/image1",
"path/to/image2",
"path/to/image3",
"path/to/image4"
],
"ranking": [1, 2, 5, 3]
}
]python evaluate/evaluate.py \
--test_json /path/to/your/test_data.json \
--config_path config/HPSv3_7B.yaml \
--checkpoint_path checkpoints/HPSv3_7B/model.pth \
--mode pair \
--batch_size 8 \
--num_processes 8To add a new text-to-image model, you must define a new PipelineParam instance in utils/pipelines.py.
utils/pipelines.py.PipelineParam.PipelineParam with your model's configuration.--pipeline_name CLI argument.Available PipelineParam fields:
pipeline_name: Model path (Hugging Face Hub or local directory).generation_path: Subdirectory name for output images.pipeline_type: Type of pipeline (e.g., 't2i' for text-to-image, 't2v' for text-to-video). Defaults to 't2i'.pipe_init_kwargs: Dictionary of arguments for initializing the pipeline (e.g., {"torch_dtype": torch.float16}).generation_kwargs: Dictionary of arguments for the generation process (e.g., {"guidance_scale": 7.0}).base_resolution: The base resolution the model was trained on.force_aspect_ratio: (Optional) Force a specific aspect ratio (e.g., 1 for square).from pydantic import BaseModel, Field
import torch
# ... (PipelineParam class definition)
# Add your new model configuration
my_new_model_pipe = PipelineParam(
pipeline_name='organization/my-cool-model',
generation_path=f'generation/my_cool_model',
pipe_init_kwargs={
"torch_dtype": torch.float16,
},
base_resolution=1024,
generation_kwargs={
"guidance_scale": 5.0,
"num_inference_steps": 30,
}
)Use the gen_images_from_prompt.py script to perform image generation. The script reads prompts from a JSON file and can distribute tasks across multiple GPUs or machines.
To run a basic generation task, provide a JSON file containing your prompts, an output directory, and the names of the pipelines you wish to use.
python gen_images_from_prompt.py \
--json_path /path/to/your/prompts.json \
--out_dir /path/to/your/output_directory \
--pipeline_name sd_xl_pipe flux_schnell_pipeCoHP is a reasoning approach for iterative image refinement. It generates images using multiple diffusion models, selects the best one using a reward model, and performs iterative image-to-image generation to improve quality.
Run the run_cohp.py script with the required --prompt and --index arguments.
--prompt (required): The text prompt for image generation.--index (required): A unique identifier for saving the results.--device: The GPU device to use (default: 'cuda:1').--reward_model: The reward model used for scoring. Supported values:hpsv3 (default, recommended)hpsv2imagerewardpickscore0.8 for rounds 1-2 and 0.5 for rounds 3-4.python hpsv3/cohp/run_cohp.py \
--prompt "A beautiful sunset over mountains" \
--index "sample_001" \
--device "cuda:0" \
--reward_model "hpsv3"When training with LoRA, the system requires specific configuration constraints:
peft_lora_config.lora_enable is used, the LLM must not be frozen (model_config.freeze_llm must be False).peft_lora_config.vision_lora is False, the system automatically adds visual to the lora_namespan_exclude list to ensure LoRA is only applied to the language components.find_target_linear_names to automatically detect which modules to attach LoRA to based on num_lora_modules and lora_namespan_exclude.When training HPSv3, you can adjust several key parameters in your configuration file.
rm_head_type: The architecture of the reward model head (e.g., "ranknet").lora_enable: Boolean. If False, the language tower is fully trainable. If True, enables LoRA for efficient fine-tuning.vision_lora: Boolean. If False, the vision tower is fully trainable. If True, applies LoRA specifically to vision components.model_name_or_path: The path to the base model checkpoint (e.g., "Qwen/Qwen2-VL-7B-Instruct").confidence_threshold: Minimum confidence score required for training data (e.g., 0.95).train_json_list: A list of training data files (e.g., ["example_train.json"]).test_json_list: A list of validation datasets.output_dim: The output dimension of the reward head for $\mu$ and $\sigma$ (e.g., 2).loss_type: The loss function type used for training (e.g., "uncertainty").HPSv3 provides granular control over which parts of the multi-modal model are updated during training. The training logic manages three main areas:
model_config.freeze_llm. If not using LoRA, embed_tokens are typically frozen while the rest of the LLM is updated.model_config.freeze_vision_tower. Additionally, model_config.tune_merger determines if the visual-language merger is updated.model_config.trainable_visual_layers is set, the system unfreezes a specific number of blocks from the end of the visual tower (e.g., setting it to 1 unfreezes only the last block).rm_head (Reward Model head) is always set to requires_grad=True to ensure the score prediction is learned.You can run an interactive web interface to test the model locally by executing the Gradio demo script. The interface will be available at http://localhost:7860.
python gradio_demo/demo.py