- 
                Notifications
    You must be signed in to change notification settings 
- Fork 282
Add flux example #2311
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
          
     Merged
      
      
    
  
     Merged
                    Add flux example #2311
Changes from 4 commits
      Commits
    
    
            Show all changes
          
          
            27 commits
          
        
        Select commit
          Hold shift + click to select a range
      
      122bc4c
              
                Add flux example
              
              
                mengniwang95 728f315
              
                add scripts
              
              
                mengniwang95 fdf6db3
              
                Merge branch 'master' into mengni/flux_example
              
              
                mengniwang95 b7a922e
              
                Update run_quant.sh
              
              
                mengniwang95 01571a1
              
                Update run_quant.sh
              
              
                mengniwang95 cdb3688
              
                Update main.py
              
              
                mengniwang95 502f571
              
                Update run_quant.sh
              
              
                mengniwang95 40c21f2
              
                Update requirements.txt
              
              
                mengniwang95 0c169e8
              
                Update requirements.txt
              
              
                mengniwang95 7412bdd
              
                Update README.md
              
              
                mengniwang95 d4097c9
              
                Update main.py
              
              
                mengniwang95 82f78d4
              
                Update main.py
              
              
                mengniwang95 9a0bbd4
              
                Update main.py
              
              
                mengniwang95 5bd640f
              
                Update main.py
              
              
                mengniwang95 6d61fac
              
                Update README.md
              
              
                mengniwang95 5d90e52
              
                Merge branch 'master' into mengni/flux_example
              
              
                mengniwang95 71dedc4
              
                fix eval
              
              
                mengniwang95 1bcbea5
              
                Update README.md
              
              
                mengniwang95 1c0c582
              
                fix script bug
              
              
                mengniwang95 decac5a
              
                update script
              
              
                mengniwang95 54d7e10
              
                Update run_benchmark.sh
              
              
                mengniwang95 49be6bf
              
                Update run_benchmark.sh
              
              
                mengniwang95 b865215
              
                Update run_quant.sh
              
              
                mengniwang95 41a7fca
              
                Update main.py
              
              
                mengniwang95 ab609b6
              
                Update run_benchmark.sh
              
              
                mengniwang95 e1567ec
              
                Update run_benchmark.sh
              
              
                mengniwang95 e8e3a0c
              
                Update run_benchmark.sh
              
              
                mengniwang95 File filter
Filter by extension
Conversations
          Failed to load comments.   
        
        
          
      Loading
        
  Jump to
        
          Jump to file
        
      
      
          Failed to load files.   
        
        
          
      Loading
        
  Diff view
Diff view
There are no files selected for viewing
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,34 @@ | ||
| # Step-by-Step | ||
|  | ||
| This example quantizes and validates the accuracy of Flux. | ||
|  | ||
| # Prerequisite | ||
|  | ||
| ## 1. Environment | ||
|  | ||
| ```shell | ||
| pip install -r requirements.txt | ||
| # Use `INC_PT_ONLY=1 pip install git+https://github.com/intel/[email protected]` for the latest updates before neural-compressor v3.6 release | ||
| pip install neural-compressor-pt==3.6 | ||
| # Use `pip install git+https://github.com/intel/[email protected]` for the latest updates before auto-round v0.8.0 release | ||
| pip install auto-round==0.8.0 | ||
| ``` | ||
|  | ||
| ## 2. Prepare Model | ||
|  | ||
| ```shell | ||
| hf download black-forest-labs/FLUX.1-dev --local-dir FLUX.1-dev | ||
| ``` | ||
|  | ||
| ## 3. Prepare Dataset | ||
| ```shell | ||
| wget https://github.com/mlcommons/inference/raw/refs/heads/master/text_to_image/coco2014/captions/captions_source.tsv | ||
| ``` | ||
|  | ||
| # Run | ||
|  | ||
| ```bash | ||
| CUDA_VISIBLE_DEVICES=0,1,2,3 bash run_quant.sh --topology=flux_fp8 --input_model=FLUX.1-dev | ||
| ``` | ||
| - topology: support flux_fp8 and flux_mxfp8 | ||
| - CUDA_VISIBLE_DEVICES: split the evaluation file into the number of GPUs' subset to speed up the evaluation | 
        
          
          
            181 changes: 181 additions & 0 deletions
          
          181 
        
  examples/pytorch/diffusion_model/diffusers/flux/main.py
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,181 @@ | ||
| # Copyright (c) 2025 Intel Corporation | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
|  | ||
| import os | ||
| import sys | ||
| import argparse | ||
|  | ||
| import pandas as pd | ||
| import tabulate | ||
| import torch | ||
|  | ||
| from diffusers import AutoPipelineForText2Image | ||
| from neural_compressor.torch.quantization import ( | ||
| AutoRoundConfig, | ||
| convert, | ||
| prepare, | ||
| ) | ||
| import multiprocessing as mp | ||
|  | ||
| from auto_round.compressors.diffusion.eval import metric_map | ||
| from auto_round.compressors.diffusion.dataset import get_diffusion_dataloader | ||
|  | ||
|  | ||
| def inference_worker(device, eval_file, pipe, image_save_dir): | ||
| if device != "cpu": | ||
| os.environ["CUDA_VISIBLE_DEVICES"] = str(device) | ||
| torch.cuda.set_device(device) | ||
|  | ||
| gen_kwargs = { | ||
| "guidance_scale": 7.5, | ||
| "num_inference_steps": 50, | ||
| "generator": None, | ||
| } | ||
|  | ||
| dataloader, _, _ = get_diffusion_dataloader(eval_file, nsamples=-1, bs=1) | ||
| prompt_list = [] | ||
| image_list = [] | ||
| for image_ids, prompts in dataloader: | ||
| prompt_list.extend(prompts) | ||
|  | ||
| new_ids = [] | ||
| new_prompts = [] | ||
| for idx, image_id in enumerate(image_ids): | ||
| image_id = image_id.item() | ||
| image_list.append(os.path.join(image_save_dir, str(image_id) + ".png")) | ||
|  | ||
| if os.path.exists(os.path.join(image_save_dir, str(image_id) + ".png")): | ||
| continue | ||
| new_ids.append(image_id) | ||
| new_prompts.append(prompts[idx]) | ||
|  | ||
| if len(new_prompts) == 0: | ||
| continue | ||
|  | ||
| output = pipe(prompt=new_prompts, **gen_kwargs) | ||
| for idx, image_id in enumerate(new_ids): | ||
| output.images[idx].save(os.path.join(image_save_dir, str(image_id) + ".png")) | ||
|  | ||
| return prompt_list, image_list | ||
|  | ||
| class BasicArgumentParser(argparse.ArgumentParser): | ||
| def __init__(self, *args, **kwargs): | ||
| super().__init__(*args, **kwargs) | ||
| self.add_argument("--model", "--model_name", "--model_name_or_path", | ||
| help="model name or path") | ||
|  | ||
| self.add_argument('--scheme', default="MXFP4", type=str, | ||
| help="quantizaion scheme.") | ||
|  | ||
| self.add_argument("--quantize", action="store_true") | ||
|  | ||
| self.add_argument("--inference", action="store_true") | ||
|  | ||
| self.add_argument("--dataset", type=str, default="coco2014", | ||
| help="the dataset for quantization training.") | ||
|  | ||
| self.add_argument("--output_dir", default="./tmp_autoround", type=str, | ||
| help="the directory to save quantized model") | ||
|  | ||
| self.add_argument("--eval_dataset", default="captions_source.tsv", type=str, | ||
| help="eval datasets") | ||
|  | ||
| self.add_argument("--output_image_path", default="./tmp_imgs", type=str, | ||
| help="the directory to save quantized model") | ||
|  | ||
|  | ||
| def setup_parser(): | ||
| parser = BasicArgumentParser() | ||
|  | ||
| parser.add_argument("--iters", "--iter", default=1000, type=int, | ||
| help="tuning iters") | ||
|  | ||
| args = parser.parse_args() | ||
| return args | ||
|  | ||
|  | ||
| def tune(args): | ||
| model_name = args.model | ||
| if model_name[-1] == "/": | ||
| model_name = model_name[:-1] | ||
| print(f"start to quantize {model_name}") | ||
|  | ||
| use_auto_mapping = True | ||
| layer_config = {} | ||
| pipe = AutoPipelineForText2Image.from_pretrained(model_name, torch_dtype=torch.bfloat16) | ||
| model = pipe.transformer | ||
| kwargs = {} | ||
| if args.scheme == "FP8": | ||
| for n, m in model.named_modules(): | ||
| if m.__class__.__name__ == "Linear": | ||
| layer_config[n] = {"bits": 8, "act_bits": 8, "data_type": "fp", "act_data_type": "fp", "group_size": 0, "act_group_size": 0} | ||
| elif args.scheme == "MXFP8": | ||
| kwargs["scheme"] = "MXFP8" | ||
|  | ||
| qconfig = AutoRoundConfig( | ||
| iters=args.iters, | ||
| dataset=args.dataset, | ||
| layer_config=layer_config, | ||
| num_inference_steps=3, | ||
| export_format="fake", | ||
| nsamples=128, | ||
| batch_size=1, | ||
| **kwargs | ||
| ) | ||
| model = prepare(model, qconfig) | ||
| model = convert(model, qconfig, pipeline=pipe) | ||
| return model, pipe | ||
|  | ||
| if __name__ == '__main__': | ||
| mp.set_start_method('spawn', force=True) | ||
| args = setup_parser() | ||
| model, pipe = tune(args) | ||
| if "--inference" in sys.argv: | ||
| if not os.path.exists(args.output_image_path): | ||
| os.makedirs(args.output_image_path) | ||
|  | ||
| visible_gpus = torch.cuda.device_count() | ||
|  | ||
| if visible_gpus == 0: | ||
| prompt_list, image_list = inference_worker("cpu", args.eval_dataset, pipe, args.output_image_path) | ||
|  | ||
| else: | ||
| df = pd.read_csv(args.eval_dataset, sep='\t') | ||
| subsut_sample_num = len(df) // visible_gpus | ||
| for i in range(visible_gpus): | ||
| start = i * subsut_sample_num | ||
| end = min((i + 1) * subsut_sample_num, len(df)) | ||
| df_subset = df.iloc[start : end] | ||
| df_subset.to_csv(f"subset_{i}.tsv", sep='\t', index=False) | ||
|  | ||
| pipe.model = model | ||
|  | ||
| with mp.Pool(processes=visible_gpus) as pool: | ||
| results = [pool.apply_async(inference_worker, (i, f"subset_{i}.tsv", pipe.to(f"cuda:{i}"), args.output_image_path)) for i in range(visible_gpus)] | ||
| outputs = [r.get() for r in results] | ||
|  | ||
| prompt_list = [] | ||
| image_list = [] | ||
| for output in outputs: | ||
| prompt_list.extend(output[0]) | ||
| image_list.extend(output[1]) | ||
|  | ||
| print("Evaluations for subset are done! Getting the final accuracy...") | ||
|  | ||
| result = {} | ||
| metrics = ["clip", "clip-iqa", "imagereward"] | ||
| for metric in metrics: | ||
| result.update(metric_map[metric](prompt_list, image_list, pipe.device)) | ||
|  | ||
| print(tabulate.tabulate(result.items(), tablefmt="grid")) | 
        
          
          
            5 changes: 5 additions & 0 deletions
          
          5 
        
  examples/pytorch/diffusion_model/diffusers/flux/requirements.txt
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| diffusers | ||
|         
                  chensuyue marked this conversation as resolved.
              Outdated
          
            Show resolved
            Hide resolved | ||
| clip | ||
| image-reward | ||
| torchmetrics | ||
| transformers==4.55.0 | ||
        
          
          
            55 changes: 55 additions & 0 deletions
          
          55 
        
  examples/pytorch/diffusion_model/diffusers/flux/run_quant.sh
  
  
      
      
   
        
      
      
    
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              | Original file line number | Diff line number | Diff line change | 
|---|---|---|
| @@ -0,0 +1,55 @@ | ||
| #!/bin/bash | ||
| set -x | ||
|  | ||
| function main { | ||
|  | ||
| init_params "$@" | ||
| run_tuning | ||
|  | ||
| } | ||
|  | ||
| # init params | ||
| function init_params { | ||
| for var in "$@" | ||
| do | ||
| case $var in | ||
| --topology=*) | ||
| topology=$(echo $var |cut -f2 -d=) | ||
| ;; | ||
| --dataset_location=*) | ||
| dataset_location=$(echo $var |cut -f2 -d=) | ||
| ;; | ||
| --input_model=*) | ||
| input_model=$(echo $var |cut -f2 -d=) | ||
| ;; | ||
| --output_model=*) | ||
| tuned_checkpoint=$(echo $var |cut -f2 -d=) | ||
| ;; | ||
| *) | ||
| echo "Error: No such parameter: ${var}" | ||
| exit 1 | ||
| ;; | ||
| esac | ||
| done | ||
|  | ||
| } | ||
|  | ||
| # run_tuning | ||
| function run_tuning { | ||
| tuned_checkpoint=${tuned_checkpoint:="saved_results"} | ||
|  | ||
| if [ "${topology}" = "flux_fp8" ]; then | ||
| extra_cmd="--scheme FP8 --iters 0 --dataset captions_source.tsv" | ||
| elif [ "${topology}" = "flux_mxfp8" ]; then | ||
| extra_cmd="--scheme MXFP8 --iters 10 --dataset captions_source.tsv" | ||
| fi | ||
|  | ||
| python3 main.py \ | ||
| --model ${input_model} \ | ||
| --output_dir ${tuned_checkpoint} \ | ||
| --quantize \ | ||
| --inference \ | ||
| ${extra_cmd} | ||
| } | ||
|  | ||
| main "$@" | 
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
              
      
      Oops, something went wrong.
        
    
  
  Add this suggestion to a batch that can be applied as a single commit.
  This suggestion is invalid because no changes were made to the code.
  Suggestions cannot be applied while the pull request is closed.
  Suggestions cannot be applied while viewing a subset of changes.
  Only one suggestion per line can be applied in a batch.
  Add this suggestion to a batch that can be applied as a single commit.
  Applying suggestions on deleted lines is not supported.
  You must change the existing code in this line in order to create a valid suggestion.
  Outdated suggestions cannot be applied.
  This suggestion has been applied or marked resolved.
  Suggestions cannot be applied from pending reviews.
  Suggestions cannot be applied on multi-line comments.
  Suggestions cannot be applied while the pull request is queued to merge.
  Suggestion cannot be applied right now. Please check back later.
  
    
  
    
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Please add Flux into this table, https://github.com/intel/neural-compressor/tree/master/examples#quantization