ymyy307 commited on
Commit
171f557
·
verified ·
1 Parent(s): 0ed6b0e

Upload folder using huggingface_hub (part 3)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. examples/boogu_image/model_training/validate_lora/Boogu-Image-0.1-Edit.py +32 -0
  2. examples/boogu_image/model_training/validate_lora/Boogu-Image-0.1-Turbo.py +30 -0
  3. examples/dev_tools/unit_test.py +121 -0
  4. examples/dev_tools/webui.py +408 -0
  5. examples/dev_tools/webui_train.py +445 -0
  6. examples/ernie_image/model_inference/ERNIE-Image-Turbo.py +25 -0
  7. examples/ernie_image/model_inference/ERNIE-Image.py +24 -0
  8. examples/ernie_image/model_inference_low_vram/ERNIE-Image-Turbo.py +37 -0
  9. examples/ernie_image/model_inference_low_vram/ERNIE-Image.py +36 -0
  10. examples/ernie_image/model_training/full/ERNIE-Image.sh +17 -0
  11. examples/ernie_image/model_training/full/accelerate_config_zero3.yaml +23 -0
  12. examples/ernie_image/model_training/lora/ERNIE-Image.sh +19 -0
  13. examples/ernie_image/model_training/special/split_training/ERNIE-Image.sh +40 -0
  14. examples/ernie_image/model_training/special/split_training/validate.py +25 -0
  15. examples/ernie_image/model_training/train.py +141 -0
  16. examples/ernie_image/model_training/validate_full/ERNIE-Image.py +25 -0
  17. examples/ernie_image/model_training/validate_lora/ERNIE-Image.py +25 -0
  18. examples/flux/README.md +3 -0
  19. examples/flux/model_inference/FLEX.2-preview.py +50 -0
  20. examples/flux/model_inference/FLUX.1-Fill-dev.py +29 -0
  21. examples/flux/model_inference/FLUX.1-Kontext-dev.py +54 -0
  22. examples/flux/model_inference/FLUX.1-Krea-dev.py +27 -0
  23. examples/flux/model_inference/FLUX.1-Redux-dev.py +28 -0
  24. examples/flux/model_inference/FLUX.1-dev-AttriCtrl.py +19 -0
  25. examples/flux/model_inference/FLUX.1-dev-Controlnet-Inpainting-Beta.py +37 -0
  26. examples/flux/model_inference/FLUX.1-dev-Controlnet-Union-alpha.py +40 -0
  27. examples/flux/model_inference/FLUX.1-dev-Controlnet-Upscaler.py +33 -0
  28. examples/flux/model_inference/FLUX.1-dev-EliGen.py +133 -0
  29. examples/flux/model_inference/FLUX.1-dev-IP-Adapter.py +24 -0
  30. examples/flux/model_inference/FLUX.1-dev-InfiniteYou.py +61 -0
  31. examples/flux/model_inference/FLUX.1-dev-LoRA-Encoder.py +38 -0
  32. examples/flux/model_inference/FLUX.1-dev-LoRA-Fusion.py +38 -0
  33. examples/flux/model_inference/FLUX.1-dev-Timestep-LoRA.py +21 -0
  34. examples/flux/model_inference/FLUX.1-dev.py +26 -0
  35. examples/flux/model_inference/Insert-Anything.py +44 -0
  36. examples/flux/model_inference/Nexus-Gen-Editing.py +37 -0
  37. examples/flux/model_inference/Nexus-Gen-Generation.py +32 -0
  38. examples/flux/model_inference/Step1X-Edit.py +32 -0
  39. examples/flux/model_inference_low_vram/FLEX.2-preview.py +61 -0
  40. examples/flux/model_inference_low_vram/FLUX.1-Fill-dev.py +39 -0
  41. examples/flux/model_inference_low_vram/FLUX.1-Kontext-dev.py +65 -0
  42. examples/flux/model_inference_low_vram/FLUX.1-Krea-dev.py +38 -0
  43. examples/flux/model_inference_low_vram/FLUX.1-Redux-dev.py +40 -0
  44. examples/flux/model_inference_low_vram/FLUX.1-dev-AttriCtrl.py +30 -0
  45. examples/flux/model_inference_low_vram/FLUX.1-dev-Controlnet-Inpainting-Beta.py +48 -0
  46. examples/flux/model_inference_low_vram/FLUX.1-dev-Controlnet-Union-alpha.py +50 -0
  47. examples/flux/model_inference_low_vram/FLUX.1-dev-Controlnet-Upscaler.py +44 -0
  48. examples/flux/model_inference_low_vram/FLUX.1-dev-EliGen.py +144 -0
  49. examples/flux/model_inference_low_vram/FLUX.1-dev-IP-Adapter.py +35 -0
  50. examples/flux/model_inference_low_vram/FLUX.1-dev-InfiniteYou.py +73 -0
examples/boogu_image/model_training/validate_lora/Boogu-Image-0.1-Edit.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from PIL import Image
3
+ from diffsynth.pipelines.boogu_image import BooguImagePipeline, ModelConfig
4
+
5
+ pipe = BooguImagePipeline.from_pretrained(
6
+ torch_dtype=torch.bfloat16,
7
+ device="cuda",
8
+ model_configs=[
9
+ ModelConfig(model_id="Boogu/Boogu-Image-0.1-Edit", origin_file_pattern="transformer/*.safetensors"),
10
+ ModelConfig(model_id="Boogu/Boogu-Image-0.1-Edit", origin_file_pattern="mllm/*.safetensors"),
11
+ ModelConfig(model_id="Boogu/Boogu-Image-0.1-Edit", origin_file_pattern="vae/*.safetensors"),
12
+ ],
13
+ processor_config=ModelConfig(model_id="Boogu/Boogu-Image-0.1-Edit", origin_file_pattern="mllm/"),
14
+ )
15
+
16
+ pipe.load_lora(pipe.dit, "models/train/Boogu-Image-0.1-Edit_lora/epoch-4.safetensors")
17
+
18
+ prompt = "将裙子改为粉色"
19
+ edit_image = Image.open("data/diffsynth_example_dataset/boogu_image/Boogu-Image-0.1-Edit/edit/image1.jpg").convert("RGB")
20
+
21
+ output = pipe(
22
+ prompt=prompt,
23
+ negative_prompt="",
24
+ edit_image=edit_image,
25
+ height=1024,
26
+ width=1024,
27
+ seed=42,
28
+ rand_device="cuda",
29
+ num_inference_steps=50,
30
+ cfg_scale=1.0,
31
+ )
32
+ output.save("image_Boogu-Image-0.1-Edit_lora.jpg")
examples/boogu_image/model_training/validate_lora/Boogu-Image-0.1-Turbo.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.boogu_image import BooguImagePipeline, ModelConfig
3
+
4
+ pipe = BooguImagePipeline.from_pretrained(
5
+ torch_dtype=torch.bfloat16,
6
+ device="cuda",
7
+ model_configs=[
8
+ ModelConfig(model_id="Boogu/Boogu-Image-0.1-Turbo", origin_file_pattern="transformer/*.safetensors"),
9
+ ModelConfig(model_id="Boogu/Boogu-Image-0.1-Turbo", origin_file_pattern="mllm/*.safetensors"),
10
+ ModelConfig(model_id="Boogu/Boogu-Image-0.1-Turbo", origin_file_pattern="vae/*.safetensors"),
11
+ ],
12
+ processor_config=ModelConfig(model_id="Boogu/Boogu-Image-0.1-Turbo", origin_file_pattern="mllm/"),
13
+ )
14
+
15
+ pipe.load_lora(pipe.dit, "models/train/Boogu-Image-0.1-Turbo_lora/epoch-4.safetensors")
16
+
17
+ prompt = "dog,white and brown dog, sitting on wall, under pink flowers"
18
+
19
+ output = pipe(
20
+ prompt=prompt,
21
+ negative_prompt="",
22
+ height=1024,
23
+ width=1024,
24
+ seed=42,
25
+ rand_device="cuda",
26
+ num_inference_steps=4,
27
+ cfg_scale=1.0,
28
+ sigmas=[0.999, 0.748, 0.5, 0.25],
29
+ )
30
+ output.save("image_Boogu-Image-0.1-Turbo_lora.jpg")
examples/dev_tools/unit_test.py ADDED
@@ -0,0 +1,121 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, shutil, multiprocessing, time
2
+ NUM_GPUS = 7
3
+
4
+
5
+ def script_is_processed(output_path, script):
6
+ return os.path.exists(os.path.join(output_path, script)) and "log.txt" in os.listdir(os.path.join(output_path, script))
7
+
8
+
9
+ def filter_unprocessed_tasks(script_path):
10
+ tasks = []
11
+ output_path = os.path.join("data", script_path)
12
+ for script in sorted(os.listdir(script_path)):
13
+ if not script.endswith(".sh") and not script.endswith(".py"):
14
+ continue
15
+ if script_is_processed(output_path, script):
16
+ continue
17
+ tasks.append(script)
18
+ return tasks
19
+
20
+
21
+ def run_inference(script_path):
22
+ tasks = filter_unprocessed_tasks(script_path)
23
+ output_path = os.path.join("data", script_path)
24
+ for script in tasks:
25
+ source_path = os.path.join(script_path, script)
26
+ target_path = os.path.join(output_path, script)
27
+ os.makedirs(target_path, exist_ok=True)
28
+ cmd = f"python {source_path} > {target_path}/log.txt 2>&1"
29
+ print(cmd, flush=True)
30
+ os.system(cmd)
31
+ for file_name in os.listdir("./"):
32
+ if file_name.endswith(".jpg") or file_name.endswith(".png") or file_name.endswith(".mp4"):
33
+ shutil.move(file_name, os.path.join(target_path, file_name))
34
+
35
+
36
+ def run_tasks_on_single_GPU(script_path, tasks, gpu_id, num_gpu):
37
+ output_path = os.path.join("data", script_path)
38
+ for script_id, script in enumerate(tasks):
39
+ if script_id % num_gpu != gpu_id:
40
+ continue
41
+ source_path = os.path.join(script_path, script)
42
+ target_path = os.path.join(output_path, script)
43
+ os.makedirs(target_path, exist_ok=True)
44
+ if script.endswith(".sh"):
45
+ cmd = f"CUDA_VISIBLE_DEVICES={gpu_id} bash {source_path} > {target_path}/log.txt 2>&1"
46
+ elif script.endswith(".py"):
47
+ cmd = f"CUDA_VISIBLE_DEVICES={gpu_id} python {source_path} > {target_path}/log.txt 2>&1"
48
+ print(cmd, flush=True)
49
+ os.system(cmd)
50
+
51
+
52
+ def run_train_multi_GPU(script_path):
53
+ tasks = filter_unprocessed_tasks(script_path)
54
+ output_path = os.path.join("data", script_path)
55
+ for script in tasks:
56
+ source_path = os.path.join(script_path, script)
57
+ target_path = os.path.join(output_path, script)
58
+ os.makedirs(target_path, exist_ok=True)
59
+ cmd = f"bash {source_path} > {target_path}/log.txt 2>&1"
60
+ print(cmd, flush=True)
61
+ os.system(cmd)
62
+ time.sleep(1)
63
+
64
+
65
+ def run_train_single_GPU(script_path):
66
+ tasks = filter_unprocessed_tasks(script_path)
67
+ processes = [multiprocessing.Process(target=run_tasks_on_single_GPU, args=(script_path, tasks, i, NUM_GPUS)) for i in range(NUM_GPUS)]
68
+ for p in processes:
69
+ p.start()
70
+ for p in processes:
71
+ p.join()
72
+
73
+
74
+ def move_files(prefix, target_folder):
75
+ os.makedirs(target_folder, exist_ok=True)
76
+ os.system(f"cp -r {prefix}* {target_folder}")
77
+ os.system(f"rm -rf {prefix}*")
78
+
79
+
80
+ def test_qwen_image():
81
+ run_inference("examples/qwen_image/model_inference")
82
+ run_inference("examples/qwen_image/model_inference_low_vram")
83
+ run_train_multi_GPU("examples/qwen_image/model_training/full")
84
+ run_inference("examples/qwen_image/model_training/validate_full")
85
+ run_train_single_GPU("examples/qwen_image/model_training/lora")
86
+ run_inference("examples/qwen_image/model_training/validate_lora")
87
+
88
+
89
+ def test_wan():
90
+ run_train_single_GPU("examples/wanvideo/model_inference")
91
+ move_files("video_", "data/output/model_inference")
92
+ run_train_single_GPU("examples/wanvideo/model_inference_low_vram")
93
+ move_files("video_", "data/output/model_inference_low_vram")
94
+ run_train_multi_GPU("examples/wanvideo/model_training/full")
95
+ run_train_single_GPU("examples/wanvideo/model_training/validate_full")
96
+ move_files("video_", "data/output/validate_full")
97
+ run_train_single_GPU("examples/wanvideo/model_training/lora")
98
+ run_train_single_GPU("examples/wanvideo/model_training/validate_lora")
99
+ move_files("video_", "data/output/validate_lora")
100
+
101
+
102
+ def test_flux():
103
+ run_inference("examples/flux/model_inference")
104
+ run_inference("examples/flux/model_inference_low_vram")
105
+ run_train_multi_GPU("examples/flux/model_training/full")
106
+ run_inference("examples/flux/model_training/validate_full")
107
+ run_train_single_GPU("examples/flux/model_training/lora")
108
+ run_inference("examples/flux/model_training/validate_lora")
109
+
110
+
111
+ def test_z_image():
112
+ run_inference("examples/z_image/model_inference")
113
+ run_inference("examples/z_image/model_inference_low_vram")
114
+ run_train_multi_GPU("examples/z_image/model_training/full")
115
+ run_inference("examples/z_image/model_training/validate_full")
116
+ run_train_single_GPU("examples/z_image/model_training/lora")
117
+ run_inference("examples/z_image/model_training/validate_lora")
118
+
119
+
120
+ if __name__ == "__main__":
121
+ test_z_image()
examples/dev_tools/webui.py ADDED
@@ -0,0 +1,408 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib, inspect, pkgutil, traceback, torch, os, re, typing, io
2
+ from typing import Union, List, Optional, Tuple, Iterable, Dict, Literal
3
+ from contextlib import contextmanager
4
+ from diffsynth.utils.data import VideoData
5
+ import streamlit as st
6
+ from diffsynth import ModelConfig
7
+ from diffsynth.diffusion.base_pipeline import ControlNetInput
8
+ from PIL import Image
9
+ from tqdm import tqdm
10
+ st.set_page_config(layout="wide")
11
+
12
+ class StreamlitTqdmWrapper:
13
+ """Wrapper class that combines tqdm and streamlit progress bar"""
14
+ def __init__(self, iterable, st_progress_bar=None):
15
+ self.iterable = iterable
16
+ self.st_progress_bar = st_progress_bar
17
+ self.tqdm_bar = tqdm(iterable)
18
+ self.total = len(iterable) if hasattr(iterable, '__len__') else None
19
+ self.current = 0
20
+
21
+ def __iter__(self):
22
+ for item in self.tqdm_bar:
23
+ if self.st_progress_bar is not None and self.total is not None:
24
+ self.current += 1
25
+ self.st_progress_bar.progress(self.current / self.total)
26
+ yield item
27
+
28
+ def __enter__(self):
29
+ return self
30
+
31
+ def __exit__(self, *args):
32
+ if hasattr(self.tqdm_bar, '__exit__'):
33
+ self.tqdm_bar.__exit__(*args)
34
+
35
+ @contextmanager
36
+ def catch_error(error_value):
37
+ try:
38
+ yield
39
+ except Exception as e:
40
+ error_message = traceback.format_exc()
41
+ print(f"Error {error_value}:\n{error_message}")
42
+
43
+ def parse_vram_config_from_an_example(path):
44
+ vram_config = {
45
+ "offload_dtype": None,
46
+ "offload_device": None,
47
+ "onload_dtype": None,
48
+ "onload_device": None,
49
+ "preparing_dtype": None,
50
+ "preparing_device": None,
51
+ "computation_dtype": None,
52
+ "computation_device": None,
53
+ }
54
+ with open(path, "r") as f:
55
+ for code in f.readlines():
56
+ code = code.strip()
57
+ for param in vram_config:
58
+ if vram_config[param] is None and f'"{param}":' in code:
59
+ value = code.split(" ")[-1].replace(",", "").replace('"', "").replace("torch.", "")
60
+ vram_config[param] = value
61
+ return vram_config
62
+
63
+ def parse_model_configs_from_an_example(path):
64
+ model_configs = []
65
+ vram_config = parse_vram_config_from_an_example(path)
66
+ with open(path, "r") as f:
67
+ for code in f.readlines():
68
+ code = code.strip()
69
+ if not code.startswith("ModelConfig"):
70
+ continue
71
+ pairs = re.findall(r'(\w+)\s*=\s*["\']([^"\']+)["\']', code)
72
+ config_dict = {k: v for k, v in pairs}
73
+ vram_config_ = vram_config if "**vram_config" in code else {}
74
+ model_configs.append(ModelConfig(model_id=config_dict["model_id"], origin_file_pattern=config_dict["origin_file_pattern"], **vram_config_))
75
+ return model_configs
76
+
77
+ def list_examples(path, keyword=None):
78
+ examples = []
79
+ if os.path.isdir(path):
80
+ for file_name in os.listdir(path):
81
+ examples.extend(list_examples(os.path.join(path, file_name), keyword=keyword))
82
+ elif path.endswith(".py"):
83
+ with open(path, "r") as f:
84
+ code = f.read()
85
+ if keyword is None or keyword in code:
86
+ examples.extend([path])
87
+ return examples
88
+
89
+ def parse_available_pipelines():
90
+ from diffsynth.diffusion.base_pipeline import BasePipeline
91
+ import diffsynth.pipelines as _pipelines_pkg
92
+ available_pipelines = {}
93
+ for _, name, _ in pkgutil.iter_modules(_pipelines_pkg.__path__):
94
+ with catch_error(f"Failed: import diffsynth.pipelines.{name}"):
95
+ mod = importlib.import_module(f"diffsynth.pipelines.{name}")
96
+ classes = {
97
+ cls_name: cls for cls_name, cls in inspect.getmembers(mod, inspect.isclass)
98
+ if issubclass(cls, BasePipeline) and cls is not BasePipeline and cls.__module__ == mod.__name__
99
+ }
100
+ available_pipelines.update(classes)
101
+ return available_pipelines
102
+
103
+ def parse_available_examples(path, available_pipelines):
104
+ available_examples = {}
105
+ for pipeline_name in available_pipelines:
106
+ examples = ["None"] + list_examples(path, keyword=f"{pipeline_name}.from_pretrained")
107
+ available_examples[pipeline_name] = examples
108
+ return available_examples
109
+
110
+ def draw_selectbox(label, options, option_map, value=None, disabled=False):
111
+ default_index = 0 if value is None else tuple(options).index([option for option in option_map if option_map[option]==value][0])
112
+ option = st.selectbox(label=label, options=tuple(options), index=default_index, disabled=disabled)
113
+ return option_map.get(option)
114
+
115
+ def parse_params(fn):
116
+ params = []
117
+ for name, param in inspect.signature(fn).parameters.items():
118
+ annotation = param.annotation if param.annotation is not inspect.Parameter.empty else None
119
+ default = param.default if param.default is not inspect.Parameter.empty else None
120
+ params.append({"name": name, "dtype": annotation, "value": default})
121
+ return params
122
+
123
+ def draw_vram_device(label, value=None, key_suffix="", disabled=False):
124
+ option_map = {"None": None, "disk": "disk", "cuda": "cuda", "cpu": "cpu"}
125
+ options = option_map.keys()
126
+ default_index = 0 if value is None else tuple(options).index(value)
127
+ option = st.selectbox(label=label, options=tuple(options), index=default_index, key=label + key_suffix, disabled=disabled)
128
+ return option_map.get(option)
129
+
130
+ def draw_vram_dtype(label, value=None, key_suffix="", disabled=False):
131
+ option_map = {"None": None, "disk": "disk", "bfloat16": torch.bfloat16, "float32": torch.float32, "float16": torch.float16, "float8_e4m3fn": torch.float8_e4m3fn, "float8_e5m2": torch.float8_e5m2}
132
+ options = option_map.keys()
133
+ default_index = 0 if value is None else tuple(options).index(value)
134
+ option = st.selectbox(label=label, options=tuple(options), index=default_index, key=label + key_suffix, disabled=disabled)
135
+ return option_map.get(option)
136
+
137
+ def draw_model_config(model_config=None, key_suffix="", disabled=False, enable_vram_config=False):
138
+ with st.container(border=True):
139
+ if model_config is None:
140
+ model_config = ModelConfig()
141
+ path = st.text_input(label="path", key="path" + key_suffix, value=model_config.path, disabled=disabled)
142
+ col1, col2 = st.columns(2)
143
+ with col1:
144
+ model_id = st.text_input(label="model_id", key="model_id" + key_suffix, value=model_config.model_id, disabled=disabled)
145
+ with col2:
146
+ origin_file_pattern = st.text_input(label="origin_file_pattern", key="origin_file_pattern" + key_suffix, value=model_config.origin_file_pattern, disabled=disabled)
147
+ if enable_vram_config:
148
+ with st.container(border=True):
149
+ col1, col2 = st.columns(2)
150
+ with col1:
151
+ offload_device = draw_vram_device(label="offload_device", value=model_config.offload_device, key_suffix=key_suffix, disabled=disabled)
152
+ onload_device = draw_vram_device(label="onload_device", value=model_config.onload_device, key_suffix=key_suffix, disabled=disabled)
153
+ preparing_device = draw_vram_device(label="preparing_device", value=model_config.preparing_device, key_suffix=key_suffix, disabled=disabled)
154
+ computation_device = draw_vram_device(label="computation_device", value=model_config.computation_device, key_suffix=key_suffix, disabled=disabled)
155
+ with col2:
156
+ offload_dtype = draw_vram_dtype(label="offload_dtype", value=model_config.offload_dtype, key_suffix=key_suffix, disabled=disabled)
157
+ onload_dtype = draw_vram_dtype(label="onload_dtype", value=model_config.onload_dtype, key_suffix=key_suffix, disabled=disabled)
158
+ preparing_dtype = draw_vram_dtype(label="preparing_dtype", value=model_config.preparing_dtype, key_suffix=key_suffix, disabled=disabled)
159
+ computation_dtype = draw_vram_dtype(label="computation_dtype", value=model_config.computation_dtype, key_suffix=key_suffix, disabled=disabled)
160
+ vram_config = {
161
+ "offload_device": offload_device,
162
+ "onload_device": onload_device,
163
+ "preparing_device": preparing_device,
164
+ "computation_device": computation_device,
165
+ "offload_dtype": offload_dtype,
166
+ "onload_dtype": onload_dtype,
167
+ "preparing_dtype": preparing_dtype,
168
+ "computation_dtype": computation_dtype,
169
+ }
170
+ else:
171
+ vram_config = {}
172
+ model_config = ModelConfig(
173
+ path=None if path == "" else path,
174
+ model_id=model_id,
175
+ origin_file_pattern=origin_file_pattern,
176
+ **vram_config,
177
+ )
178
+ return model_config
179
+
180
+ def draw_multi_model_config(name="", value=None, disabled=False, enable_vram_config=False):
181
+ model_configs = []
182
+ with st.container(border=True):
183
+ st.markdown(name)
184
+ num = st.number_input(f"num_{name}", min_value=0, max_value=20, value=0 if value is None else len(value), disabled=disabled)
185
+ for i in range(num):
186
+ model_config = draw_model_config(key_suffix=f"_{name}_{i}", model_config=None if value is None else value[i], disabled=disabled, enable_vram_config=enable_vram_config)
187
+ model_configs.append(model_config)
188
+ return model_configs
189
+
190
+ def draw_single_model_config(name="", value=None, disabled=False):
191
+ with st.container(border=True):
192
+ st.markdown(name)
193
+ model_config = draw_model_config(value, key_suffix=f"_{name}", disabled=disabled)
194
+ return model_config
195
+
196
+ def draw_multi_images(name="", value=None, disabled=False):
197
+ images = []
198
+ with st.container(border=True):
199
+ st.markdown(name)
200
+ num = st.number_input(f"num_{name}", min_value=0, max_value=20, value=0 if value is None else len(value), disabled=disabled)
201
+ for i in range(num):
202
+ image = st.file_uploader(name, type=["png", "jpg", "jpeg", "webp"], key=f"{name}_{i}", disabled=disabled)
203
+ if image is not None: images.append(Image.open(image))
204
+ return images
205
+
206
+ def draw_multi_elements(st_element, name="", value=None, disabled=False, kwargs=None):
207
+ if kwargs is None:
208
+ kwargs = {}
209
+ elements = []
210
+ with st.container(border=True):
211
+ st.markdown(name)
212
+ num = st.number_input(f"num_{name}", min_value=0, max_value=20, value=0 if value is None else len(value), disabled=disabled)
213
+ for i in range(num):
214
+ element = st_element(name, key=f"{name}_{i}", disabled=disabled, value=None if value is None else value[i], **kwargs)
215
+ elements.append(element)
216
+ return elements
217
+
218
+ def draw_lora_configs(name="", value=None, disabled=False):
219
+ elements = []
220
+ with st.container(border=True):
221
+ st.markdown(name)
222
+ num = st.number_input(f"num_{name}", min_value=0, max_value=20, value=0 if value is None else len(value), disabled=disabled)
223
+ for i in range(num):
224
+ with st.container(border=True):
225
+ lora_base_model = st.text_input(label="LoRA base model", key="LoRA base model" + f"LoRA_{i}")
226
+ lora_scale = st.slider(label="LoRA scale", min_value=-8.0, max_value=8.0, value=1.0, step=0.1, key="LoRA scale" + f"LoRA_{i}")
227
+ lora_config = draw_model_config(key_suffix=f"LoRA_{i}", disabled=disabled)
228
+ element = {"base_model": lora_base_model, "alpha": lora_scale, "lora_config": lora_config}
229
+ elements.append(element)
230
+ return elements
231
+
232
+ def draw_controlnet_input(name="", value=None, disabled=False):
233
+ with st.container(border=True):
234
+ st.markdown(name)
235
+ controlnet_id = st.number_input("controlnet_id", value=0, min_value=0, max_value=20, step=1, key=f"{name}_controlnet_id")
236
+ scale = st.number_input("scale", value=1.0, min_value=0.0, max_value=10.0, key=f"{name}_scale")
237
+ image = st.file_uploader("image", type=["png", "jpg", "jpeg", "webp"], disabled=disabled, key=f"{name}_image")
238
+ if image is not None: image = Image.open(image)
239
+ inpaint_image = st.file_uploader("inpaint_image", type=["png", "jpg", "jpeg", "webp"], disabled=disabled, key=f"{name}_inpaint_image")
240
+ if inpaint_image is not None: inpaint_image = Image.open(inpaint_image)
241
+ inpaint_mask = st.file_uploader("inpaint_mask", type=["png", "jpg", "jpeg", "webp"], disabled=disabled, key=f"{name}_inpaint_mask")
242
+ if inpaint_mask is not None: inpaint_mask = Image.open(inpaint_mask)
243
+ return ControlNetInput(controlnet_id=controlnet_id, scale=scale, image=image, inpaint_image=inpaint_image, inpaint_mask=inpaint_mask)
244
+
245
+ def draw_controlnet_inputs(name, value=None, disabled=False):
246
+ controlnet_inputs = []
247
+ with st.container(border=True):
248
+ st.markdown(name)
249
+ num = st.number_input(f"num_{name}", min_value=0, max_value=20, value=0 if value is None else len(value), disabled=disabled)
250
+ for i in range(num):
251
+ controlnet_input = draw_controlnet_input(name=f"{name}_{i}", value=None, disabled=disabled)
252
+ controlnet_inputs.append(controlnet_input)
253
+ return controlnet_inputs
254
+
255
+ def draw_ui_element(name, dtype, value):
256
+ unsupported_dtype = [
257
+ Dict[str, torch.Tensor],
258
+ torch.Tensor,
259
+ ]
260
+ if dtype in unsupported_dtype:
261
+ return
262
+ if value is None:
263
+ with st.container(border=True):
264
+ enable = st.checkbox(f"Enable {name}", value=False)
265
+ ui = draw_ui_element_safely(name, dtype, value=value, disabled=not enable)
266
+ if enable:
267
+ return ui
268
+ else:
269
+ return None
270
+ else:
271
+ return draw_ui_element_safely(name, dtype, value)
272
+
273
+ def draw_video(name, value=None, disabled=False):
274
+ ui = st.file_uploader(name, type=["mp4"], disabled=disabled)
275
+ if ui is not None:
276
+ ui = VideoData(ui)
277
+ ui = [ui[i] for i in range(len(ui))]
278
+ return ui
279
+
280
+ def draw_ui_element_safely(name, dtype, value, disabled=False):
281
+ if dtype == torch.dtype:
282
+ option_map = {"bfloat16": torch.bfloat16, "float32": torch.float32, "float16": torch.float16}
283
+ ui = draw_selectbox(name, option_map.keys(), option_map, value=value, disabled=disabled)
284
+ elif dtype == Union[str, torch.device]:
285
+ option_map = {"cuda": "cuda", "cpu": "cpu"}
286
+ ui = draw_selectbox(name, option_map.keys(), option_map, value=value, disabled=disabled)
287
+ elif dtype == bool:
288
+ ui = st.checkbox(name, value=value, disabled=disabled)
289
+ elif dtype == ModelConfig:
290
+ ui = draw_single_model_config(name, value=value, disabled=disabled)
291
+ elif dtype in [list[ModelConfig], List[ModelConfig], Union[list[ModelConfig], ModelConfig, str]]:
292
+ if name == "model_configs":
293
+ model_configs = st.session_state.get("model_configs_from_example")
294
+ ui = draw_multi_model_config(name, model_configs, disabled=disabled, enable_vram_config=True)
295
+ else:
296
+ ui = draw_multi_model_config(name, disabled=disabled)
297
+ elif dtype == str:
298
+ if "prompt" in name:
299
+ ui = st.text_area(name, value=value, height=3, disabled=disabled)
300
+ else:
301
+ ui = st.text_input(name, value=value, disabled=disabled)
302
+ elif dtype == float:
303
+ ui = st.number_input(name, value=value, disabled=disabled)
304
+ elif dtype == int:
305
+ ui = st.number_input(name, value=value, step=1, disabled=disabled)
306
+ elif dtype == Image.Image:
307
+ ui = st.file_uploader(name, type=["png", "jpg", "jpeg", "webp"], disabled=disabled)
308
+ if ui is not None: ui = Image.open(ui)
309
+ elif dtype in [List[Image.Image], list[Image.Image], Union[list[Image.Image], Image.Image], Union[List[Image.Image], Image.Image]]:
310
+ if "video" in name:
311
+ ui = draw_video(name, value=value, disabled=disabled)
312
+ else:
313
+ ui = draw_multi_images(name, value=value, disabled=disabled)
314
+ elif dtype in [List[ControlNetInput], list[ControlNetInput]]:
315
+ ui = draw_controlnet_inputs(name, value=value, disabled=disabled)
316
+ elif dtype in [List[str], list[str]]:
317
+ ui = draw_multi_elements(st.text_input, name, value=value, disabled=disabled)
318
+ elif dtype in [List[float], list[float], Union[list[float], float], Union[List[float], float]]:
319
+ ui = draw_multi_elements(st.number_input, name, value=value, disabled=disabled)
320
+ elif dtype in [List[int], list[int]]:
321
+ ui = draw_multi_elements(st.number_input, name, value=value, disabled=disabled, kwargs={"step": 1})
322
+ elif dtype in [List[List[Image.Image]], list[list[Image.Image]]]:
323
+ ui = draw_multi_elements(draw_video, name, value=value, disabled=disabled)
324
+ elif dtype in [tuple[int, int], Tuple[int, int]]:
325
+ with st.container(border=True):
326
+ st.markdown(name)
327
+ ui = (st.text_input(f"{name}_0", value=value[0], disabled=disabled), st.text_input(f"{name}_1", value=value[1], disabled=disabled))
328
+ elif isinstance(dtype, typing._LiteralGenericAlias):
329
+ with st.container(border=True):
330
+ st.markdown(f"{name} ({dtype})")
331
+ ui = st.text_input(name, value=value, disabled=disabled, label_visibility="hidden")
332
+ elif dtype is None:
333
+ if name == "progress_bar_cmd":
334
+ ui = value
335
+ else:
336
+ st.markdown(f"(`{name}` is not not configurable in WebUI). dtype: `{dtype}`.")
337
+ ui = value
338
+ return ui
339
+
340
+ def flush_example():
341
+ for key in list(st.session_state.keys()):
342
+ if key not in ["available_pipelines", "available_examples"]:
343
+ del st.session_state[key]
344
+
345
+ def launch_webui():
346
+ input_col, output_col = st.columns(2)
347
+ with input_col:
348
+ if "available_pipelines" not in st.session_state:
349
+ st.session_state["available_pipelines"] = parse_available_pipelines()
350
+ if "available_examples" not in st.session_state:
351
+ st.session_state["available_examples"] = parse_available_examples("./examples", st.session_state["available_pipelines"])
352
+
353
+ with st.expander("Pipeline", expanded=True):
354
+ pipeline_class = draw_selectbox("Pipeline Class", st.session_state["available_pipelines"].keys(), st.session_state["available_pipelines"], value=st.session_state["available_pipelines"]["ZImagePipeline"])
355
+ example = st.selectbox("Parse model configs from an example (optional)", st.session_state["available_examples"][pipeline_class.__name__], on_change=flush_example)
356
+
357
+ if st.button("Step 1: Parse Pipeline", type="primary"):
358
+ st.session_state["pipeline_class"] = pipeline_class
359
+ if example != "None":
360
+ st.session_state["model_configs_from_example"] = parse_model_configs_from_an_example(example)
361
+
362
+ if "pipeline_class" not in st.session_state:
363
+ return
364
+ with st.expander("Model", expanded=True):
365
+ input_params = {}
366
+ params = parse_params(pipeline_class.from_pretrained)
367
+ for param in params:
368
+ input_params[param["name"]] = draw_ui_element(**param)
369
+ lora_configs = draw_lora_configs(name="LoRA")
370
+ if st.button("Step 2: Load Models", type="primary"):
371
+ with st.spinner("Loading models", show_time=True):
372
+ if "pipe" in st.session_state:
373
+ del st.session_state["pipe"]
374
+ torch.cuda.empty_cache()
375
+ pipe = pipeline_class.from_pretrained(**input_params)
376
+ for lora_config in lora_configs:
377
+ pipe.load_lora(pipe.get_module(pipe, lora_config["base_model"]), lora_config=lora_config["lora_config"], alpha=lora_config["alpha"])
378
+ st.session_state["pipe"] = pipe
379
+
380
+ if "pipe" not in st.session_state:
381
+ return
382
+ with st.expander("Input", expanded=True):
383
+ pipe = st.session_state["pipe"]
384
+ input_params = {}
385
+ params = parse_params(pipeline_class.__call__)
386
+ for param in params:
387
+ if param["name"] in ["self"]:
388
+ continue
389
+ input_params[param["name"]] = draw_ui_element(**param)
390
+
391
+ with output_col:
392
+ if st.button("Step 3: Generate", type="primary"):
393
+ if "progress_bar_cmd" in input_params:
394
+ input_params["progress_bar_cmd"] = lambda iterable: StreamlitTqdmWrapper(iterable, st.progress(0))
395
+ result = pipe(**input_params)
396
+ st.session_state["result"] = result
397
+
398
+ if "result" in st.session_state:
399
+ result = st.session_state["result"]
400
+ if isinstance(result, Image.Image):
401
+ st.image(result)
402
+ buf = io.BytesIO()
403
+ result.save(buf, format='PNG')
404
+ st.download_button(label="Download", data=buf.getvalue(), file_name="image.png", mime="image/png", type="primary")
405
+ else:
406
+ print(f"unsupported result format: {result}")
407
+
408
+ launch_webui()
examples/dev_tools/webui_train.py ADDED
@@ -0,0 +1,445 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, importlib.util, argparse, pkgutil, inspect
2
+ from dataclasses import dataclass
3
+ import streamlit as st
4
+ st.set_page_config(layout="wide")
5
+
6
+ available_data_file_keys = ["animate_face_video", "animate_pose_video", "audio", "blockwise_controlnet_image", "blockwise_controlnet_inpaint_mask", "context_image", "control_video", "controlnet_image", "controlnet_inpaint_mask", "edit_image", "eligen_entity_masks", "image", "in_context_videos", "infinityou_id_image", "input_audio", "ipadapter_images", "kontext_images", "layer_input_image", "nexus_gen_reference_image", "reference_image", "s2v_pose_video", "step1x_reference_image", "vace_reference_image", "vace_video", "vap_video", "video", "wantodance_keyframes", "wantodance_music_path", "wantodance_reference_image"]
7
+ available_extra_inputs = ["animate_face_video", "animate_pose_video", "blockwise_controlnet_image", "blockwise_controlnet_inpaint_mask", "camera_control_direction", "camera_control_speed", "cfg_scale", "context_image", "control_video", "controlnet_image", "controlnet_inpaint_mask", "controlnet_processor_id", "edit_image", "eligen_entity_masks", "eligen_entity_prompts", "end_image", "frame_rate", "framewise_decoding", "in_context_downsample_factor", "in_context_videos", "infinityou_guidance", "infinityou_id_image", "input_audio", "input_image", "ipadapter_images", "kontext_images", "layer_input_image", "layer_num", "lora_encoder_inputs", "motion_bucket_id", "nexus_gen_reference_image", "num_inference_steps", "rand_device", "reference_image", "s2v_pose_video", "seed", "step1x_reference_image", "template_inputs", "vace_reference_image", "vace_video", "value_controller_inputs", "vap_video", "wantodance_fps", "wantodance_keyframes", "wantodance_keyframes_mask", "wantodance_music_path", "wantodance_reference_image"]
8
+ available_model_components = ["animate_adapter", "audio_dit", "audio_encoder", "audio_vae", "audio_vae_decoder", "audio_vae_encoder", "audio_vocoder", "blockwise_controlnet", "conditioner", "controlnet", "dinov3_image_encoder", "dit", "dit2", "dual_tower_bridge", "image2lora_coarse", "image2lora_fine", "image2lora_style", "image_encoder", "image_proj_model", "infinityou_processor", "ipadapter", "ipadapter_image_encoder", "lora_encoder", "lora_patcher", "motion_controller", "nexus_gen", "nexus_gen_editing_adapter", "nexus_gen_generation_adapter", "qwenvl", "siglip2_image_encoder", "step1x_connector", "text_encoder", "text_encoder_1", "text_encoder_2", "text_encoder_post_modules", "text_encoder_qwen3", "tokenizer_model", "tokenizer_t5xxl", "unet", "upsampler", "vace", "vace2", "vae", "vae_decoder", "vae_encoder", "value_controller", "vap", "video_dit", "video_dit2", "video_vae", "video_vae_decoder", "video_vae_encoder"]
9
+
10
+ @dataclass
11
+ class Parameter:
12
+ name: str = None
13
+ dtype: type = None
14
+ value: any = None
15
+ required: bool = False
16
+ choices: list = None
17
+ help: str = None
18
+
19
+ def parse_available_pipelines():
20
+ from diffsynth.diffusion.base_pipeline import BasePipeline
21
+ import diffsynth.pipelines as _pipelines_pkg
22
+ available_pipelines = {}
23
+ for _, name, _ in pkgutil.iter_modules(_pipelines_pkg.__path__):
24
+ mod = importlib.import_module(f"diffsynth.pipelines.{name}")
25
+ classes = {
26
+ cls_name: cls for cls_name, cls in inspect.getmembers(mod, inspect.isclass)
27
+ if issubclass(cls, BasePipeline) and cls is not BasePipeline and cls.__module__ == mod.__name__
28
+ }
29
+ available_pipelines.update(classes)
30
+ return available_pipelines
31
+
32
+ def search_for_options(name):
33
+ files = search_for_files("examples", ".sh")
34
+ params = set()
35
+ for file in files:
36
+ with open(file, "r", encoding="utf-8") as f:
37
+ for line in f.readlines():
38
+ if f"--{name}" in line and not line.startswith("#"):
39
+ line = line.strip()
40
+ line = line.replace(" \\", "").replace(f"--{name}", "").replace('"', "").replace(" ", "")
41
+ for param in line.split(","):
42
+ params.add(param)
43
+ for param in sorted(list(params)):
44
+ print(f'"{param}", ', end="")
45
+ print()
46
+
47
+ def search_for_available_pipeline_options():
48
+ from diffsynth.diffusion.base_pipeline import BasePipeline
49
+ pipeline_classes = parse_available_pipelines()
50
+ base_attrs = set(vars(BasePipeline()))
51
+ black_list = ["tokenizer", "processor", "tokenizer_1", "tokenizer_2", "audio_processor"]
52
+ options = []
53
+ for pipeline_class in pipeline_classes:
54
+ pipe = pipeline_classes[pipeline_class]()
55
+ members = [attr for attr in vars(pipe) if not attr.startswith("__") and attr not in base_attrs and getattr(pipe, attr) is None]
56
+ members = [attr for attr in members if attr not in black_list]
57
+ options.extend(members)
58
+ options = sorted(list(set(options)))
59
+ for option in sorted(list(options)):
60
+ print(f'"{option}", ', end="")
61
+ print()
62
+
63
+ def parse_available_training_scripts(path):
64
+ training_scripts = {}
65
+ for folder in os.listdir(path):
66
+ if os.path.isfile(f"{path}/{folder}/model_training/train.py"):
67
+ training_scripts[folder] = f"{path}/{folder}/model_training/train.py"
68
+ return training_scripts
69
+
70
+ def search_for_files(path, suffix):
71
+ if os.path.isfile(path):
72
+ if path.endswith(suffix): return [path]
73
+ return []
74
+ else:
75
+ files = []
76
+ for sub_path in os.listdir(path):
77
+ files.extend(search_for_files(os.path.join(path, sub_path), suffix))
78
+ return files
79
+
80
+ def parse_available_examples(path):
81
+ path = os.path.dirname(path)
82
+ examples = search_for_files(path, ".sh")
83
+ return examples
84
+
85
+ def parse_example(example_path):
86
+ value_dict = {}
87
+ with open(example_path, "r", encoding="utf-8") as f:
88
+ for line in f.readlines():
89
+ line = line.strip()
90
+ if line.startswith("#"):
91
+ continue
92
+ if not line.startswith("--"):
93
+ continue
94
+ line = line.replace("\\", "").strip()
95
+ if " " in line:
96
+ name, value = line[2:line.index(" ")], line[line.index(" ") + 1:]
97
+ if value.startswith('"') and value.endswith('"'):
98
+ value = value[1:-1]
99
+ if value.startswith("'") and value.endswith("'"):
100
+ value = value[1:-1]
101
+ else:
102
+ name, value = line[2:], True
103
+ value_dict[name] = value
104
+ return value_dict
105
+
106
+ def parse_parser(path):
107
+ spec = importlib.util.spec_from_file_location("train", path)
108
+ module = importlib.util.module_from_spec(spec)
109
+ spec.loader.exec_module(module)
110
+ for name in dir(module):
111
+ if name.endswith("parser") and callable(getattr(module, name)):
112
+ return getattr(module, name)
113
+ return None
114
+
115
+ def parse_parser_action(action, value=None):
116
+ if isinstance(action, argparse._StoreTrueAction) or isinstance(action, argparse._StoreFalseAction):
117
+ dtype = bool
118
+ else:
119
+ dtype = action.type
120
+ param = Parameter(
121
+ name=action.dest,
122
+ dtype=dtype,
123
+ value=action.default if value is None else dtype(value),
124
+ required=action.required,
125
+ choices=action.choices,
126
+ help=action.help,
127
+ )
128
+ return param
129
+
130
+ def parse_parser_actions(parser, example_path=None):
131
+ value_dict = {} if example_path is None or example_path == "None" else parse_example(example_path)
132
+ params = []
133
+ for action in parser._actions:
134
+ param = parse_parser_action(action, value=value_dict.get(action.dest))
135
+ if param.name == "help":
136
+ continue
137
+ params.append(param)
138
+ return params
139
+
140
+ def draw_model_id_with_origin_paths(param, disabled=False):
141
+ with st.container(border=True):
142
+ st.markdown(param.name, help=param.help)
143
+ model_id_with_origin_paths = [] if param.value is None else param.value.split(",")
144
+ num = st.number_input(f"Number of models", min_value=0, max_value=20, value=len(model_id_with_origin_paths), disabled=disabled)
145
+ result = []
146
+ for i in range(num):
147
+ col1, col2 = st.columns(2)
148
+ value = model_id_with_origin_paths[i].split(":") if i < len(model_id_with_origin_paths) else (None, None)
149
+ with col1:
150
+ model_id = st.text_input("model_id", value=value[0], key=f"model_id_{i}", disabled=disabled)
151
+ with col2:
152
+ origin_file_pattern = st.text_input("origin_file_pattern", value=value[1], key=f"origin_file_pattern_{i}", disabled=disabled)
153
+ result.append(f"{model_id}:{origin_file_pattern}")
154
+ result = ",".join(result)
155
+ return result
156
+
157
+ def draw_parameter(param, check_enable=True, disabled=False):
158
+ if check_enable and param.value is None:
159
+ with st.container(border=True):
160
+ enable_button = st.checkbox(f"Enable {param.name}", value=False, disabled=disabled)
161
+ ui = draw_parameter(param, check_enable=False, disabled=disabled or not enable_button)
162
+ if enable_button:
163
+ return ui
164
+ else:
165
+ return None
166
+ if param.name == "data_file_keys":
167
+ ui = st.multiselect(param.name, options=available_data_file_keys, accept_new_options=True, default=param.value.split(","), disabled=disabled, help=param.help)
168
+ ui = ",".join(ui)
169
+ elif param.name == "model_paths":
170
+ ui = st.text_area(param.name, value=param.value, height=3, disabled=disabled, help=param.help)
171
+ elif param.name == "model_id_with_origin_paths":
172
+ ui = draw_model_id_with_origin_paths(param, disabled=disabled)
173
+ elif param.name == "extra_inputs":
174
+ value = None if param.value is None else param.value.split(",")
175
+ ui = st.multiselect(param.name, options=available_extra_inputs, accept_new_options=True, default=value, disabled=disabled, help=param.help)
176
+ ui = ",".join(ui)
177
+ elif param.name in ["fp8_models", "offload_models", "trainable_models", "lora_base_model", "preset_lora_model"]:
178
+ value = None if param.value is None else param.value.split(",")
179
+ ui = st.multiselect(param.name, options=available_model_components, accept_new_options=True, default=value, disabled=disabled, help=param.help)
180
+ ui = ",".join(ui)
181
+ elif param.name == "learning_rate":
182
+ ui = st.number_input(param.name, value=param.value, format="%0.7f", step=1e-4, disabled=disabled, help=param.help)
183
+ elif param.dtype == str:
184
+ ui = st.text_input(param.name, value=param.value, disabled=disabled, help=param.help)
185
+ elif param.dtype == int:
186
+ ui = st.number_input(param.name, value=param.value, step=1, disabled=disabled, help=param.help)
187
+ elif param.dtype == float:
188
+ ui = st.number_input(param.name, value=param.value, disabled=disabled, help=param.help)
189
+ elif param.dtype == bool:
190
+ ui = st.checkbox(param.name, value=param.value, disabled=disabled, help=param.help)
191
+ else:
192
+ st.markdown(f"(`{param.name}` is not not configurable in WebUI). dtype: `{param.dtype}`.")
193
+ ui = None
194
+ return ui
195
+
196
+ def draw_dataset_configs(dataset_base_path, dataset_metadata_path, dataset_repeat, dataset_num_workers, data_file_keys):
197
+ dataset_base_path = draw_parameter(dataset_base_path)
198
+ dataset_metadata_path = draw_parameter(dataset_metadata_path)
199
+ col_1, col_2 = st.columns(2)
200
+ with col_1:
201
+ dataset_repeat = draw_parameter(dataset_repeat)
202
+ with col_2:
203
+ dataset_num_workers = draw_parameter(dataset_num_workers)
204
+ data_file_keys = draw_parameter(data_file_keys)
205
+ params = {
206
+ "dataset_base_path": dataset_base_path,
207
+ "dataset_metadata_path": dataset_metadata_path,
208
+ "dataset_repeat": dataset_repeat,
209
+ }
210
+ if dataset_num_workers > 0: params["dataset_num_workers"] = dataset_num_workers
211
+ params["data_file_keys"] = data_file_keys
212
+ return params
213
+
214
+ def draw_image_size(height, width, max_pixels):
215
+ mode = st.selectbox("Image scaling and cropping", options=["Scale if pixel count exceeds threshold", "Resize to a fixed size and crop"], index=int(max_pixels.value is None))
216
+ use_max_pixel = mode == "Scale if pixel count exceeds threshold"
217
+ use_height_width = mode == "Resize to a fixed size and crop"
218
+ col1, col2 = st.columns(2)
219
+ with col1:
220
+ with st.container(border=True):
221
+ max_pixels = draw_parameter(max_pixels, disabled=not use_max_pixel)
222
+ with col2:
223
+ with st.container(border=True):
224
+ height = draw_parameter(height, disabled=not use_height_width, check_enable=False)
225
+ width = draw_parameter(width, disabled=not use_height_width, check_enable=False)
226
+ if use_max_pixel:
227
+ return {"max_pixels": max_pixels}
228
+ else:
229
+ return {"height": height, "width": width}
230
+
231
+ def draw_model_configs(model_paths, model_id_with_origin_paths, extra_inputs, fp8_models, offload_models):
232
+ model_id_with_origin_paths = draw_parameter(model_id_with_origin_paths)
233
+ model_paths = draw_parameter(model_paths)
234
+ extra_inputs = draw_parameter(extra_inputs)
235
+ fp8_models = draw_parameter(fp8_models)
236
+ offload_models = draw_parameter(offload_models)
237
+ params = {}
238
+ if model_paths is not None: params["model_paths"] = model_paths
239
+ if model_id_with_origin_paths is not None: params["model_id_with_origin_paths"] = model_id_with_origin_paths
240
+ if extra_inputs is not None: params["extra_inputs"] = extra_inputs
241
+ if fp8_models is not None: params["fp8_models"] = fp8_models
242
+ if offload_models is not None: params["offload_models"] = offload_models
243
+ return params
244
+
245
+ def draw_video_size(height, width, max_pixels, num_frames):
246
+ mode = st.selectbox("Video scaling and cropping", options=["Scale if pixel count exceeds threshold", "Resize to a fixed size and crop"], index=int(max_pixels.value is not None))
247
+ use_max_pixel = mode == "Scale if pixel count exceeds threshold"
248
+ use_height_width = mode == "Resize to a fixed size and crop"
249
+ col1, col2 = st.columns(2)
250
+ with col1:
251
+ with st.container(border=True):
252
+ max_pixels = draw_parameter(max_pixels, disabled=not use_max_pixel)
253
+ with col2:
254
+ with st.container(border=True):
255
+ height = draw_parameter(height, disabled=not use_height_width)
256
+ width = draw_parameter(width, disabled=not use_height_width)
257
+ num_frames = draw_parameter(num_frames)
258
+ if use_max_pixel:
259
+ return {"max_pixels": max_pixels, "num_frames": num_frames}
260
+ else:
261
+ return {"height": height, "width": width, "num_frames": num_frames}
262
+
263
+ def draw_training_configs(learning_rate, num_epochs, trainable_models, find_unused_parameters, weight_decay, task):
264
+ learning_rate = draw_parameter(learning_rate)
265
+ num_epochs = draw_parameter(num_epochs)
266
+ trainable_models = draw_parameter(trainable_models)
267
+ weight_decay = draw_parameter(weight_decay)
268
+ task = draw_parameter(task)
269
+ find_unused_parameters = draw_parameter(find_unused_parameters)
270
+ params = {
271
+ "task": task,
272
+ "find_unused_parameters": find_unused_parameters,
273
+ "num_epochs": num_epochs,
274
+ "learning_rate": learning_rate,
275
+ }
276
+ if weight_decay != 0.01: params["weight_decay"] = weight_decay
277
+ if trainable_models is not None: params["trainable_models"] = trainable_models
278
+ return params
279
+
280
+ def draw_output_configs(output_path, remove_prefix_in_ckpt, save_steps):
281
+ output_path = draw_parameter(output_path)
282
+ remove_prefix_in_ckpt = draw_parameter(remove_prefix_in_ckpt)
283
+ save_steps = draw_parameter(save_steps)
284
+ params = {
285
+ "output_path": output_path,
286
+ "remove_prefix_in_ckpt": remove_prefix_in_ckpt,
287
+ }
288
+ if save_steps is not None: params["save_steps"] = save_steps
289
+ return params
290
+
291
+ def draw_lora_configs(lora_base_model, lora_target_modules, lora_rank, lora_checkpoint, preset_lora_path, preset_lora_model):
292
+ with st.container(border=True):
293
+ train_lora = st.checkbox("Train LoRA", value=lora_base_model is not None)
294
+ lora_base_model = draw_parameter(lora_base_model, check_enable=False, disabled=not train_lora)
295
+ lora_target_modules = draw_parameter(lora_target_modules, check_enable=False, disabled=not train_lora)
296
+ lora_rank = draw_parameter(lora_rank, check_enable=False, disabled=not train_lora)
297
+ lora_checkpoint = draw_parameter(lora_checkpoint, check_enable=False, disabled=not train_lora)
298
+ preset_lora_path = draw_parameter(preset_lora_path)
299
+ preset_lora_model = draw_parameter(preset_lora_model)
300
+ params = {}
301
+ if train_lora:
302
+ if lora_base_model is not None: params["lora_base_model"] = lora_base_model
303
+ if lora_target_modules is not None: params["lora_target_modules"] = lora_target_modules
304
+ if lora_rank is not None: params["lora_rank"] = lora_rank
305
+ if lora_checkpoint is not None: params["lora_checkpoint"] = lora_checkpoint
306
+ if preset_lora_path is not None: params["preset_lora_path"] = preset_lora_path
307
+ if preset_lora_model is not None: params["preset_lora_model"] = preset_lora_model
308
+ return params
309
+
310
+ def draw_gradient_configs(use_gradient_checkpointing, use_gradient_checkpointing_offload, gradient_accumulation_steps):
311
+ use_gradient_checkpointing = draw_parameter(use_gradient_checkpointing)
312
+ use_gradient_checkpointing_offload = draw_parameter(use_gradient_checkpointing_offload)
313
+ gradient_accumulation_steps = draw_parameter(gradient_accumulation_steps)
314
+ params = {
315
+ "use_gradient_checkpointing": use_gradient_checkpointing,
316
+ "use_gradient_checkpointing_offload": use_gradient_checkpointing_offload,
317
+ }
318
+ if gradient_accumulation_steps != 1:
319
+ params["gradient_accumulation_steps"] = gradient_accumulation_steps
320
+ return params
321
+
322
+ def draw_template_model_configs(template_model_id_or_path, enable_lora_hot_loading):
323
+ template_model_id_or_path = draw_parameter(template_model_id_or_path)
324
+ enable_lora_hot_loading = draw_parameter(enable_lora_hot_loading)
325
+ params = {"enable_lora_hot_loading": enable_lora_hot_loading}
326
+ if template_model_id_or_path is not None: params["template_model_id_or_path"] = template_model_id_or_path
327
+ return params
328
+
329
+ def match_ui_groups(params, ui_groups):
330
+ param_names = [param.name for param in params]
331
+ for ui_group in ui_groups:
332
+ if sum([name in param_names for name in ui_group["params"]]) == len(ui_group["params"]):
333
+ group_params = {param.name: param for param in params if param.name in ui_group["params"]}
334
+ other_params = [param for param in params if param.name not in ui_group["params"]]
335
+ return group_params, other_params, ui_group
336
+ return {}, params, None
337
+
338
+ def draw_other_params(params):
339
+ results = {}
340
+ for param in params:
341
+ results[param.name] = draw_parameter(param)
342
+ return results
343
+
344
+ def draw_all_params(params, ui_groups):
345
+ matched_ui_groups = []
346
+ while True:
347
+ group_params, other_params, ui_group = match_ui_groups(params, ui_groups)
348
+ if len(group_params) == 0:
349
+ break
350
+ matched_ui_groups.append((ui_group, group_params))
351
+ params = other_params
352
+ tabs = st.tabs([ui_group["name"] for ui_group, _ in matched_ui_groups] + ["Others"])
353
+ inputs = {}
354
+ for tab, (ui_group, group_params) in zip(tabs, matched_ui_groups):
355
+ with tab:
356
+ inputs.update(ui_group["fn"](**group_params))
357
+ with tabs[-1]:
358
+ inputs.update(draw_other_params(params))
359
+ return inputs
360
+
361
+ def generate_training_script(script_path, inputs):
362
+ cmd = f"accelerate launch {script_path}"
363
+ for name, value in inputs.items():
364
+ if value is not None:
365
+ if isinstance(value, bool):
366
+ if value == True:
367
+ cmd = f"{cmd} \\\n --{name}"
368
+ elif isinstance(value, str):
369
+ cmd = f"{cmd} \\\n --{name} \"{value}\""
370
+ else:
371
+ cmd = f"{cmd} \\\n --{name} {value}"
372
+ return cmd
373
+
374
+ ui_groups = [
375
+ {
376
+ "name": "Dataset",
377
+ "params": ("dataset_base_path", "dataset_metadata_path", "dataset_repeat", "dataset_num_workers", "data_file_keys"),
378
+ "fn": draw_dataset_configs,
379
+ },
380
+ {
381
+ "name": "Video Size",
382
+ "params": ("height", "width", "max_pixels", "num_frames"),
383
+ "fn": draw_video_size,
384
+ },
385
+ {
386
+ "name": "Image Size",
387
+ "params": ("height", "width", "max_pixels"),
388
+ "fn": draw_image_size,
389
+ },
390
+ {
391
+ "name": "Model",
392
+ "params": ("model_paths", "model_id_with_origin_paths", "extra_inputs", "fp8_models", "offload_models"),
393
+ "fn": draw_model_configs,
394
+ },
395
+ {
396
+ "name": "Training",
397
+ "params": ("learning_rate", "num_epochs", "trainable_models", "find_unused_parameters", "weight_decay", "task"),
398
+ "fn": draw_training_configs,
399
+ },
400
+ {
401
+ "name": "Output",
402
+ "params": ("output_path", "remove_prefix_in_ckpt", "save_steps"),
403
+ "fn": draw_output_configs,
404
+ },
405
+ {
406
+ "name": "LoRA",
407
+ "params": ("lora_base_model", "lora_target_modules", "lora_rank", "lora_checkpoint", "preset_lora_path", "preset_lora_model"),
408
+ "fn": draw_lora_configs,
409
+ },
410
+ {
411
+ "name": "Gradient",
412
+ "params": ("use_gradient_checkpointing", "use_gradient_checkpointing_offload", "gradient_accumulation_steps"),
413
+ "fn": draw_gradient_configs,
414
+ },
415
+ {
416
+ "name": "Templates",
417
+ "params": ("template_model_id_or_path", "enable_lora_hot_loading"),
418
+ "fn": draw_template_model_configs,
419
+ },
420
+ ]
421
+
422
+ def launch_webui():
423
+ input_col, output_col = st.columns(2)
424
+ with input_col:
425
+ if "available_training_scripts" not in st.session_state:
426
+ st.session_state["available_training_scripts"] = parse_available_training_scripts("examples")
427
+ with st.container(border=True):
428
+ script_path = st.selectbox(label="Script path", options=st.session_state["available_training_scripts"].values(), index=0)
429
+ example_path = st.selectbox(label="Example path (Optional)", options=["None"] + parse_available_examples(script_path), index=0)
430
+ if st.button("Step 1: Parse Training Script", type="primary"):
431
+ st.session_state["script_path"] = script_path
432
+
433
+ if "script_path" not in st.session_state:
434
+ return
435
+ with st.spinner("Fetching input parameters", show_time=False):
436
+ parser = parse_parser(script_path)
437
+ parser = parser()
438
+ params = parse_parser_actions(parser, example_path)
439
+ inputs = draw_all_params(params, ui_groups)
440
+ with output_col:
441
+ if st.button("Step 2: Generate training script", type="primary"):
442
+ script = generate_training_script(script_path, inputs)
443
+ st.code(script, language="shell")
444
+
445
+ launch_webui()
examples/ernie_image/model_inference/ERNIE-Image-Turbo.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffsynth.pipelines.ernie_image import ErnieImagePipeline, ModelConfig
2
+ import torch
3
+
4
+ pipe = ErnieImagePipeline.from_pretrained(
5
+ torch_dtype=torch.bfloat16,
6
+ device='cuda',
7
+ model_configs=[
8
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image-Turbo", origin_file_pattern="transformer/diffusion_pytorch_model*.safetensors"),
9
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="text_encoder/model.safetensors"),
10
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="vae/diffusion_pytorch_model.safetensors"),
11
+ ],
12
+ tokenizer_config=ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="tokenizer/"),
13
+ )
14
+
15
+ image = pipe(
16
+ prompt="一只黑白相间的中华田园犬",
17
+ negative_prompt="",
18
+ height=1024,
19
+ width=1024,
20
+ seed=42,
21
+ num_inference_steps=8,
22
+ cfg_scale=1.0,
23
+ sigma_shift=4.0,
24
+ )
25
+ image.save("output_turbo.jpg")
examples/ernie_image/model_inference/ERNIE-Image.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffsynth.pipelines.ernie_image import ErnieImagePipeline, ModelConfig
2
+ import torch
3
+
4
+ pipe = ErnieImagePipeline.from_pretrained(
5
+ torch_dtype=torch.bfloat16,
6
+ device='cuda',
7
+ model_configs=[
8
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="transformer/diffusion_pytorch_model*.safetensors"),
9
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="text_encoder/model.safetensors"),
10
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="vae/diffusion_pytorch_model.safetensors"),
11
+ ],
12
+ tokenizer_config=ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="tokenizer/"),
13
+ )
14
+
15
+ image = pipe(
16
+ prompt="一只黑白相间的中华田园犬",
17
+ negative_prompt="",
18
+ height=1024,
19
+ width=1024,
20
+ seed=42,
21
+ num_inference_steps=50,
22
+ cfg_scale=4.0,
23
+ )
24
+ image.save("output.jpg")
examples/ernie_image/model_inference_low_vram/ERNIE-Image-Turbo.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffsynth.pipelines.ernie_image import ErnieImagePipeline, ModelConfig
2
+ import torch
3
+
4
+ vram_config = {
5
+ "offload_dtype": torch.bfloat16,
6
+ "offload_device": "cpu",
7
+ "onload_dtype": torch.bfloat16,
8
+ "onload_device": "cpu",
9
+ "preparing_dtype": torch.bfloat16,
10
+ "preparing_device": "cuda",
11
+ "computation_dtype": torch.bfloat16,
12
+ "computation_device": "cuda",
13
+ }
14
+
15
+ pipe = ErnieImagePipeline.from_pretrained(
16
+ torch_dtype=torch.bfloat16,
17
+ device='cuda',
18
+ model_configs=[
19
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image-Turbo", origin_file_pattern="transformer/diffusion_pytorch_model*.safetensors", **vram_config),
20
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
21
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="vae/diffusion_pytorch_model.safetensors", **vram_config),
22
+ ],
23
+ tokenizer_config=ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="tokenizer/"),
24
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
25
+ )
26
+
27
+ image = pipe(
28
+ prompt="一只黑白相间的中华田园犬",
29
+ negative_prompt="",
30
+ height=1024,
31
+ width=1024,
32
+ seed=42,
33
+ num_inference_steps=8,
34
+ cfg_scale=1.0,
35
+ sigma_shift=4.0,
36
+ )
37
+ image.save("output_turbo.jpg")
examples/ernie_image/model_inference_low_vram/ERNIE-Image.py ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffsynth.pipelines.ernie_image import ErnieImagePipeline, ModelConfig
2
+ import torch
3
+
4
+ vram_config = {
5
+ "offload_dtype": torch.bfloat16,
6
+ "offload_device": "cpu",
7
+ "onload_dtype": torch.bfloat16,
8
+ "onload_device": "cpu",
9
+ "preparing_dtype": torch.bfloat16,
10
+ "preparing_device": "cuda",
11
+ "computation_dtype": torch.bfloat16,
12
+ "computation_device": "cuda",
13
+ }
14
+
15
+ pipe = ErnieImagePipeline.from_pretrained(
16
+ torch_dtype=torch.bfloat16,
17
+ device='cuda',
18
+ model_configs=[
19
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="transformer/diffusion_pytorch_model*.safetensors", **vram_config),
20
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
21
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="vae/diffusion_pytorch_model.safetensors", **vram_config),
22
+ ],
23
+ tokenizer_config=ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="tokenizer/"),
24
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
25
+ )
26
+
27
+ image = pipe(
28
+ prompt="一只黑白相间的中华田园犬",
29
+ negative_prompt="",
30
+ height=1024,
31
+ width=1024,
32
+ seed=42,
33
+ num_inference_steps=50,
34
+ cfg_scale=4.0,
35
+ )
36
+ image.save("output.jpg")
examples/ernie_image/model_training/full/ERNIE-Image.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dataset: data/diffsynth_example_dataset/ernie_image/Ernie-Image-T2I/
2
+
3
+ accelerate launch --config_file examples/ernie_image/model_training/full/accelerate_config_zero3.yaml \
4
+ examples/ernie_image/model_training/train.py \
5
+ --dataset_base_path data/diffsynth_example_dataset/ernie_image/Ernie-Image-T2I \
6
+ --dataset_metadata_path data/diffsynth_example_dataset/ernie_image/Ernie-Image-T2I/metadata.csv \
7
+ --max_pixels 1048576 \
8
+ --dataset_repeat 50 \
9
+ --model_id_with_origin_paths "PaddlePaddle/ERNIE-Image:transformer/diffusion_pytorch_model*.safetensors,PaddlePaddle/ERNIE-Image:text_encoder/model.safetensors,PaddlePaddle/ERNIE-Image:vae/diffusion_pytorch_model.safetensors" \
10
+ --learning_rate 1e-5 \
11
+ --num_epochs 2 \
12
+ --remove_prefix_in_ckpt "pipe.dit." \
13
+ --output_path "./models/train/Ernie-Image-T2I_full" \
14
+ --trainable_models "dit" \
15
+ --use_gradient_checkpointing \
16
+ --dataset_num_workers 8 \
17
+ --find_unused_parameters
examples/ernie_image/model_training/full/accelerate_config_zero3.yaml ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ compute_environment: LOCAL_MACHINE
2
+ debug: false
3
+ deepspeed_config:
4
+ gradient_accumulation_steps: 1
5
+ offload_optimizer_device: none
6
+ offload_param_device: none
7
+ zero3_init_flag: true
8
+ zero3_save_16bit_model: true
9
+ zero_stage: 3
10
+ distributed_type: DEEPSPEED
11
+ downcast_bf16: 'no'
12
+ enable_cpu_affinity: false
13
+ machine_rank: 0
14
+ main_training_function: main
15
+ mixed_precision: bf16
16
+ num_machines: 1
17
+ num_processes: 8
18
+ rdzv_backend: static
19
+ same_network: true
20
+ tpu_env: []
21
+ tpu_use_cluster: false
22
+ tpu_use_sudo: false
23
+ use_cpu: false
examples/ernie_image/model_training/lora/ERNIE-Image.sh ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Dataset: data/diffsynth_example_dataset/ernie_image/Ernie-Image-T2I/
2
+ # Download: modelscope download --dataset DiffSynth-Studio/diffsynth_example_dataset --include "ernie_image/Ernie-Image-T2I/*" --local_dir ./data/diffsynth_example_dataset
3
+
4
+ accelerate launch examples/ernie_image/model_training/train.py \
5
+ --dataset_base_path data/diffsynth_example_dataset/ernie_image/Ernie-Image-T2I \
6
+ --dataset_metadata_path data/diffsynth_example_dataset/ernie_image/Ernie-Image-T2I/metadata.csv \
7
+ --max_pixels 1048576 \
8
+ --dataset_repeat 50 \
9
+ --model_id_with_origin_paths "PaddlePaddle/ERNIE-Image:transformer/diffusion_pytorch_model*.safetensors,PaddlePaddle/ERNIE-Image:text_encoder/model.safetensors,PaddlePaddle/ERNIE-Image:vae/diffusion_pytorch_model.safetensors" \
10
+ --learning_rate 1e-4 \
11
+ --num_epochs 5 \
12
+ --remove_prefix_in_ckpt "pipe.dit." \
13
+ --output_path "./models/train/Ernie-Image-T2I_lora" \
14
+ --lora_base_model "dit" \
15
+ --lora_target_modules "to_q,to_k,to_v,to_out.0" \
16
+ --lora_rank 32 \
17
+ --use_gradient_checkpointing \
18
+ --dataset_num_workers 8 \
19
+ --find_unused_parameters
examples/ernie_image/model_training/special/split_training/ERNIE-Image.sh ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ modelscope download --dataset DiffSynth-Studio/diffsynth_example_dataset --include "ernie_image/Ernie-Image-T2I/*" --local_dir ./data/diffsynth_example_dataset
2
+
3
+ # Stage 1: cache deterministic preprocessing outputs.
4
+ accelerate launch examples/ernie_image/model_training/train.py \
5
+ --dataset_base_path data/diffsynth_example_dataset/ernie_image/Ernie-Image-T2I \
6
+ --dataset_metadata_path data/diffsynth_example_dataset/ernie_image/Ernie-Image-T2I/metadata.csv \
7
+ --max_pixels 1048576 \
8
+ --dataset_repeat 1 \
9
+ --model_id_with_origin_paths 'PaddlePaddle/ERNIE-Image:transformer/diffusion_pytorch_model*.safetensors,PaddlePaddle/ERNIE-Image:text_encoder/model.safetensors,PaddlePaddle/ERNIE-Image:vae/diffusion_pytorch_model.safetensors' \
10
+ --learning_rate 1e-4 \
11
+ --num_epochs 5 \
12
+ --remove_prefix_in_ckpt pipe.dit. \
13
+ --output_path ./models/train/Ernie-Image-T2I_split_cache \
14
+ --lora_base_model dit \
15
+ --lora_target_modules to_q,to_k,to_v,to_out.0 \
16
+ --lora_rank 32 \
17
+ --use_gradient_checkpointing \
18
+ --dataset_num_workers 8 \
19
+ --find_unused_parameters \
20
+ --offload_models 'PaddlePaddle/ERNIE-Image:transformer/diffusion_pytorch_model*.safetensors' \
21
+ --task sft:data_process
22
+
23
+ # Stage 2: train LoRA from the cached dataset.
24
+ accelerate launch examples/ernie_image/model_training/train.py \
25
+ --dataset_base_path ./models/train/Ernie-Image-T2I_split_cache \
26
+ --max_pixels 1048576 \
27
+ --dataset_repeat 50 \
28
+ --model_id_with_origin_paths 'PaddlePaddle/ERNIE-Image:transformer/diffusion_pytorch_model*.safetensors,PaddlePaddle/ERNIE-Image:text_encoder/model.safetensors,PaddlePaddle/ERNIE-Image:vae/diffusion_pytorch_model.safetensors' \
29
+ --learning_rate 1e-4 \
30
+ --num_epochs 5 \
31
+ --remove_prefix_in_ckpt pipe.dit. \
32
+ --output_path ./models/train/Ernie-Image-T2I_split \
33
+ --lora_base_model dit \
34
+ --lora_target_modules to_q,to_k,to_v,to_out.0 \
35
+ --lora_rank 32 \
36
+ --use_gradient_checkpointing \
37
+ --dataset_num_workers 8 \
38
+ --find_unused_parameters \
39
+ --offload_models PaddlePaddle/ERNIE-Image:text_encoder/model.safetensors,PaddlePaddle/ERNIE-Image:vae/diffusion_pytorch_model.safetensors \
40
+ --task sft:train
examples/ernie_image/model_training/special/split_training/validate.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.ernie_image import ErnieImagePipeline, ModelConfig
3
+ from diffsynth.core.loader.file import load_state_dict
4
+
5
+ pipe = ErnieImagePipeline.from_pretrained(
6
+ torch_dtype=torch.bfloat16,
7
+ device="cuda",
8
+ model_configs=[
9
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="transformer/diffusion_pytorch_model*.safetensors"),
10
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="text_encoder/model.safetensors"),
11
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="vae/diffusion_pytorch_model.safetensors"),
12
+ ],
13
+ )
14
+
15
+ lora_state_dict = load_state_dict('./models/train/Ernie-Image-T2I_split/epoch-4.safetensors', torch_dtype=torch.bfloat16, device="cuda")
16
+ pipe.load_lora(pipe.dit, state_dict=lora_state_dict, alpha=1.0)
17
+
18
+ image = pipe(
19
+ prompt="a professional photo of a cute dog",
20
+ seed=0,
21
+ num_inference_steps=50,
22
+ cfg_scale=4.0,
23
+ )
24
+ image.save('split_training_ERNIE-Image.jpg')
25
+ print("LoRA validation image saved to image_lora.jpg")
examples/ernie_image/model_training/train.py ADDED
@@ -0,0 +1,141 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch, os, argparse, accelerate
2
+ from diffsynth.core import UnifiedDataset
3
+ from diffsynth.pipelines.ernie_image import ErnieImagePipeline, ModelConfig
4
+ from diffsynth.diffusion import *
5
+ from diffsynth.core.data.operators import *
6
+ os.environ["TOKENIZERS_PARALLELISM"] = "false"
7
+
8
+
9
+ class ErnieImageTrainingModule(DiffusionTrainingModule):
10
+ def __init__(
11
+ self,
12
+ model_paths=None, model_id_with_origin_paths=None,
13
+ tokenizer_path=None,
14
+ trainable_models=None,
15
+ lora_base_model=None, lora_target_modules="", lora_rank=32, lora_checkpoint=None,
16
+ preset_lora_path=None, preset_lora_model=None,
17
+ use_gradient_checkpointing=True,
18
+ use_gradient_checkpointing_offload=False,
19
+ extra_inputs=None,
20
+ fp8_models=None,
21
+ offload_models=None,
22
+ quant_options=None,
23
+ resume_from_checkpoint=None, remove_prefix_in_ckpt=None,
24
+ device="cpu",
25
+ task="sft",
26
+ ):
27
+ super().__init__()
28
+ # Load models
29
+ model_configs = self.parse_model_configs(model_paths, model_id_with_origin_paths, fp8_models=fp8_models, offload_models=offload_models, quant_options=quant_options, device=device)
30
+ tokenizer_config = ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="tokenizer/") if tokenizer_path is None else ModelConfig(tokenizer_path)
31
+ self.pipe = ErnieImagePipeline.from_pretrained(torch_dtype=torch.bfloat16, device=device, model_configs=model_configs, tokenizer_config=tokenizer_config)
32
+ self.pipe = self.split_pipeline_units(task, self.pipe, trainable_models, lora_base_model)
33
+ self.resume_from_checkpoint(resume_from_checkpoint, remove_prefix_in_ckpt)
34
+
35
+ # Training mode
36
+ self.switch_pipe_to_training_mode(
37
+ self.pipe, trainable_models,
38
+ lora_base_model, lora_target_modules, lora_rank, lora_checkpoint,
39
+ preset_lora_path, preset_lora_model,
40
+ task=task,
41
+ )
42
+
43
+ # Other configs
44
+ self.use_gradient_checkpointing = use_gradient_checkpointing
45
+ self.use_gradient_checkpointing_offload = use_gradient_checkpointing_offload
46
+ self.extra_inputs = extra_inputs.split(",") if extra_inputs is not None else []
47
+ self.task = task
48
+ self.task_to_loss = {
49
+ "sft:data_process": lambda pipe, inputs_shared, inputs_posi, inputs_nega: (inputs_shared, inputs_posi, inputs_nega),
50
+ "sft": lambda pipe, inputs_shared, inputs_posi, inputs_nega: FlowMatchSFTLoss(pipe, **inputs_shared, **inputs_posi),
51
+ "sft:train": lambda pipe, inputs_shared, inputs_posi, inputs_nega: FlowMatchSFTLoss(pipe, **inputs_shared, **inputs_posi),
52
+ }
53
+
54
+ def get_pipeline_inputs(self, data):
55
+ inputs_posi = {"prompt": data["prompt"]}
56
+ inputs_nega = {"negative_prompt": ""}
57
+ inputs_shared = {
58
+ "input_image": data["image"],
59
+ "height": data["image"].size[1],
60
+ "width": data["image"].size[0],
61
+ "cfg_scale": 1,
62
+ "rand_device": self.pipe.device,
63
+ "use_gradient_checkpointing": self.use_gradient_checkpointing,
64
+ "use_gradient_checkpointing_offload": self.use_gradient_checkpointing_offload,
65
+ }
66
+ inputs_shared = self.parse_extra_inputs(data, self.extra_inputs, inputs_shared)
67
+ return inputs_shared, inputs_posi, inputs_nega
68
+
69
+ def forward(self, data, inputs=None):
70
+ if inputs is None:
71
+ inputs = self.get_pipeline_inputs(data)
72
+ inputs = self.transfer_data_to_device(inputs, self.pipe.device, self.pipe.torch_dtype)
73
+ for unit in self.pipe.units:
74
+ inputs = self.pipe.unit_runner(unit, self.pipe, *inputs)
75
+ loss = self.task_to_loss[self.task](self.pipe, *inputs)
76
+ return loss
77
+
78
+
79
+ def ernie_image_parser():
80
+ parser = argparse.ArgumentParser(description="ERNIE-Image training.")
81
+ parser = add_general_config(parser)
82
+ parser = add_image_size_config(parser)
83
+ parser.add_argument("--tokenizer_path", type=str, default=None, help="Path to tokenizer.")
84
+ return parser
85
+
86
+
87
+ if __name__ == "__main__":
88
+ parser = ernie_image_parser()
89
+ args = parser.parse_args()
90
+ accelerator = accelerate.Accelerator(
91
+ gradient_accumulation_steps=args.gradient_accumulation_steps,
92
+ kwargs_handlers=[accelerate.DistributedDataParallelKwargs(find_unused_parameters=args.find_unused_parameters)],
93
+ )
94
+ dataset = UnifiedDataset(
95
+ base_path=args.dataset_base_path,
96
+ metadata_path=args.dataset_metadata_path,
97
+ repeat=args.dataset_repeat,
98
+ data_file_keys=args.data_file_keys.split(","),
99
+ main_data_operator=lambda x: x,
100
+ special_operator_map={
101
+ "image": ToAbsolutePath(args.dataset_base_path) >> LoadImage() >> ImageCropAndResize(args.height, args.width, args.max_pixels, 16, 16),
102
+ },
103
+ )
104
+ model = ErnieImageTrainingModule(
105
+ model_paths=args.model_paths,
106
+ model_id_with_origin_paths=args.model_id_with_origin_paths,
107
+ tokenizer_path=args.tokenizer_path,
108
+ trainable_models=args.trainable_models,
109
+ lora_base_model=args.lora_base_model,
110
+ lora_target_modules=args.lora_target_modules,
111
+ lora_rank=args.lora_rank,
112
+ lora_checkpoint=args.lora_checkpoint,
113
+ preset_lora_path=args.preset_lora_path,
114
+ preset_lora_model=args.preset_lora_model,
115
+ use_gradient_checkpointing=args.use_gradient_checkpointing,
116
+ use_gradient_checkpointing_offload=args.use_gradient_checkpointing_offload,
117
+ extra_inputs=args.extra_inputs,
118
+ fp8_models=args.fp8_models,
119
+ offload_models=args.offload_models,
120
+ quant_options=args.quant_options,
121
+ resume_from_checkpoint=args.resume_from_checkpoint,
122
+ remove_prefix_in_ckpt=args.remove_prefix_in_ckpt,
123
+ task=args.task,
124
+ device="cpu" if args.enable_model_cpu_offload else accelerator.device,
125
+ )
126
+ model_logger = ModelLogger(
127
+ args.output_path,
128
+ remove_prefix_in_ckpt=args.remove_prefix_in_ckpt,
129
+ enable_tensorboard_log=args.enable_tensorboard_log,
130
+ enable_swanlab_log=args.enable_swanlab_log,
131
+ swanlab_project=args.swanlab_project,
132
+ enable_wandb_log=args.enable_wandb_log,
133
+ wandb_project=args.wandb_project,
134
+ enable_csv_log=args.enable_csv_log,
135
+ )
136
+ launcher_map = {
137
+ "sft:data_process": launch_data_process_task,
138
+ "sft": launch_training_task,
139
+ "sft:train": launch_training_task,
140
+ }
141
+ launcher_map[args.task](accelerator, dataset, model, model_logger, args=args)
examples/ernie_image/model_training/validate_full/ERNIE-Image.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.ernie_image import ErnieImagePipeline, ModelConfig
3
+ from diffsynth.core import load_state_dict
4
+
5
+ pipe = ErnieImagePipeline.from_pretrained(
6
+ torch_dtype=torch.bfloat16,
7
+ device="cuda",
8
+ model_configs=[
9
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="transformer/diffusion_pytorch_model*.safetensors"),
10
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="text_encoder/model.safetensors"),
11
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="vae/diffusion_pytorch_model.safetensors"),
12
+ ],
13
+ )
14
+
15
+ state_dict = load_state_dict("./models/train/Ernie-Image-T2I_full/epoch-1.safetensors")
16
+ pipe.dit.load_state_dict(state_dict)
17
+
18
+ image = pipe(
19
+ prompt="a professional photo of a cute dog",
20
+ seed=0,
21
+ num_inference_steps=50,
22
+ cfg_scale=4.0,
23
+ )
24
+ image.save("image_full.jpg")
25
+ print("Full validation image saved to image_full.jpg")
examples/ernie_image/model_training/validate_lora/ERNIE-Image.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.ernie_image import ErnieImagePipeline, ModelConfig
3
+ from diffsynth.core.loader.file import load_state_dict
4
+
5
+ pipe = ErnieImagePipeline.from_pretrained(
6
+ torch_dtype=torch.bfloat16,
7
+ device="cuda",
8
+ model_configs=[
9
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="transformer/diffusion_pytorch_model*.safetensors"),
10
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="text_encoder/model.safetensors"),
11
+ ModelConfig(model_id="PaddlePaddle/ERNIE-Image", origin_file_pattern="vae/diffusion_pytorch_model.safetensors"),
12
+ ],
13
+ )
14
+
15
+ lora_state_dict = load_state_dict("./models/train/Ernie-Image-T2I_lora/epoch-4.safetensors", torch_dtype=torch.bfloat16, device="cuda")
16
+ pipe.load_lora(pipe.dit, state_dict=lora_state_dict, alpha=1.0)
17
+
18
+ image = pipe(
19
+ prompt="a professional photo of a cute dog",
20
+ seed=0,
21
+ num_inference_steps=50,
22
+ cfg_scale=4.0,
23
+ )
24
+ image.save("image_lora.jpg")
25
+ print("LoRA validation image saved to image_lora.jpg")
examples/flux/README.md ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ English Document: https://diffsynth-studio-doc.readthedocs.io/en/latest/Model_Details/FLUX.html
2
+
3
+ 中文文档:https://diffsynth-studio-doc.readthedocs.io/zh-cn/latest/Model_Details/FLUX.html
examples/flux/model_inference/FLEX.2-preview.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+ from diffsynth.utils.controlnet import Annotator
4
+ import numpy as np
5
+ from PIL import Image
6
+
7
+
8
+ pipe = FluxImagePipeline.from_pretrained(
9
+ torch_dtype=torch.bfloat16,
10
+ device="cuda",
11
+ model_configs=[
12
+ ModelConfig(model_id="ostris/Flex.2-preview", origin_file_pattern="Flex.2-preview.safetensors"),
13
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
14
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
15
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
16
+ ],
17
+ )
18
+
19
+ image = pipe(
20
+ prompt="portrait of a beautiful Asian girl, long hair, red t-shirt, sunshine, beach",
21
+ num_inference_steps=50, embedded_guidance=3.5,
22
+ seed=0
23
+ )
24
+ image.save("image_1.jpg")
25
+
26
+ mask = np.zeros((1024, 1024, 3), dtype=np.uint8)
27
+ mask[200:400, 400:700] = 255
28
+ mask = Image.fromarray(mask)
29
+ mask.save("image_mask.jpg")
30
+
31
+ inpaint_image = image
32
+
33
+ image = pipe(
34
+ prompt="portrait of a beautiful Asian girl with sunglasses, long hair, red t-shirt, sunshine, beach",
35
+ num_inference_steps=50, embedded_guidance=3.5,
36
+ flex_inpaint_image=inpaint_image, flex_inpaint_mask=mask,
37
+ seed=4
38
+ )
39
+ image.save("image_2.jpg")
40
+
41
+ control_image = Annotator("canny")(image)
42
+ control_image.save("image_control.jpg")
43
+
44
+ image = pipe(
45
+ prompt="portrait of a beautiful Asian girl with sunglasses, long hair, yellow t-shirt, sunshine, beach",
46
+ num_inference_steps=50, embedded_guidance=3.5,
47
+ flex_control_image=control_image,
48
+ seed=4
49
+ )
50
+ image.save("image_3.jpg")
examples/flux/model_inference/FLUX.1-Fill-dev.py ADDED
@@ -0,0 +1,29 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+ from PIL import Image
4
+ from modelscope import dataset_snapshot_download
5
+
6
+
7
+ pipe = FluxImagePipeline.from_pretrained(
8
+ torch_dtype=torch.bfloat16,
9
+ device="cuda",
10
+ model_configs=[
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="flux1-fill-dev.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="text_encoder/model.safetensors"),
13
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
14
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="ae.safetensors"),
15
+ ],
16
+ )
17
+
18
+ dataset_snapshot_download(
19
+ dataset_id="HuanJue/example_dataset",
20
+ local_dir="./",
21
+ allow_file_pattern=f"FLUX.1-Fill-dev/*",
22
+ )
23
+
24
+ flux_fill_image = Image.open("FLUX.1-Fill-dev/cup.png").convert("RGB")
25
+ flux_fill_mask = Image.open("FLUX.1-Fill-dev/cup_mask.png").convert("L")
26
+ prompt = "a white paper cup"
27
+ image = pipe(prompt=prompt, flux_fill_image=flux_fill_image, flux_fill_mask=flux_fill_mask, height=1632, width=1232, seed=0, embedded_guidance=30.0, num_inference_steps=50)
28
+
29
+ image.save("image_FLUX.1-Fill-dev.jpg")
examples/flux/model_inference/FLUX.1-Kontext-dev.py ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+ from PIL import Image
4
+
5
+
6
+ pipe = FluxImagePipeline.from_pretrained(
7
+ torch_dtype=torch.bfloat16,
8
+ device="cuda",
9
+ model_configs=[
10
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Kontext-dev", origin_file_pattern="flux1-kontext-dev.safetensors"),
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
13
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
14
+ ],
15
+ )
16
+
17
+ image_1 = pipe(
18
+ prompt="a beautiful Asian long-haired female college student.",
19
+ embedded_guidance=2.5,
20
+ seed=1,
21
+ )
22
+ image_1.save("image_1.jpg")
23
+
24
+ image_2 = pipe(
25
+ prompt="transform the style to anime style.",
26
+ kontext_images=image_1,
27
+ embedded_guidance=2.5,
28
+ seed=2,
29
+ )
30
+ image_2.save("image_2.jpg")
31
+
32
+ image_3 = pipe(
33
+ prompt="let her smile.",
34
+ kontext_images=image_1,
35
+ embedded_guidance=2.5,
36
+ seed=3,
37
+ )
38
+ image_3.save("image_3.jpg")
39
+
40
+ image_4 = pipe(
41
+ prompt="let the girl play basketball.",
42
+ kontext_images=image_1,
43
+ embedded_guidance=2.5,
44
+ seed=4,
45
+ )
46
+ image_4.save("image_4.jpg")
47
+
48
+ image_5 = pipe(
49
+ prompt="move the girl to a park, let her sit on a chair.",
50
+ kontext_images=image_1,
51
+ embedded_guidance=2.5,
52
+ seed=5,
53
+ )
54
+ image_5.save("image_5.jpg")
examples/flux/model_inference/FLUX.1-Krea-dev.py ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+
4
+
5
+ pipe = FluxImagePipeline.from_pretrained(
6
+ torch_dtype=torch.bfloat16,
7
+ device="cuda",
8
+ model_configs=[
9
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Krea-dev", origin_file_pattern="flux1-krea-dev.safetensors"),
10
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
13
+ ],
14
+ )
15
+
16
+ prompt = "An beautiful woman is riding a bicycle in a park, wearing a red dress"
17
+ negative_prompt = "worst quality, low quality, monochrome, zombie, interlocked fingers, Aissist, cleavage, nsfw,"
18
+
19
+ image = pipe(prompt=prompt, seed=0, embedded_guidance=4.5)
20
+ image.save("flux_krea.jpg")
21
+
22
+ image = pipe(
23
+ prompt=prompt, negative_prompt=negative_prompt,
24
+ seed=0, cfg_scale=2, num_inference_steps=50,
25
+ embedded_guidance=4.5
26
+ )
27
+ image.save("flux_krea_cfg.jpg")
examples/flux/model_inference/FLUX.1-Redux-dev.py ADDED
@@ -0,0 +1,28 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+ from PIL import Image
4
+ from modelscope import dataset_snapshot_download
5
+
6
+ pipe = FluxImagePipeline.from_pretrained(
7
+ torch_dtype=torch.bfloat16,
8
+ device="cuda",
9
+ model_configs=[
10
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors"),
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
13
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
14
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Redux-dev", origin_file_pattern="image_encoder/model.safetensors"),
15
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Redux-dev", origin_file_pattern="image_embedder/diffusion_pytorch_model.safetensors"),
16
+ ],
17
+ )
18
+ dataset_snapshot_download(
19
+ dataset_id="HuanJue/example_dataset",
20
+ local_dir="./",
21
+ allow_file_pattern=f"FLUX.1-Redux-dev/*",
22
+ )
23
+
24
+ flux_redux_image = Image.open("FLUX.1-Redux-dev/robot.png").convert("RGB")
25
+
26
+ image = pipe(flux_redux_image=flux_redux_image, embedded_guidance=2.5, num_inference_steps=50)
27
+
28
+ image.save("image_FLUX.1-Redux-dev.jpg")
examples/flux/model_inference/FLUX.1-dev-AttriCtrl.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+
4
+
5
+ pipe = FluxImagePipeline.from_pretrained(
6
+ torch_dtype=torch.bfloat16,
7
+ device="cuda",
8
+ model_configs=[
9
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors"),
10
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
13
+ ModelConfig(model_id="DiffSynth-Studio/AttriCtrl-FLUX.1-Dev", origin_file_pattern="models/brightness.safetensors")
14
+ ],
15
+ )
16
+
17
+ for i in [0.1, 0.3, 0.5, 0.7, 0.9]:
18
+ image = pipe(prompt="a cat on the beach", seed=2, value_controller_inputs=[i])
19
+ image.save(f"value_control_{i}.jpg")
examples/flux/model_inference/FLUX.1-dev-Controlnet-Inpainting-Beta.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig, ControlNetInput
3
+ import numpy as np
4
+ from PIL import Image
5
+
6
+
7
+ pipe = FluxImagePipeline.from_pretrained(
8
+ torch_dtype=torch.bfloat16,
9
+ device="cuda",
10
+ model_configs=[
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
13
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
14
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
15
+ ModelConfig(model_id="alimama-creative/FLUX.1-dev-Controlnet-Inpainting-Beta", origin_file_pattern="diffusion_pytorch_model.safetensors"),
16
+ ],
17
+ )
18
+
19
+ image_1 = pipe(
20
+ prompt="a cat sitting on a chair",
21
+ height=1024, width=1024,
22
+ seed=8, rand_device="cuda",
23
+ )
24
+ image_1.save("image_1.jpg")
25
+
26
+ mask = np.zeros((1024, 1024, 3), dtype=np.uint8)
27
+ mask[100:350, 350: -300] = 255
28
+ mask = Image.fromarray(mask)
29
+ mask.save("mask.jpg")
30
+
31
+ image_2 = pipe(
32
+ prompt="a cat sitting on a chair, wearing sunglasses",
33
+ controlnet_inputs=[ControlNetInput(image=image_1, inpaint_mask=mask, scale=0.9)],
34
+ height=1024, width=1024,
35
+ seed=9, rand_device="cuda",
36
+ )
37
+ image_2.save("image_2.jpg")
examples/flux/model_inference/FLUX.1-dev-Controlnet-Union-alpha.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig, ControlNetInput
3
+ from diffsynth.utils.controlnet import Annotator
4
+ from modelscope import snapshot_download
5
+
6
+
7
+
8
+ snapshot_download("sd_lora/Annotators", allow_file_pattern="dpt_hybrid-midas-501f0c75.pt", local_dir="models/Annotators")
9
+ pipe = FluxImagePipeline.from_pretrained(
10
+ torch_dtype=torch.bfloat16,
11
+ device="cuda",
12
+ model_configs=[
13
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors"),
14
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
15
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
16
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
17
+ ModelConfig(model_id="InstantX/FLUX.1-dev-Controlnet-Union-alpha", origin_file_pattern="diffusion_pytorch_model.safetensors"),
18
+ ],
19
+ )
20
+
21
+ image_1 = pipe(
22
+ prompt="a beautiful Asian girl, full body, red dress, summer",
23
+ height=1024, width=1024,
24
+ seed=6, rand_device="cuda",
25
+ )
26
+ image_1.save("image_1.jpg")
27
+
28
+ image_canny = Annotator("canny")(image_1)
29
+ image_depth = Annotator("depth")(image_1)
30
+
31
+ image_2 = pipe(
32
+ prompt="a beautiful Asian girl, full body, red dress, winter",
33
+ controlnet_inputs=[
34
+ ControlNetInput(image=image_canny, scale=0.3, processor_id="canny"),
35
+ ControlNetInput(image=image_depth, scale=0.3, processor_id="depth"),
36
+ ],
37
+ height=1024, width=1024,
38
+ seed=7, rand_device="cuda",
39
+ )
40
+ image_2.save("image_2.jpg")
examples/flux/model_inference/FLUX.1-dev-Controlnet-Upscaler.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig, ControlNetInput
3
+
4
+
5
+ pipe = FluxImagePipeline.from_pretrained(
6
+ torch_dtype=torch.bfloat16,
7
+ device="cuda",
8
+ model_configs=[
9
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors"),
10
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
13
+ ModelConfig(model_id="jasperai/Flux.1-dev-Controlnet-Upscaler", origin_file_pattern="diffusion_pytorch_model.safetensors"),
14
+ ],
15
+ )
16
+
17
+ image_1 = pipe(
18
+ prompt="a photo of a cat, highly detailed",
19
+ height=768, width=768,
20
+ seed=0, rand_device="cuda",
21
+ )
22
+ image_1.save("image_1.jpg")
23
+
24
+ image_1 = image_1.resize((2048, 2048))
25
+ image_2 = pipe(
26
+ prompt="a photo of a cat, highly detailed",
27
+ controlnet_inputs=[ControlNetInput(image=image_1, scale=0.7)],
28
+ input_image=image_1,
29
+ denoising_strength=0.99,
30
+ height=2048, width=2048, tiled=True,
31
+ seed=1, rand_device="cuda",
32
+ )
33
+ image_2.save("image_2.jpg")
examples/flux/model_inference/FLUX.1-dev-EliGen.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import torch
3
+ from PIL import Image, ImageDraw, ImageFont
4
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
5
+ from modelscope import dataset_snapshot_download
6
+
7
+
8
+ def visualize_masks(image, masks, mask_prompts, output_path, font_size=35, use_random_colors=False):
9
+ # Create a blank image for overlays
10
+ overlay = Image.new('RGBA', image.size, (0, 0, 0, 0))
11
+
12
+ colors = [
13
+ (165, 238, 173, 80),
14
+ (76, 102, 221, 80),
15
+ (221, 160, 77, 80),
16
+ (204, 93, 71, 80),
17
+ (145, 187, 149, 80),
18
+ (134, 141, 172, 80),
19
+ (157, 137, 109, 80),
20
+ (153, 104, 95, 80),
21
+ (165, 238, 173, 80),
22
+ (76, 102, 221, 80),
23
+ (221, 160, 77, 80),
24
+ (204, 93, 71, 80),
25
+ (145, 187, 149, 80),
26
+ (134, 141, 172, 80),
27
+ (157, 137, 109, 80),
28
+ (153, 104, 95, 80),
29
+ ]
30
+ # Generate random colors for each mask
31
+ if use_random_colors:
32
+ colors = [(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), 80) for _ in range(len(masks))]
33
+
34
+ # Font settings
35
+ try:
36
+ font = ImageFont.truetype("arial", font_size) # Adjust as needed
37
+ except IOError:
38
+ font = ImageFont.load_default(font_size)
39
+
40
+ # Overlay each mask onto the overlay image
41
+ for mask, mask_prompt, color in zip(masks, mask_prompts, colors):
42
+ # Convert mask to RGBA mode
43
+ mask_rgba = mask.convert('RGBA')
44
+ mask_data = mask_rgba.getdata()
45
+ new_data = [(color if item[:3] == (255, 255, 255) else (0, 0, 0, 0)) for item in mask_data]
46
+ mask_rgba.putdata(new_data)
47
+
48
+ # Draw the mask prompt text on the mask
49
+ draw = ImageDraw.Draw(mask_rgba)
50
+ mask_bbox = mask.getbbox() # Get the bounding box of the mask
51
+ text_position = (mask_bbox[0] + 10, mask_bbox[1] + 10) # Adjust text position based on mask position
52
+ draw.text(text_position, mask_prompt, fill=(255, 255, 255, 255), font=font)
53
+
54
+ # Alpha composite the overlay with this mask
55
+ overlay = Image.alpha_composite(overlay, mask_rgba)
56
+
57
+ # Composite the overlay onto the original image
58
+ result = Image.alpha_composite(image.convert('RGBA'), overlay)
59
+
60
+ # Save or display the resulting image
61
+ result.save(output_path)
62
+
63
+ return result
64
+
65
+ def example(pipe, seeds, example_id, global_prompt, entity_prompts):
66
+ dataset_snapshot_download(dataset_id="DiffSynth-Studio/examples_in_diffsynth", local_dir="./", allow_file_pattern=f"data/examples/eligen/entity_control/example_{example_id}/*.png")
67
+ masks = [Image.open(f"./data/examples/eligen/entity_control/example_{example_id}/{i}.png").convert('RGB') for i in range(len(entity_prompts))]
68
+ negative_prompt = "worst quality, low quality, monochrome, zombie, interlocked fingers, Aissist, cleavage, nsfw,"
69
+ for seed in seeds:
70
+ # generate image
71
+ image = pipe(
72
+ prompt=global_prompt,
73
+ cfg_scale=3.0,
74
+ negative_prompt=negative_prompt,
75
+ num_inference_steps=50,
76
+ embedded_guidance=3.5,
77
+ seed=seed,
78
+ height=1024,
79
+ width=1024,
80
+ eligen_entity_prompts=entity_prompts,
81
+ eligen_entity_masks=masks,
82
+ )
83
+ image.save(f"eligen_example_{example_id}_{seed}.png")
84
+ visualize_masks(image, masks, entity_prompts, f"eligen_example_{example_id}_mask_{seed}.png")
85
+
86
+
87
+ pipe = FluxImagePipeline.from_pretrained(
88
+ torch_dtype=torch.bfloat16,
89
+ device="cuda",
90
+ model_configs=[
91
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors"),
92
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
93
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
94
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
95
+ ],
96
+ )
97
+ pipe.load_lora(pipe.dit, ModelConfig(model_id="DiffSynth-Studio/Eligen", origin_file_pattern="model_bf16.safetensors"), alpha=1)
98
+
99
+ # example 1
100
+ global_prompt = "A breathtaking beauty of Raja Ampat by the late-night moonlight , one beautiful woman from behind wearing a pale blue long dress with soft glow, sitting at the top of a cliff looking towards the beach,pastell light colors, a group of small distant birds flying in far sky, a boat sailing on the sea, best quality, realistic, whimsical, fantastic, splash art, intricate detailed, hyperdetailed, maximalist style, photorealistic, concept art, sharp focus, harmony, serenity, tranquility, soft pastell colors,ambient occlusion, cozy ambient lighting, masterpiece, liiv1, linquivera, metix, mentixis, masterpiece, award winning, view from above\n"
101
+ entity_prompts = ["cliff", "sea", "moon", "sailing boat", "a seated beautiful woman", "pale blue long dress with soft glow"]
102
+ example(pipe, [0], 1, global_prompt, entity_prompts)
103
+
104
+ # example 2
105
+ global_prompt = "samurai girl wearing a kimono, she's holding a sword glowing with red flame, her long hair is flowing in the wind, she is looking at a small bird perched on the back of her hand. ultra realist style. maximum image detail. maximum realistic render."
106
+ entity_prompts = ["flowing hair", "sword glowing with red flame", "A cute bird", "blue belt"]
107
+ example(pipe, [0], 2, global_prompt, entity_prompts)
108
+
109
+ # example 3
110
+ global_prompt = "Image of a neverending staircase up to a mysterious palace in the sky, The ancient palace stood majestically atop a mist-shrouded mountain, sunrise, two traditional monk walk in the stair looking at the sunrise, fog,see-through, best quality, whimsical, fantastic, splash art, intricate detailed, hyperdetailed, photorealistic, concept art, harmony, serenity, tranquility, ambient occlusion, halation, cozy ambient lighting, dynamic lighting,masterpiece, liiv1, linquivera, metix, mentixis, masterpiece, award winning,"
111
+ entity_prompts = ["ancient palace", "stone staircase with railings", "a traditional monk", "a traditional monk"]
112
+ example(pipe, [27], 3, global_prompt, entity_prompts)
113
+
114
+ # example 4
115
+ global_prompt = "A beautiful girl wearing shirt and shorts in the street, holding a sign 'Entity Control'"
116
+ entity_prompts = ["A beautiful girl", "sign 'Entity Control'", "shorts", "shirt"]
117
+ example(pipe, [21], 4, global_prompt, entity_prompts)
118
+
119
+ # example 5
120
+ global_prompt = "A captivating, dramatic scene in a painting that exudes mystery and foreboding. A white sky, swirling blue clouds, and a crescent yellow moon illuminate a solitary woman standing near the water's edge. Her long dress flows in the wind, silhouetted against the eerie glow. The water mirrors the fiery sky and moonlight, amplifying the uneasy atmosphere."
121
+ entity_prompts = ["crescent yellow moon", "a solitary woman", "water", "swirling blue clouds"]
122
+ example(pipe, [0], 5, global_prompt, entity_prompts)
123
+
124
+ # example 6
125
+ global_prompt = "Snow White and the 6 Dwarfs."
126
+ entity_prompts = ["Dwarf 1", "Dwarf 2", "Dwarf 3", "Snow White", "Dwarf 4", "Dwarf 5", "Dwarf 6"]
127
+ example(pipe, [8], 6, global_prompt, entity_prompts)
128
+
129
+ # example 7, same prompt with different seeds
130
+ seeds = range(5, 9)
131
+ global_prompt = "A beautiful woman wearing white dress, holding a mirror, with a warm light background;"
132
+ entity_prompts = ["A beautiful woman", "mirror", "necklace", "glasses", "earring", "white dress", "jewelry headpiece"]
133
+ example(pipe, seeds, 7, global_prompt, entity_prompts)
examples/flux/model_inference/FLUX.1-dev-IP-Adapter.py ADDED
@@ -0,0 +1,24 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+
4
+
5
+ pipe = FluxImagePipeline.from_pretrained(
6
+ torch_dtype=torch.bfloat16,
7
+ device="cuda",
8
+ model_configs=[
9
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors"),
10
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
13
+ ModelConfig(model_id="InstantX/FLUX.1-dev-IP-Adapter", origin_file_pattern="ip-adapter.bin"),
14
+ ModelConfig(model_id="google/siglip-so400m-patch14-384", origin_file_pattern="model.safetensors"),
15
+ ],
16
+ )
17
+
18
+ origin_prompt = "a rabbit in a garden, colorful flowers"
19
+ image = pipe(prompt=origin_prompt, height=1280, width=960, seed=42)
20
+ image.save("style image.jpg")
21
+
22
+ image = pipe(prompt="A piggy", height=1280, width=960, seed=42,
23
+ ipadapter_images=[image], ipadapter_scale=0.7)
24
+ image.save("A piggy.jpg")
examples/flux/model_inference/FLUX.1-dev-InfiniteYou.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig, ControlNetInput
3
+ from modelscope import dataset_snapshot_download
4
+ from modelscope import snapshot_download
5
+ from PIL import Image
6
+ import numpy as np
7
+
8
+ # This model has additional requirements.
9
+ # Please install the following packages.
10
+ # pip install facexlib insightface onnxruntime
11
+ snapshot_download(
12
+ "ByteDance/InfiniteYou",
13
+ allow_file_pattern="supports/insightface/models/antelopev2/*",
14
+ local_dir="models/ByteDance/InfiniteYou",
15
+ )
16
+ pipe = FluxImagePipeline.from_pretrained(
17
+ torch_dtype=torch.bfloat16,
18
+ device="cuda",
19
+ model_configs=[
20
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors"),
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
23
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
24
+ ModelConfig(model_id="ByteDance/InfiniteYou", origin_file_pattern="infu_flux_v1.0/aes_stage2/image_proj_model.bin"),
25
+ ModelConfig(model_id="ByteDance/InfiniteYou", origin_file_pattern="infu_flux_v1.0/aes_stage2/InfuseNetModel/*.safetensors"),
26
+ ],
27
+ )
28
+
29
+ dataset_snapshot_download(
30
+ dataset_id="DiffSynth-Studio/examples_in_diffsynth",
31
+ local_dir="./",
32
+ allow_file_pattern=f"data/examples/infiniteyou/*",
33
+ )
34
+
35
+ height, width = 1024, 1024
36
+ controlnet_image = Image.fromarray(np.zeros([height, width, 3]).astype(np.uint8))
37
+ controlnet_inputs = [ControlNetInput(image=controlnet_image, scale=1.0, processor_id="None")]
38
+
39
+ prompt = "A man, portrait, cinematic"
40
+ id_image = "data/examples/infiniteyou/man.jpg"
41
+ id_image = Image.open(id_image).convert('RGB')
42
+ image = pipe(
43
+ prompt=prompt, seed=1,
44
+ infinityou_id_image=id_image, infinityou_guidance=1.0,
45
+ controlnet_inputs=controlnet_inputs,
46
+ num_inference_steps=50, embedded_guidance=3.5,
47
+ height=height, width=width,
48
+ )
49
+ image.save("man.jpg")
50
+
51
+ prompt = "A woman, portrait, cinematic"
52
+ id_image = "data/examples/infiniteyou/woman.jpg"
53
+ id_image = Image.open(id_image).convert('RGB')
54
+ image = pipe(
55
+ prompt=prompt, seed=1,
56
+ infinityou_id_image=id_image, infinityou_guidance=1.0,
57
+ controlnet_inputs=controlnet_inputs,
58
+ num_inference_steps=50, embedded_guidance=3.5,
59
+ height=height, width=width,
60
+ )
61
+ image.save("woman.jpg")
examples/flux/model_inference/FLUX.1-dev-LoRA-Encoder.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+
4
+
5
+ pipe = FluxImagePipeline.from_pretrained(
6
+ torch_dtype=torch.bfloat16,
7
+ device="cuda",
8
+ model_configs=[
9
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors"),
10
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
13
+ ModelConfig(model_id="DiffSynth-Studio/LoRA-Encoder-FLUX.1-Dev", origin_file_pattern="model.safetensors"),
14
+ ],
15
+ )
16
+ lora = ModelConfig(model_id="VoidOc/flux_animal_forest1", origin_file_pattern="20.safetensors")
17
+ pipe.load_lora(pipe.dit, lora) # Use `pipe.clear_lora()` to drop the loaded LoRA.
18
+
19
+ # Empty prompt can automatically activate LoRA capabilities.
20
+ image = pipe(prompt="", seed=0, lora_encoder_inputs=lora)
21
+ image.save("image_1.jpg")
22
+
23
+ image = pipe(prompt="", seed=0)
24
+ image.save("image_1_origin.jpg")
25
+
26
+ # Prompt without trigger words can also activate LoRA capabilities.
27
+ image = pipe(prompt="a car", seed=0, lora_encoder_inputs=lora)
28
+ image.save("image_2.jpg")
29
+
30
+ image = pipe(prompt="a car", seed=0,)
31
+ image.save("image_2_origin.jpg")
32
+
33
+ # Adjust the activation intensity through the scale parameter.
34
+ image = pipe(prompt="a cat", seed=0, lora_encoder_inputs=lora, lora_encoder_scale=1.0)
35
+ image.save("image_3.jpg")
36
+
37
+ image = pipe(prompt="a cat", seed=0, lora_encoder_inputs=lora, lora_encoder_scale=0.5)
38
+ image.save("image_3_scale.jpg")
examples/flux/model_inference/FLUX.1-dev-LoRA-Fusion.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+
4
+
5
+ vram_config = {
6
+ # Enable lora hotloading
7
+ "offload_dtype": torch.bfloat16,
8
+ "offload_device": "cuda",
9
+ "onload_dtype": torch.bfloat16,
10
+ "onload_device": "cuda",
11
+ "preparing_dtype": torch.bfloat16,
12
+ "preparing_device": "cuda",
13
+ "computation_dtype": torch.bfloat16,
14
+ "computation_device": "cuda",
15
+ }
16
+ pipe = FluxImagePipeline.from_pretrained(
17
+ torch_dtype=torch.bfloat16,
18
+ device="cuda",
19
+ model_configs=[
20
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors", **vram_config),
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
23
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
24
+ ModelConfig(model_id="DiffSynth-Studio/LoRAFusion-preview-FLUX.1-dev", origin_file_pattern="model.safetensors"),
25
+ ],
26
+ )
27
+ pipe.enable_lora_merger()
28
+
29
+ pipe.load_lora(
30
+ pipe.dit,
31
+ ModelConfig(model_id="cancel13/cxsk", origin_file_pattern="30.safetensors"),
32
+ )
33
+ pipe.load_lora(
34
+ pipe.dit,
35
+ ModelConfig(model_id="DiffSynth-Studio/ArtAug-lora-FLUX.1dev-v1", origin_file_pattern="merged_lora.safetensors"),
36
+ )
37
+ image = pipe(prompt="a cat", seed=0)
38
+ image.save("image_fused.jpg")
examples/flux/model_inference/FLUX.1-dev-Timestep-LoRA.py ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+
4
+
5
+ pipe = FluxImagePipeline.from_pretrained(
6
+ torch_dtype=torch.bfloat16,
7
+ device="cuda",
8
+ model_configs=[
9
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors"),
10
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
13
+ ],
14
+ )
15
+
16
+ pipe.load_timestep_lora(ModelConfig(model_id="DiffSynth-Studio/MultiAlign-FLUX.1-dev", origin_file_pattern="adapter_model.safetensors"))
17
+
18
+ prompt = "A moonlit Venetian canal scene with a gondola floating on the left, a candlelit table for two on a stone terrace to the right, and flower boxes under arched windows in the peach-colored building behind, with shimmering reflections in dark water; romantic cinematic mood and the restaurant sign reading 'NOTTE SERENA'"
19
+
20
+ image = pipe(prompt=prompt, seed=0, num_inference_steps=30, t5_sequence_length=128)
21
+ image.save("FLUX.1-dev-Timestep-LoRA.jpg")
examples/flux/model_inference/FLUX.1-dev.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+
4
+
5
+ pipe = FluxImagePipeline.from_pretrained(
6
+ torch_dtype=torch.bfloat16,
7
+ device="cuda",
8
+ model_configs=[
9
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors"),
10
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
13
+ ],
14
+ )
15
+
16
+ prompt = "CG, masterpiece, best quality, solo, long hair, wavy hair, silver hair, blue eyes, blue dress, medium breasts, dress, underwater, air bubble, floating hair, refraction, portrait. The girl's flowing silver hair shimmers with every color of the rainbow and cascades down, merging with the floating flora around her."
17
+ negative_prompt = "worst quality, low quality, monochrome, zombie, interlocked fingers, Aissist, cleavage, nsfw,"
18
+
19
+ image = pipe(prompt=prompt, seed=0)
20
+ image.save("flux.jpg")
21
+
22
+ image = pipe(
23
+ prompt=prompt, negative_prompt=negative_prompt,
24
+ seed=0, cfg_scale=2, num_inference_steps=50,
25
+ )
26
+ image.save("flux_cfg.jpg")
examples/flux/model_inference/Insert-Anything.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+ from PIL import Image
4
+ from modelscope import dataset_snapshot_download
5
+
6
+ pipe = FluxImagePipeline.from_pretrained(
7
+ torch_dtype=torch.bfloat16,
8
+ device="cuda",
9
+ model_configs=[
10
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="flux1-fill-dev.safetensors"),
11
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="text_encoder/model.safetensors"),
12
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
13
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="ae.safetensors"),
14
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Redux-dev", origin_file_pattern="image_encoder/model.safetensors"),
15
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Redux-dev", origin_file_pattern="image_embedder/diffusion_pytorch_model.safetensors"),
16
+ ],
17
+ )
18
+
19
+ pipe.load_lora(pipe.dit, ModelConfig(model_id="HuanJue/Insert-Anything", origin_file_pattern="20250321_steps5000_pytorch_lora_weights.safetensors"))
20
+
21
+ dataset_snapshot_download(
22
+ dataset_id="HuanJue/example_dataset",
23
+ local_dir="./",
24
+ allow_file_pattern=f"Insert-Anything/*",
25
+ )
26
+
27
+ source_image = Image.open("Insert-Anything/source_image.png").convert("RGB")
28
+ source_mask = Image.open("Insert-Anything/source_mask.png").convert("L")
29
+ ref_image = Image.open("Insert-Anything/ref_image.png").convert("RGB")
30
+ ref_mask = Image.open("Insert-Anything/ref_mask.png").convert("L")
31
+
32
+ seed = 666
33
+
34
+ image = pipe(
35
+ insert_anything_source_image=source_image,
36
+ insert_anything_source_mask=source_mask,
37
+ insert_anything_ref_image=ref_image,
38
+ insert_anything_ref_mask=ref_mask,
39
+ seed=seed,
40
+ embedded_guidance=30.0,
41
+ num_inference_steps=50,
42
+ )
43
+
44
+ image.save("image_Insert-Anything.jpg")
examples/flux/model_inference/Nexus-Gen-Editing.py ADDED
@@ -0,0 +1,37 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import torch
3
+ from PIL import Image
4
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
5
+ from modelscope import dataset_snapshot_download
6
+
7
+
8
+ if importlib.util.find_spec("transformers") is None:
9
+ raise ImportError("You are using Nexus-GenV2. It depends on transformers, which is not installed. Please install it with `pip install transformers==4.49.0`.")
10
+ else:
11
+ import transformers
12
+ assert transformers.__version__ == "4.49.0", "Nexus-GenV2 requires transformers==4.49.0, please install it with `pip install transformers==4.49.0`."
13
+
14
+
15
+ pipe = FluxImagePipeline.from_pretrained(
16
+ torch_dtype=torch.bfloat16,
17
+ device="cuda",
18
+ model_configs=[
19
+ ModelConfig(model_id="DiffSynth-Studio/Nexus-GenV2", origin_file_pattern="model*.safetensors"),
20
+ ModelConfig(model_id="DiffSynth-Studio/Nexus-GenV2", origin_file_pattern="edit_decoder.bin"),
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
23
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
24
+ ],
25
+ nexus_gen_processor_config=ModelConfig(model_id="DiffSynth-Studio/Nexus-GenV2", origin_file_pattern="processor/"),
26
+ )
27
+
28
+ dataset_snapshot_download(dataset_id="DiffSynth-Studio/examples_in_diffsynth", local_dir="./", allow_file_pattern=f"data/examples/nexusgen/cat.jpg")
29
+ ref_image = Image.open("data/examples/nexusgen/cat.jpg").convert("RGB")
30
+ prompt = "Add a crown."
31
+ image = pipe(
32
+ prompt=prompt, negative_prompt="",
33
+ seed=42, cfg_scale=2.0, num_inference_steps=50,
34
+ nexus_gen_reference_image=ref_image,
35
+ height=512, width=512,
36
+ )
37
+ image.save("cat_crown.jpg")
examples/flux/model_inference/Nexus-Gen-Generation.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import importlib
2
+ import torch
3
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
4
+
5
+
6
+ if importlib.util.find_spec("transformers") is None:
7
+ raise ImportError("You are using Nexus-GenV2. It depends on transformers, which is not installed. Please install it with `pip install transformers==4.49.0`.")
8
+ else:
9
+ import transformers
10
+ assert transformers.__version__ == "4.49.0", "Nexus-GenV2 requires transformers==4.49.0, please install it with `pip install transformers==4.49.0`."
11
+
12
+
13
+ pipe = FluxImagePipeline.from_pretrained(
14
+ torch_dtype=torch.bfloat16,
15
+ device="cuda",
16
+ model_configs=[
17
+ ModelConfig(model_id="DiffSynth-Studio/Nexus-GenV2", origin_file_pattern="model*.safetensors"),
18
+ ModelConfig(model_id="DiffSynth-Studio/Nexus-GenV2", origin_file_pattern="generation_decoder.bin"),
19
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors"),
20
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors"),
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors"),
22
+ ],
23
+ nexus_gen_processor_config=ModelConfig("DiffSynth-Studio/Nexus-GenV2", origin_file_pattern="processor"),
24
+ )
25
+
26
+ prompt = "一只可爱的猫咪"
27
+ image = pipe(
28
+ prompt=prompt, negative_prompt="",
29
+ seed=0, cfg_scale=3, num_inference_steps=50,
30
+ height=1024, width=1024,
31
+ )
32
+ image.save("cat.jpg")
examples/flux/model_inference/Step1X-Edit.py ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+ from PIL import Image
4
+ import numpy as np
5
+
6
+
7
+ pipe = FluxImagePipeline.from_pretrained(
8
+ torch_dtype=torch.bfloat16,
9
+ device="cuda",
10
+ model_configs=[
11
+ ModelConfig(model_id="Qwen/Qwen2.5-VL-7B-Instruct", origin_file_pattern="model-*.safetensors"),
12
+ ModelConfig(model_id="stepfun-ai/Step1X-Edit", origin_file_pattern="step1x-edit-i1258.safetensors"),
13
+ ModelConfig(model_id="stepfun-ai/Step1X-Edit", origin_file_pattern="vae.safetensors"),
14
+ ],
15
+ )
16
+
17
+ image = Image.fromarray(np.zeros((1248, 832, 3), dtype=np.uint8) + 255)
18
+ image = pipe(
19
+ prompt="draw red flowers in Chinese ink painting style",
20
+ step1x_reference_image=image,
21
+ width=832, height=1248, cfg_scale=6,
22
+ seed=1, rand_device='cuda'
23
+ )
24
+ image.save("image_1.jpg")
25
+
26
+ image = pipe(
27
+ prompt="add more flowers in Chinese ink painting style",
28
+ step1x_reference_image=image,
29
+ width=832, height=1248, cfg_scale=6,
30
+ seed=2, rand_device='cuda'
31
+ )
32
+ image.save("image_2.jpg")
examples/flux/model_inference_low_vram/FLEX.2-preview.py ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+ from diffsynth.utils.controlnet import Annotator
4
+ import numpy as np
5
+ from PIL import Image
6
+
7
+
8
+ vram_config = {
9
+ "offload_dtype": torch.float8_e4m3fn,
10
+ "offload_device": "cpu",
11
+ "onload_dtype": torch.float8_e4m3fn,
12
+ "onload_device": "cpu",
13
+ "preparing_dtype": torch.float8_e4m3fn,
14
+ "preparing_device": "cuda",
15
+ "computation_dtype": torch.bfloat16,
16
+ "computation_device": "cuda",
17
+ }
18
+ pipe = FluxImagePipeline.from_pretrained(
19
+ torch_dtype=torch.bfloat16,
20
+ device="cuda",
21
+ model_configs=[
22
+ ModelConfig(model_id="ostris/Flex.2-preview", origin_file_pattern="Flex.2-preview.safetensors", **vram_config),
23
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
24
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
25
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors", **vram_config),
26
+ ],
27
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
28
+ )
29
+
30
+ image = pipe(
31
+ prompt="portrait of a beautiful Asian girl, long hair, red t-shirt, sunshine, beach",
32
+ num_inference_steps=50, embedded_guidance=3.5,
33
+ seed=0
34
+ )
35
+ image.save("image_1.jpg")
36
+
37
+ mask = np.zeros((1024, 1024, 3), dtype=np.uint8)
38
+ mask[200:400, 400:700] = 255
39
+ mask = Image.fromarray(mask)
40
+ mask.save("image_mask.jpg")
41
+
42
+ inpaint_image = image
43
+
44
+ image = pipe(
45
+ prompt="portrait of a beautiful Asian girl with sunglasses, long hair, red t-shirt, sunshine, beach",
46
+ num_inference_steps=50, embedded_guidance=3.5,
47
+ flex_inpaint_image=inpaint_image, flex_inpaint_mask=mask,
48
+ seed=4
49
+ )
50
+ image.save("image_2.jpg")
51
+
52
+ control_image = Annotator("canny")(image)
53
+ control_image.save("image_control.jpg")
54
+
55
+ image = pipe(
56
+ prompt="portrait of a beautiful Asian girl with sunglasses, long hair, yellow t-shirt, sunshine, beach",
57
+ num_inference_steps=50, embedded_guidance=3.5,
58
+ flex_control_image=control_image,
59
+ seed=4
60
+ )
61
+ image.save("image_3.jpg")
examples/flux/model_inference_low_vram/FLUX.1-Fill-dev.py ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+ from PIL import Image
4
+ from modelscope import dataset_snapshot_download
5
+
6
+ vram_config = {
7
+ "offload_dtype": torch.float8_e4m3fn,
8
+ "offload_device": "cpu",
9
+ "onload_dtype": torch.float8_e4m3fn,
10
+ "onload_device": "cpu",
11
+ "preparing_dtype": torch.float8_e4m3fn,
12
+ "preparing_device": "cuda",
13
+ "computation_dtype": torch.bfloat16,
14
+ "computation_device": "cuda",
15
+ }
16
+ pipe = FluxImagePipeline.from_pretrained(
17
+ torch_dtype=torch.bfloat16,
18
+ device="cuda",
19
+ model_configs=[
20
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="flux1-fill-dev.safetensors", **vram_config),
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
23
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Fill-dev", origin_file_pattern="ae.safetensors", **vram_config),
24
+ ],
25
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
26
+ )
27
+
28
+ dataset_snapshot_download(
29
+ dataset_id="HuanJue/example_dataset",
30
+ local_dir="./",
31
+ allow_file_pattern=f"FLUX.1-Fill-dev/*",
32
+ )
33
+
34
+ flux_fill_image = Image.open("FLUX.1-Fill-dev/cup.png").convert("RGB")
35
+ flux_fill_mask = Image.open("FLUX.1-Fill-dev/cup_mask.png").convert("L")
36
+ prompt = "a white paper cup"
37
+ image = pipe(prompt=prompt, flux_fill_image=flux_fill_image, flux_fill_mask=flux_fill_mask, height=1632, width=1232, seed=0, embedded_guidance=30.0, num_inference_steps=50)
38
+
39
+ image.save("image_FLUX.1-Fill-dev.jpg")
examples/flux/model_inference_low_vram/FLUX.1-Kontext-dev.py ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+ from PIL import Image
4
+
5
+
6
+ vram_config = {
7
+ "offload_dtype": torch.float8_e4m3fn,
8
+ "offload_device": "cpu",
9
+ "onload_dtype": torch.float8_e4m3fn,
10
+ "onload_device": "cpu",
11
+ "preparing_dtype": torch.float8_e4m3fn,
12
+ "preparing_device": "cuda",
13
+ "computation_dtype": torch.bfloat16,
14
+ "computation_device": "cuda",
15
+ }
16
+ pipe = FluxImagePipeline.from_pretrained(
17
+ torch_dtype=torch.bfloat16,
18
+ device="cuda",
19
+ model_configs=[
20
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Kontext-dev", origin_file_pattern="flux1-kontext-dev.safetensors", **vram_config),
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
23
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors", **vram_config),
24
+ ],
25
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
26
+ )
27
+
28
+ image_1 = pipe(
29
+ prompt="a beautiful Asian long-haired female college student.",
30
+ embedded_guidance=2.5,
31
+ seed=1,
32
+ )
33
+ image_1.save("image_1.jpg")
34
+
35
+ image_2 = pipe(
36
+ prompt="transform the style to anime style.",
37
+ kontext_images=image_1,
38
+ embedded_guidance=2.5,
39
+ seed=2,
40
+ )
41
+ image_2.save("image_2.jpg")
42
+
43
+ image_3 = pipe(
44
+ prompt="let her smile.",
45
+ kontext_images=image_1,
46
+ embedded_guidance=2.5,
47
+ seed=3,
48
+ )
49
+ image_3.save("image_3.jpg")
50
+
51
+ image_4 = pipe(
52
+ prompt="let the girl play basketball.",
53
+ kontext_images=image_1,
54
+ embedded_guidance=2.5,
55
+ seed=4,
56
+ )
57
+ image_4.save("image_4.jpg")
58
+
59
+ image_5 = pipe(
60
+ prompt="move the girl to a park, let her sit on a chair.",
61
+ kontext_images=image_1,
62
+ embedded_guidance=2.5,
63
+ seed=5,
64
+ )
65
+ image_5.save("image_5.jpg")
examples/flux/model_inference_low_vram/FLUX.1-Krea-dev.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+
4
+
5
+ vram_config = {
6
+ "offload_dtype": torch.float8_e4m3fn,
7
+ "offload_device": "cpu",
8
+ "onload_dtype": torch.float8_e4m3fn,
9
+ "onload_device": "cpu",
10
+ "preparing_dtype": torch.float8_e4m3fn,
11
+ "preparing_device": "cuda",
12
+ "computation_dtype": torch.bfloat16,
13
+ "computation_device": "cuda",
14
+ }
15
+ pipe = FluxImagePipeline.from_pretrained(
16
+ torch_dtype=torch.bfloat16,
17
+ device="cuda",
18
+ model_configs=[
19
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Krea-dev", origin_file_pattern="flux1-krea-dev.safetensors", **vram_config),
20
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors", **vram_config),
23
+ ],
24
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
25
+ )
26
+
27
+ prompt = "An beautiful woman is riding a bicycle in a park, wearing a red dress"
28
+ negative_prompt = "worst quality, low quality, monochrome, zombie, interlocked fingers, Aissist, cleavage, nsfw,"
29
+
30
+ image = pipe(prompt=prompt, seed=0, embedded_guidance=4.5)
31
+ image.save("flux_krea.jpg")
32
+
33
+ image = pipe(
34
+ prompt=prompt, negative_prompt=negative_prompt,
35
+ seed=0, cfg_scale=2, num_inference_steps=50,
36
+ embedded_guidance=4.5
37
+ )
38
+ image.save("flux_krea_cfg.jpg")
examples/flux/model_inference_low_vram/FLUX.1-Redux-dev.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+ from PIL import Image
4
+ from modelscope import dataset_snapshot_download
5
+
6
+ vram_config = {
7
+ "offload_dtype": torch.float8_e4m3fn,
8
+ "offload_device": "cpu",
9
+ "onload_dtype": torch.float8_e4m3fn,
10
+ "onload_device": "cpu",
11
+ "preparing_dtype": torch.float8_e4m3fn,
12
+ "preparing_device": "cuda",
13
+ "computation_dtype": torch.bfloat16,
14
+ "computation_device": "cuda",
15
+ }
16
+
17
+ pipe = FluxImagePipeline.from_pretrained(
18
+ torch_dtype=torch.bfloat16,
19
+ device="cuda",
20
+ model_configs=[
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors", **vram_config),
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
23
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
24
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors", **vram_config),
25
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Redux-dev", origin_file_pattern="image_encoder/model.safetensors", **vram_config),
26
+ ModelConfig(model_id="black-forest-labs/FLUX.1-Redux-dev", origin_file_pattern="image_embedder/diffusion_pytorch_model.safetensors", **vram_config),
27
+ ],
28
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
29
+ )
30
+ dataset_snapshot_download(
31
+ dataset_id="HuanJue/example_dataset",
32
+ local_dir="./",
33
+ allow_file_pattern=f"FLUX.1-Redux-dev/*",
34
+ )
35
+
36
+ flux_redux_image = Image.open("FLUX.1-Redux-dev/robot.png").convert("RGB")
37
+
38
+ image = pipe(flux_redux_image=flux_redux_image, embedded_guidance=2.5, num_inference_steps=50)
39
+
40
+ image.save("image_FLUX.1-Redux-dev.jpg")
examples/flux/model_inference_low_vram/FLUX.1-dev-AttriCtrl.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+
4
+
5
+ vram_config = {
6
+ "offload_dtype": torch.float8_e4m3fn,
7
+ "offload_device": "cpu",
8
+ "onload_dtype": torch.float8_e4m3fn,
9
+ "onload_device": "cpu",
10
+ "preparing_dtype": torch.float8_e4m3fn,
11
+ "preparing_device": "cuda",
12
+ "computation_dtype": torch.bfloat16,
13
+ "computation_device": "cuda",
14
+ }
15
+ pipe = FluxImagePipeline.from_pretrained(
16
+ torch_dtype=torch.bfloat16,
17
+ device="cuda",
18
+ model_configs=[
19
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors", **vram_config),
20
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors", **vram_config),
23
+ ModelConfig(model_id="DiffSynth-Studio/AttriCtrl-FLUX.1-Dev", origin_file_pattern="models/brightness.safetensors", **vram_config)
24
+ ],
25
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
26
+ )
27
+
28
+ for i in [0.1, 0.3, 0.5, 0.7, 0.9]:
29
+ image = pipe(prompt="a cat on the beach", seed=2, value_controller_inputs=[i])
30
+ image.save(f"value_control_{i}.jpg")
examples/flux/model_inference_low_vram/FLUX.1-dev-Controlnet-Inpainting-Beta.py ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig, ControlNetInput
3
+ import numpy as np
4
+ from PIL import Image
5
+
6
+
7
+ vram_config = {
8
+ "offload_dtype": torch.float8_e4m3fn,
9
+ "offload_device": "cpu",
10
+ "onload_dtype": torch.float8_e4m3fn,
11
+ "onload_device": "cpu",
12
+ "preparing_dtype": torch.float8_e4m3fn,
13
+ "preparing_device": "cuda",
14
+ "computation_dtype": torch.bfloat16,
15
+ "computation_device": "cuda",
16
+ }
17
+ pipe = FluxImagePipeline.from_pretrained(
18
+ torch_dtype=torch.bfloat16,
19
+ device="cuda",
20
+ model_configs=[
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors", **vram_config),
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
23
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
24
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors", **vram_config),
25
+ ModelConfig(model_id="alimama-creative/FLUX.1-dev-Controlnet-Inpainting-Beta", origin_file_pattern="diffusion_pytorch_model.safetensors", **vram_config),
26
+ ],
27
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
28
+ )
29
+
30
+ image_1 = pipe(
31
+ prompt="a cat sitting on a chair",
32
+ height=1024, width=1024,
33
+ seed=8, rand_device="cuda",
34
+ )
35
+ image_1.save("image_1.jpg")
36
+
37
+ mask = np.zeros((1024, 1024, 3), dtype=np.uint8)
38
+ mask[100:350, 350: -300] = 255
39
+ mask = Image.fromarray(mask)
40
+ mask.save("mask.jpg")
41
+
42
+ image_2 = pipe(
43
+ prompt="a cat sitting on a chair, wearing sunglasses",
44
+ controlnet_inputs=[ControlNetInput(image=image_1, inpaint_mask=mask, scale=0.9)],
45
+ height=1024, width=1024,
46
+ seed=9, rand_device="cuda",
47
+ )
48
+ image_2.save("image_2.jpg")
examples/flux/model_inference_low_vram/FLUX.1-dev-Controlnet-Union-alpha.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig, ControlNetInput
3
+ from diffsynth.utils.controlnet import Annotator
4
+ from modelscope import snapshot_download
5
+
6
+
7
+ vram_config = {
8
+ "offload_dtype": torch.float8_e4m3fn,
9
+ "offload_device": "cpu",
10
+ "onload_dtype": torch.float8_e4m3fn,
11
+ "onload_device": "cpu",
12
+ "preparing_dtype": torch.float8_e4m3fn,
13
+ "preparing_device": "cuda",
14
+ "computation_dtype": torch.bfloat16,
15
+ "computation_device": "cuda",
16
+ }
17
+ snapshot_download("sd_lora/Annotators", allow_file_pattern="dpt_hybrid-midas-501f0c75.pt", local_dir="models/Annotators")
18
+ pipe = FluxImagePipeline.from_pretrained(
19
+ torch_dtype=torch.bfloat16,
20
+ device="cuda",
21
+ model_configs=[
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors", **vram_config),
23
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
24
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
25
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors", **vram_config),
26
+ ModelConfig(model_id="InstantX/FLUX.1-dev-Controlnet-Union-alpha", origin_file_pattern="diffusion_pytorch_model.safetensors", **vram_config),
27
+ ],
28
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
29
+ )
30
+
31
+ image_1 = pipe(
32
+ prompt="a beautiful Asian girl, full body, red dress, summer",
33
+ height=1024, width=1024,
34
+ seed=6, rand_device="cuda",
35
+ )
36
+ image_1.save("image_1.jpg")
37
+
38
+ image_canny = Annotator("canny")(image_1)
39
+ image_depth = Annotator("depth")(image_1)
40
+
41
+ image_2 = pipe(
42
+ prompt="a beautiful Asian girl, full body, red dress, winter",
43
+ controlnet_inputs=[
44
+ ControlNetInput(image=image_canny, scale=0.3, processor_id="canny"),
45
+ ControlNetInput(image=image_depth, scale=0.3, processor_id="depth"),
46
+ ],
47
+ height=1024, width=1024,
48
+ seed=7, rand_device="cuda",
49
+ )
50
+ image_2.save("image_2.jpg")
examples/flux/model_inference_low_vram/FLUX.1-dev-Controlnet-Upscaler.py ADDED
@@ -0,0 +1,44 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig, ControlNetInput
3
+
4
+
5
+ vram_config = {
6
+ "offload_dtype": torch.float8_e4m3fn,
7
+ "offload_device": "cpu",
8
+ "onload_dtype": torch.float8_e4m3fn,
9
+ "onload_device": "cpu",
10
+ "preparing_dtype": torch.float8_e4m3fn,
11
+ "preparing_device": "cuda",
12
+ "computation_dtype": torch.bfloat16,
13
+ "computation_device": "cuda",
14
+ }
15
+ pipe = FluxImagePipeline.from_pretrained(
16
+ torch_dtype=torch.bfloat16,
17
+ device="cuda",
18
+ model_configs=[
19
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors", **vram_config),
20
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors", **vram_config),
23
+ ModelConfig(model_id="jasperai/Flux.1-dev-Controlnet-Upscaler", origin_file_pattern="diffusion_pytorch_model.safetensors", **vram_config),
24
+ ],
25
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
26
+ )
27
+
28
+ image_1 = pipe(
29
+ prompt="a photo of a cat, highly detailed",
30
+ height=768, width=768,
31
+ seed=0, rand_device="cuda",
32
+ )
33
+ image_1.save("image_1.jpg")
34
+
35
+ image_1 = image_1.resize((2048, 2048))
36
+ image_2 = pipe(
37
+ prompt="a photo of a cat, highly detailed",
38
+ controlnet_inputs=[ControlNetInput(image=image_1, scale=0.7)],
39
+ input_image=image_1,
40
+ denoising_strength=0.99,
41
+ height=2048, width=2048, tiled=True,
42
+ seed=1, rand_device="cuda",
43
+ )
44
+ image_2.save("image_2.jpg")
examples/flux/model_inference_low_vram/FLUX.1-dev-EliGen.py ADDED
@@ -0,0 +1,144 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import random
2
+ import torch
3
+ from PIL import Image, ImageDraw, ImageFont
4
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
5
+ from modelscope import dataset_snapshot_download
6
+
7
+
8
+ vram_config = {
9
+ "offload_dtype": torch.float8_e4m3fn,
10
+ "offload_device": "cpu",
11
+ "onload_dtype": torch.float8_e4m3fn,
12
+ "onload_device": "cpu",
13
+ "preparing_dtype": torch.float8_e4m3fn,
14
+ "preparing_device": "cuda",
15
+ "computation_dtype": torch.bfloat16,
16
+ "computation_device": "cuda",
17
+ }
18
+ def visualize_masks(image, masks, mask_prompts, output_path, font_size=35, use_random_colors=False):
19
+ # Create a blank image for overlays
20
+ overlay = Image.new('RGBA', image.size, (0, 0, 0, 0))
21
+
22
+ colors = [
23
+ (165, 238, 173, 80),
24
+ (76, 102, 221, 80),
25
+ (221, 160, 77, 80),
26
+ (204, 93, 71, 80),
27
+ (145, 187, 149, 80),
28
+ (134, 141, 172, 80),
29
+ (157, 137, 109, 80),
30
+ (153, 104, 95, 80),
31
+ (165, 238, 173, 80),
32
+ (76, 102, 221, 80),
33
+ (221, 160, 77, 80),
34
+ (204, 93, 71, 80),
35
+ (145, 187, 149, 80),
36
+ (134, 141, 172, 80),
37
+ (157, 137, 109, 80),
38
+ (153, 104, 95, 80),
39
+ ]
40
+ # Generate random colors for each mask
41
+ if use_random_colors:
42
+ colors = [(random.randint(0, 255), random.randint(0, 255), random.randint(0, 255), 80) for _ in range(len(masks))]
43
+
44
+ # Font settings
45
+ try:
46
+ font = ImageFont.truetype("arial", font_size) # Adjust as needed
47
+ except IOError:
48
+ font = ImageFont.load_default(font_size)
49
+
50
+ # Overlay each mask onto the overlay image
51
+ for mask, mask_prompt, color in zip(masks, mask_prompts, colors):
52
+ # Convert mask to RGBA mode
53
+ mask_rgba = mask.convert('RGBA')
54
+ mask_data = mask_rgba.getdata()
55
+ new_data = [(color if item[:3] == (255, 255, 255) else (0, 0, 0, 0)) for item in mask_data]
56
+ mask_rgba.putdata(new_data)
57
+
58
+ # Draw the mask prompt text on the mask
59
+ draw = ImageDraw.Draw(mask_rgba)
60
+ mask_bbox = mask.getbbox() # Get the bounding box of the mask
61
+ text_position = (mask_bbox[0] + 10, mask_bbox[1] + 10) # Adjust text position based on mask position
62
+ draw.text(text_position, mask_prompt, fill=(255, 255, 255, 255), font=font)
63
+
64
+ # Alpha composite the overlay with this mask
65
+ overlay = Image.alpha_composite(overlay, mask_rgba)
66
+
67
+ # Composite the overlay onto the original image
68
+ result = Image.alpha_composite(image.convert('RGBA'), overlay)
69
+
70
+ # Save or display the resulting image
71
+ result.save(output_path)
72
+
73
+ return result
74
+
75
+ def example(pipe, seeds, example_id, global_prompt, entity_prompts):
76
+ dataset_snapshot_download(dataset_id="DiffSynth-Studio/examples_in_diffsynth", local_dir="./", allow_file_pattern=f"data/examples/eligen/entity_control/example_{example_id}/*.png")
77
+ masks = [Image.open(f"./data/examples/eligen/entity_control/example_{example_id}/{i}.png").convert('RGB') for i in range(len(entity_prompts))]
78
+ negative_prompt = "worst quality, low quality, monochrome, zombie, interlocked fingers, Aissist, cleavage, nsfw,"
79
+ for seed in seeds:
80
+ # generate image
81
+ image = pipe(
82
+ prompt=global_prompt,
83
+ cfg_scale=3.0,
84
+ negative_prompt=negative_prompt,
85
+ num_inference_steps=50,
86
+ embedded_guidance=3.5,
87
+ seed=seed,
88
+ height=1024,
89
+ width=1024,
90
+ eligen_entity_prompts=entity_prompts,
91
+ eligen_entity_masks=masks,
92
+ )
93
+ image.save(f"eligen_example_{example_id}_{seed}.png")
94
+ visualize_masks(image, masks, entity_prompts, f"eligen_example_{example_id}_mask_{seed}.png")
95
+
96
+
97
+ pipe = FluxImagePipeline.from_pretrained(
98
+ torch_dtype=torch.bfloat16,
99
+ device="cuda",
100
+ model_configs=[
101
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors", **vram_config),
102
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
103
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
104
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors", **vram_config),
105
+ ],
106
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
107
+ )
108
+ pipe.load_lora(pipe.dit, ModelConfig(model_id="DiffSynth-Studio/Eligen", origin_file_pattern="model_bf16.safetensors"), alpha=1)
109
+
110
+ # example 1
111
+ global_prompt = "A breathtaking beauty of Raja Ampat by the late-night moonlight , one beautiful woman from behind wearing a pale blue long dress with soft glow, sitting at the top of a cliff looking towards the beach,pastell light colors, a group of small distant birds flying in far sky, a boat sailing on the sea, best quality, realistic, whimsical, fantastic, splash art, intricate detailed, hyperdetailed, maximalist style, photorealistic, concept art, sharp focus, harmony, serenity, tranquility, soft pastell colors,ambient occlusion, cozy ambient lighting, masterpiece, liiv1, linquivera, metix, mentixis, masterpiece, award winning, view from above\n"
112
+ entity_prompts = ["cliff", "sea", "moon", "sailing boat", "a seated beautiful woman", "pale blue long dress with soft glow"]
113
+ example(pipe, [0], 1, global_prompt, entity_prompts)
114
+
115
+ # example 2
116
+ global_prompt = "samurai girl wearing a kimono, she's holding a sword glowing with red flame, her long hair is flowing in the wind, she is looking at a small bird perched on the back of her hand. ultra realist style. maximum image detail. maximum realistic render."
117
+ entity_prompts = ["flowing hair", "sword glowing with red flame", "A cute bird", "blue belt"]
118
+ example(pipe, [0], 2, global_prompt, entity_prompts)
119
+
120
+ # example 3
121
+ global_prompt = "Image of a neverending staircase up to a mysterious palace in the sky, The ancient palace stood majestically atop a mist-shrouded mountain, sunrise, two traditional monk walk in the stair looking at the sunrise, fog,see-through, best quality, whimsical, fantastic, splash art, intricate detailed, hyperdetailed, photorealistic, concept art, harmony, serenity, tranquility, ambient occlusion, halation, cozy ambient lighting, dynamic lighting,masterpiece, liiv1, linquivera, metix, mentixis, masterpiece, award winning,"
122
+ entity_prompts = ["ancient palace", "stone staircase with railings", "a traditional monk", "a traditional monk"]
123
+ example(pipe, [27], 3, global_prompt, entity_prompts)
124
+
125
+ # example 4
126
+ global_prompt = "A beautiful girl wearing shirt and shorts in the street, holding a sign 'Entity Control'"
127
+ entity_prompts = ["A beautiful girl", "sign 'Entity Control'", "shorts", "shirt"]
128
+ example(pipe, [21], 4, global_prompt, entity_prompts)
129
+
130
+ # example 5
131
+ global_prompt = "A captivating, dramatic scene in a painting that exudes mystery and foreboding. A white sky, swirling blue clouds, and a crescent yellow moon illuminate a solitary woman standing near the water's edge. Her long dress flows in the wind, silhouetted against the eerie glow. The water mirrors the fiery sky and moonlight, amplifying the uneasy atmosphere."
132
+ entity_prompts = ["crescent yellow moon", "a solitary woman", "water", "swirling blue clouds"]
133
+ example(pipe, [0], 5, global_prompt, entity_prompts)
134
+
135
+ # example 6
136
+ global_prompt = "Snow White and the 6 Dwarfs."
137
+ entity_prompts = ["Dwarf 1", "Dwarf 2", "Dwarf 3", "Snow White", "Dwarf 4", "Dwarf 5", "Dwarf 6"]
138
+ example(pipe, [8], 6, global_prompt, entity_prompts)
139
+
140
+ # example 7, same prompt with different seeds
141
+ seeds = range(5, 9)
142
+ global_prompt = "A beautiful woman wearing white dress, holding a mirror, with a warm light background;"
143
+ entity_prompts = ["A beautiful woman", "mirror", "necklace", "glasses", "earring", "white dress", "jewelry headpiece"]
144
+ example(pipe, seeds, 7, global_prompt, entity_prompts)
examples/flux/model_inference_low_vram/FLUX.1-dev-IP-Adapter.py ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig
3
+
4
+
5
+ vram_config = {
6
+ "offload_dtype": torch.float8_e4m3fn,
7
+ "offload_device": "cpu",
8
+ "onload_dtype": torch.float8_e4m3fn,
9
+ "onload_device": "cpu",
10
+ "preparing_dtype": torch.float8_e4m3fn,
11
+ "preparing_device": "cuda",
12
+ "computation_dtype": torch.bfloat16,
13
+ "computation_device": "cuda",
14
+ }
15
+ pipe = FluxImagePipeline.from_pretrained(
16
+ torch_dtype=torch.bfloat16,
17
+ device="cuda",
18
+ model_configs=[
19
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors", **vram_config),
20
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
21
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
22
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors", **vram_config),
23
+ ModelConfig(model_id="InstantX/FLUX.1-dev-IP-Adapter", origin_file_pattern="ip-adapter.bin", **vram_config),
24
+ ModelConfig(model_id="google/siglip-so400m-patch14-384", origin_file_pattern="model.safetensors", **vram_config),
25
+ ],
26
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
27
+ )
28
+
29
+ origin_prompt = "a rabbit in a garden, colorful flowers"
30
+ image = pipe(prompt=origin_prompt, height=1280, width=960, seed=42)
31
+ image.save("style image.jpg")
32
+
33
+ image = pipe(prompt="A piggy", height=1280, width=960, seed=42,
34
+ ipadapter_images=[image], ipadapter_scale=0.7)
35
+ image.save("A piggy.jpg")
examples/flux/model_inference_low_vram/FLUX.1-dev-InfiniteYou.py ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import torch
2
+ from diffsynth.pipelines.flux_image import FluxImagePipeline, ModelConfig, ControlNetInput
3
+ from modelscope import dataset_snapshot_download
4
+ from modelscope import snapshot_download
5
+ from PIL import Image
6
+ import numpy as np
7
+
8
+
9
+ # This model has additional requirements.
10
+ # Please install the following packages.
11
+ # pip install facexlib insightface onnxruntime
12
+ vram_config = {
13
+ "offload_dtype": torch.float8_e4m3fn,
14
+ "offload_device": "cpu",
15
+ "onload_dtype": torch.float8_e4m3fn,
16
+ "onload_device": "cpu",
17
+ "preparing_dtype": torch.float8_e4m3fn,
18
+ "preparing_device": "cuda",
19
+ "computation_dtype": torch.bfloat16,
20
+ "computation_device": "cuda",
21
+ }
22
+ snapshot_download(
23
+ "ByteDance/InfiniteYou",
24
+ allow_file_pattern="supports/insightface/models/antelopev2/*",
25
+ local_dir="models/ByteDance/InfiniteYou",
26
+ )
27
+ pipe = FluxImagePipeline.from_pretrained(
28
+ torch_dtype=torch.bfloat16,
29
+ device="cuda",
30
+ model_configs=[
31
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="flux1-dev.safetensors", **vram_config),
32
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder/model.safetensors", **vram_config),
33
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="text_encoder_2/*.safetensors", **vram_config),
34
+ ModelConfig(model_id="black-forest-labs/FLUX.1-dev", origin_file_pattern="ae.safetensors", **vram_config),
35
+ ModelConfig(model_id="ByteDance/InfiniteYou", origin_file_pattern="infu_flux_v1.0/aes_stage2/image_proj_model.bin", **vram_config),
36
+ ModelConfig(model_id="ByteDance/InfiniteYou", origin_file_pattern="infu_flux_v1.0/aes_stage2/InfuseNetModel/*.safetensors", **vram_config),
37
+ ],
38
+ vram_limit=torch.cuda.mem_get_info("cuda")[1] / (1024 ** 3) - 0.5,
39
+ )
40
+
41
+ dataset_snapshot_download(
42
+ dataset_id="DiffSynth-Studio/examples_in_diffsynth",
43
+ local_dir="./",
44
+ allow_file_pattern=f"data/examples/infiniteyou/*",
45
+ )
46
+
47
+ height, width = 1024, 1024
48
+ controlnet_image = Image.fromarray(np.zeros([height, width, 3]).astype(np.uint8))
49
+ controlnet_inputs = [ControlNetInput(image=controlnet_image, scale=1.0, processor_id="None")]
50
+
51
+ prompt = "A man, portrait, cinematic"
52
+ id_image = "data/examples/infiniteyou/man.jpg"
53
+ id_image = Image.open(id_image).convert('RGB')
54
+ image = pipe(
55
+ prompt=prompt, seed=1,
56
+ infinityou_id_image=id_image, infinityou_guidance=1.0,
57
+ controlnet_inputs=controlnet_inputs,
58
+ num_inference_steps=50, embedded_guidance=3.5,
59
+ height=height, width=width,
60
+ )
61
+ image.save("man.jpg")
62
+
63
+ prompt = "A woman, portrait, cinematic"
64
+ id_image = "data/examples/infiniteyou/woman.jpg"
65
+ id_image = Image.open(id_image).convert('RGB')
66
+ image = pipe(
67
+ prompt=prompt, seed=1,
68
+ infinityou_id_image=id_image, infinityou_guidance=1.0,
69
+ controlnet_inputs=controlnet_inputs,
70
+ num_inference_steps=50, embedded_guidance=3.5,
71
+ height=height, width=width,
72
+ )
73
+ image.save("woman.jpg")