HPSv3: Human Preference Score v3

repository·main·Indexed 43 days ago

https://github.com/mizzenai/hpsv3

A 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.

Tokens
6.6K
Snippets
23
Records
26
Agent score
57%

What's inside HPSv3

  1. Install HPSv3 locally for development or training

    main

    To 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 .
  2. Download the HPDv3 dataset

    main

    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-path
  3. Run reward benchmarking with `benchmark.py`

    main

    Use 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 8
  4. Evaluate model performance with `evaluate.py`

    main

    Use the evaluate/evaluate.py script to assess model performance on a test set. The script supports two evaluation modes:

    1. pair mode: Calculates pairwise accuracy. The input JSON must provide a path1 (assumed better) and a path2 for each prompt.
    2. 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.

    Input Data Formats

    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 8
  5. Add a new model to the Image Generation Module

    main

    To add a new text-to-image model, you must define a new PipelineParam instance in utils/pipelines.py.

    1. Open utils/pipelines.py.
    2. Import PipelineParam.
    3. Create a new instance of PipelineParam with your model's configuration.
    4. Use the variable name of your new instance in the --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,
            }
        )
  6. Generate images from text prompts using the CLI

    main

    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_pipe
  7. Run CoHP (Chain-of-Human-Preference) for iterative image refinement

    main

    CoHP 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.

    Usage

    Run the run_cohp.py script with the required --prompt and --index arguments.

    CLI 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)
      • hpsv2
      • imagereward
      • pickscore

    Process Details

    1. Multi-Model Generation: Uses FLUX.1 dev, Kolors, Stable Diffusion 3 Medium, and Playground v2.5.
    2. Reward Scoring: Evaluates images via the chosen reward model.
    3. Selection: Picks the model with the highest average score.
    4. Refinement: Performs 4 rounds of image-to-image generation. Strength is set to 0.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"
  8. Configure LoRA and PEFT for HPSv3 training

    main

    When training with LoRA, the system requires specific configuration constraints:

    1. LLM State: If peft_lora_config.lora_enable is used, the LLM must not be frozen (model_config.freeze_llm must be False).
    2. Vision LoRA: If 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.
    3. Target Modules: The system uses find_target_linear_names to automatically detect which modules to attach LoRA to based on num_lora_modules and lora_namespan_exclude.
  9. Configure HPSv3 training parameters

    main

    When training HPSv3, you can adjust several key parameters in your configuration file.

    Model Configuration

    • 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").

    Data Configuration

    • 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").
  10. Manage trainable parameters and layer freezing

    main

    HPSv3 provides granular control over which parts of the multi-modal model are updated during training. The training logic manages three main areas:

    • LLM/Embeddings: Controlled by model_config.freeze_llm. If not using LoRA, embed_tokens are typically frozen while the rest of the LLM is updated.
    • Vision Tower: Controlled by model_config.freeze_vision_tower. Additionally, model_config.tune_merger determines if the visual-language merger is updated.
    • Visual Layers: If 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).
    • Regression Head: The rm_head (Reward Model head) is always set to requires_grad=True to ensure the score prediction is learned.
  11. Launch the HPSv3 Gradio Demo

    main

    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