-
Notifications
You must be signed in to change notification settings - Fork 281
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
Open
mengniwang95
wants to merge
19
commits into
master
Choose a base branch
from
mengni/flux_example
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+320
−1
Open
Add flux example #2311
Changes from all commits
Commits
Show all changes
19 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 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
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/neural-compressor.git@v3.6rc` 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/auto-round.git@v0.8.0rc2` 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 |
191 changes: 191 additions & 0 deletions
191
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,191 @@ | ||
# 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 | ||
from torch.multiprocessing import Process, Queue | ||
|
||
|
||
def inference_worker(device, eval_file, pipe, image_save_dir, queue=None): | ||
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")) | ||
|
||
if queue is None: | ||
return prompt_list, image_list | ||
else: | ||
queue.put((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="MXFP8", 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, pipe): | ||
model = pipe.transformer | ||
layer_config = {} | ||
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) | ||
delattr(model, "save") | ||
return pipe | ||
|
||
if __name__ == '__main__': | ||
mp.set_start_method('spawn', force=True) | ||
args = setup_parser() | ||
model_name = args.model | ||
if model_name[-1] == "/": | ||
model_name = model_name[:-1] | ||
pipe = AutoPipelineForText2Image.from_pretrained(model_name, torch_dtype=torch.bfloat16) | ||
|
||
if "--quantize" in sys.argv: | ||
print(f"start to quantize {model_name}") | ||
pipe = tune(args, pipe) | ||
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) | ||
|
||
processes = [] | ||
queue = Queue() | ||
for i in range(visible_gpus): | ||
p = Process(target=inference_worker, args=(i, f"subset_{i}.tsv", pipe.to(f"cuda:{i}"), args.output_image_path, queue)) | ||
p.start() | ||
processes.append(p) | ||
for p in processes: | ||
p.join() | ||
|
||
outputs = [queue.get() for _ in range(visible_gpus)] | ||
|
||
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")) |
6 changes: 6 additions & 0 deletions
6
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,6 @@ | ||
diffusers==0.35.1 | ||
pandas==2.2.2 | ||
clip==0.2.0 | ||
image-reward==1.5 | ||
torchmetrics==1.8.2 | ||
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 --inference --quantize" | ||
elif [ "${topology}" = "flux_mxfp8" ]; then | ||
extra_cmd="--scheme MXFP8 --iters 1000 --dataset captions_source.tsv --inference --quantize" | ||
else | ||
extra_cmd="--inference" | ||
fi | ||
|
||
python3 main.py \ | ||
--model ${input_model} \ | ||
--output_dir ${tuned_checkpoint} \ | ||
${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
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