Skip to content

Commit bf1c996

Browse files
authored
Merge pull request #308 from mi804/eligen
fix bug for enable_eligen_on_negative
2 parents 3423190 + c2478ff commit bf1c996

File tree

8 files changed

+103
-55
lines changed

8 files changed

+103
-55
lines changed

README.md

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -34,9 +34,9 @@ Until now, DiffSynth Studio has supported the following models:
3434
* [Stable Diffusion](https://huggingface.co/runwayml/stable-diffusion-v1-5)
3535

3636
## News
37-
- **December 31, 2024** We propose EliGen, a novel framework for precise entity-level controlled text-to-image generation, complemented by an inpainting fusion pipeline to extend its capabilities to image inpainting tasks. EliGen seamlessly integrates with existing community models, such as IP-Adapter, enhancing its versatility. For more details, see [./examples/EntityControl](./examples/EntityControl/README.md).
38-
* Paper: Comming soon
39-
* Github: https://github.com/modelscope/DiffSynth-Studio
37+
- **December 31, 2024** We propose EliGen, a novel framework for precise entity-level controlled text-to-image generation, complemented by an inpainting fusion pipeline to extend its capabilities to image inpainting tasks. EliGen seamlessly integrates with existing community models, such as IP-Adapter and In-Context LoRA, enhancing its versatility. For more details, see [./examples/EntityControl](./examples/EntityControl/).
38+
* Paper: [EliGen: Entity-Level Controlled Image Generation with Regional Attention](https://arxiv.org/abs/2501.01097)
39+
* Github: [DiffSynth-Studio](https://github.com/modelscope/DiffSynth-Studio)
4040
* Model: [ModelScope](https://www.modelscope.cn/models/DiffSynth-Studio/Eligen)
4141
* Training dataset: Coming soon
4242

apps/gradio/eligen_ui.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,7 @@
99

1010
def save_mask_prompts(masks, mask_prompts, global_prompt, seed=0, random_dir='0000000'):
1111
save_dir = os.path.join('workdirs/tmp_mask', random_dir)
12+
print(f'save to {save_dir}')
1213
os.makedirs(save_dir, exist_ok=True)
1314
for i, mask in enumerate(masks):
1415
save_path = os.path.join(save_dir, f'{i}.png')
@@ -205,8 +206,8 @@ def model_path_to_default_params(model_type, model_path, prompt, negative_prompt
205206
local_prompt = gr.Textbox(label="Local prompt", key=f"local_prompt_{painter_layer_id}")
206207
mask_scale = gr.Slider(minimum=0.0, maximum=5.0, value=1.0, step=0.1, interactive=True, label="Mask scale", key=f"mask_scale_{painter_layer_id}")
207208
canvas = gr.ImageEditor(canvas_size=(512, 1), sources=None, layers=False, interactive=True, image_mode="RGBA",
208-
brush=gr.Brush(default_size=30, default_color="#000000", colors=["#000000"]),
209-
label="Painter", key=f"canvas_{painter_layer_id}")
209+
brush=gr.Brush(default_size=50, default_color="#000000", colors=["#000000"]),
210+
label="Painter", key=f"canvas_{painter_layer_id}", width=width, height=height)
210211
@gr.on(inputs=[height, width, canvas], outputs=canvas, triggers=[height.change, width.change, canvas.clear, enable_local_prompt.change], show_progress="hidden")
211212
def resize_canvas(height, width, canvas):
212213
h, w = canvas["background"].shape[:2]

diffsynth/pipelines/flux_image.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -223,8 +223,8 @@ def prepare_eligen(self, prompt_emb_nega, eligen_entity_prompts, eligen_entity_m
223223
if eligen_entity_masks is not None:
224224
entity_prompt_emb_posi, entity_masks_posi, fg_mask, bg_mask = self.prepare_entity_inputs(eligen_entity_prompts, eligen_entity_masks, width, height, t5_sequence_length, enable_eligen_inpaint)
225225
if enable_eligen_on_negative and cfg_scale != 1.0:
226-
entity_prompt_emb_nega = prompt_emb_nega['prompt_emb'].unsqueeze(1).repeat(1, eligen_entity_masks.shape[1], 1, 1)
227-
entity_masks_nega = eligen_entity_masks
226+
entity_prompt_emb_nega = prompt_emb_nega['prompt_emb'].unsqueeze(1).repeat(1, entity_masks_posi.shape[1], 1, 1)
227+
entity_masks_nega = entity_masks_posi
228228
else:
229229
entity_prompt_emb_nega, entity_masks_nega = None, None
230230
else:

examples/EntityControl/README.md

Lines changed: 31 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -2,34 +2,36 @@
22

33
## Introduction
44

5-
We propose EliGen, a novel approach that leverages fine-grained entity-level information to enable precise and controllable text-to-image generation. EliGen excels in tasks such as entity-level controlled image generation and image inpainting, while its applicability is not limited to these areas. Additionally, it can be seamlessly integrated with existing community models, such as the IP-Adpater.
5+
We propose EliGen, a novel approach that leverages fine-grained entity-level information to enable precise and controllable text-to-image generation. EliGen excels in tasks such as entity-level controlled image generation and image inpainting, while its applicability is not limited to these areas. Additionally, it can be seamlessly integrated with existing community models, such as the IP-Adpater and In-Cotext LoRA.
66

7-
* Paper: Comming soon
8-
* Github: https://github.com/modelscope/DiffSynth-Studio
7+
* Paper: [EliGen: Entity-Level Controlled Image Generation with Regional Attention](https://arxiv.org/abs/2501.01097)
8+
* Github: [DiffSynth-Studio](https://github.com/modelscope/DiffSynth-Studio)
99
* Model: [ModelScope](https://www.modelscope.cn/models/DiffSynth-Studio/Eligen)
1010
* Training dataset: Coming soon
1111

1212
## Methodology
1313

1414
![regional-attention](https://github.com/user-attachments/assets/9a147201-15ab-421f-a6c5-701075754478)
1515

16-
We introduce a regional attention mechanism within the DiT framework to effectively process the conditions of each entity. This mechanism enables the local prompt associated with each entity to semantically influence specific regions through regional attention. To further enhance the layout control capabilities of EliGen, we meticulously curate an entity-annotated dataset and fine-tune the model using the LoRA framework.
16+
We introduce a regional attention mechanism within the DiT framework to effectively process the conditions of each entity. This mechanism enables the local prompt associated with each entity to semantically influence specific regions through regional attention. To further enhance the layout control capabilities of EliGen, we meticulously contribute an entity-annotated dataset and fine-tune the model using the LoRA framework.
1717

1818
1. **Regional Attention**: Regional attention is shown in above figure, which can be easily applied to other text-to-image models. Its core principle involves transforming the positional information of each entity into an attention mask, ensuring that the mechanism only affects the designated regions.
1919

20-
2. **Dataset with Entity Annotation**: To curate a dedicated entity control dataset, we start by randomly selecting captions from DiffusionDB and generating the corresponding source image using Flux. Next, we employ Qwen2-VL 72B, recognized for its advanced grounding capabilities among MLLMs, to randomly identify entities within the image. These entities are annotated with local prompts and bounding boxes for precise localization, forming the foundation of our dataset for further training.
20+
2. **Dataset with Entity Annotation**: To construct a dedicated entity control dataset, we start by randomly selecting captions from DiffusionDB and generating the corresponding source image using Flux. Next, we employ Qwen2-VL 72B, recognized for its advanced grounding capabilities among MLLMs, to randomly identify entities within the image. These entities are annotated with local prompts and bounding boxes for precise localization, forming the foundation of our dataset for further training.
2121

22-
3. **Training**: We apply LoRA and deepspeed to finetune regional attention with curated dataset, enabling our EliGen performing effective entity-level control.
22+
3. **Training**: We utilize LoRA (Low-Rank Adaptation) and DeepSpeed to fine-tune regional attention mechanisms using a curated dataset, enabling our EliGen model to achieve effective entity-level control.
2323

2424
## Usage
2525
1. **Entity-Level Controlled Image Generation**
26-
See [./entity_control.py](./entity_control.py) for usage.
26+
EliGen achieves effective entity-level control results. See [./entity_control.py](./entity_control.py) for usage.
2727
2. **Image Inpainting**
2828
To apply EliGen to image inpainting task, we propose a inpainting fusion pipeline to preserve the non-painting areas while enabling precise, entity-level modifications over inpaining regions.
2929
See [./entity_inpaint.py](./entity_inpaint.py) for usage.
3030
3. **Styled Entity Control**
3131
EliGen can be seamlessly integrated with existing community models. We have provided an example of how to integrate it with the IP-Adpater. See [./entity_control_ipadapter.py](./entity_control_ipadapter.py) for usage.
32-
4. **Play with EliGen using UI**
32+
4. **Entity Transfer**
33+
We have provided an example of how to integrate EliGen with In-Cotext LoRA, which achieves interesting entity transfer results. See [./entity_transfer.py](./entity_transfer.py) for usage.
34+
5. **Play with EliGen using UI**
3335
Download the checkpoint of EliGen from [ModelScope](https://www.modelscope.cn/models/DiffSynth-Studio/Eligen) to `models/lora/entity_control` and run the following command to try interactive UI:
3436
```bash
3537
python apps/gradio/entity_level_control.py
@@ -41,20 +43,34 @@ See [./entity_control.py](./entity_control.py) for usage.
4143

4244
https://github.com/user-attachments/assets/4fc76df1-b26a-46e8-a950-865cdf02a38d
4345

44-
2. The image generation effect of complex Entity combinations, demonstrating the strong generalization of EliGen.
46+
2. The image generation effect of complex Entity combinations, demonstrating the strong generalization of EliGen. See [./entity_control.py](./entity_control.py) `example_1-6` for generation prompts.
4547

46-
|![image_1_base](https://github.com/user-attachments/assets/b8564b28-19b5-424f-bf3c-6476f2923ff9)|![image_1_base](https://github.com/user-attachments/assets/20793715-42d3-46f7-8d62-0cb4cacef38d)|
48+
|![image_1_base](https://github.com/user-attachments/assets/4b9fb79f-cb3c-45a5-8d22-14e52865387c)|![image_1_base](https://github.com/user-attachments/assets/2e60e51b-f8d5-4b25-ae21-f64531e20b1b)|
4749
|-|-|
48-
|![image_1_base](https://github.com/user-attachments/assets/70ef12fe-d300-4b52-9d11-eabc9b5464a8)|![image_1_enhance](https://github.com/user-attachments/assets/7645ce0e-4aa7-4b1e-b7a7-bccfd9796461)|
49-
|![image_2_base](https://github.com/user-attachments/assets/2f1e44e1-8f1f-4c6e-ab7a-1b6861a33a69)|![image_2_enhance](https://github.com/user-attachments/assets/faf78498-57ba-41bd-b516-570c86984515)|
50-
|![image_3_base](https://github.com/user-attachments/assets/206d1cef-2e96-4469-aed5-cdeb06ab9e99)|![image_3_enhance](https://github.com/user-attachments/assets/75d784d6-d5a1-474f-a5d5-ef8074135f35)|
50+
|![image_1_base](https://github.com/user-attachments/assets/5bdfebc2-8c1e-4619-87f3-579883a3671e)|![image_1_enhance](https://github.com/user-attachments/assets/d38be37d-68ed-4123-9cb2-429069dbd870)|
51+
|![image_2_base](https://github.com/user-attachments/assets/e4b37440-fde0-4d7c-9658-98995d335097)|![image_2_enhance](https://github.com/user-attachments/assets/aa4ccae9-1074-4200-b890-5687f3409a70)|
52+
53+
3. Demonstration of the robustness of EliGen. The following examples are generated using the same prompt but different seeds. Refer to [./entity_control.py](./entity_control.py) `example_7` for the prompts.
54+
55+
|![image_1_base](https://github.com/user-attachments/assets/fb39ca42-074b-4d7c-85c8-55e4dec9a851)|![image_1_base](https://github.com/user-attachments/assets/34d7f17a-06b6-492a-8522-44aa1c75f233)|
56+
|-|-|
57+
|![image_1_base](https://github.com/user-attachments/assets/cecfee76-7e44-496b-8d02-ffa29f5142a3)|![image_1_enhance](https://github.com/user-attachments/assets/a51d3bba-52e6-483f-9c75-f7e87120b30c)|
58+
5159
### Image Inpainting
60+
Demonstration of the inpainting mode of EliGen, see [./entity_inpaint.py](./entity_inpaint.py) for generation prompts.
5261
|Inpainting Input|Inpainting Output|
5362
|-|-|
63+
|![image_2_base](https://github.com/user-attachments/assets/5ef499f3-3d8a-49cc-8ceb-86af7f5cb9f8)|![image_2_enhance](https://github.com/user-attachments/assets/88fc3bde-0984-4b3c-8ca9-d63de660855b)|
5464
|![image_1_base](https://github.com/user-attachments/assets/5f74c710-bf30-4db1-ae40-a1e1995ccef6)|![image_1_enhance](https://github.com/user-attachments/assets/1cd71177-e956-46d3-86ce-06f774c96efd)|
55-
|![image_2_base](https://github.com/user-attachments/assets/5ef499f3-3d8a-49cc-8ceb-86af7f5cb9f8)|![image_2_enhance](https://github.com/user-attachments/assets/fb967035-7b28-466c-a753-c00135559121)|
5665
### Styled Entity Control
66+
Demonstration of the styled entity control results with EliGen and IP-Adapter, see [./entity_control_ipadapter.py](./entity_control_ipadapter.py) for generation prompts.
5767
|Style Reference|Entity Control Variance 1|Entity Control Variance 2|Entity Control Variance 3|
5868
|-|-|-|-|
5969
|![image_1_base](https://github.com/user-attachments/assets/5e2dd3ab-37d3-4f58-8e02-ee2f9b238604)|![image_1_enhance](https://github.com/user-attachments/assets/0f6711a2-572a-41b3-938a-95deff6d732d)|![image_1_enhance](https://github.com/user-attachments/assets/ce2e66e5-1fdf-44e8-bca7-555d805a50b1)|![image_1_enhance](https://github.com/user-attachments/assets/ad2da233-2f7c-4065-ab57-b2d84dc2c0e2)|
60-
|![image_2_base](https://github.com/user-attachments/assets/77cf7ceb-48e3-442d-8ffc-5fa4a10fe81a)|![image_2_enhance](https://github.com/user-attachments/assets/59a4f3c2-e59d-40c7-886c-0768f14fcc89)|![image_2_enhance](https://github.com/user-attachments/assets/a9187fb0-489a-49c9-a52f-56b1bd96faf7)|![image_2_enhance](https://github.com/user-attachments/assets/a62caee4-3863-4b56-96ff-e0785c6d93bb)|
70+
71+
### Entity Transfer
72+
Demonstration of the entity transfer results with EliGen and In-Context LoRA, see [./entity_transfer.py](./entity_transfer.py) for generation prompts.
73+
74+
|Entity to Transfer|Transfer Target Image|Transfer Example 1|Transfer Example 2|
75+
|-|-|-|-|
76+
|![image_1_base](https://github.com/user-attachments/assets/bb3d4a46-8d82-4d3c-bce8-8c01a9973b8d)|![image_1_enhance](https://github.com/user-attachments/assets/44c0f422-525e-42ca-991b-f407f8faafc3)|![image_1_enhance](https://github.com/user-attachments/assets/a042ff5b-2748-4d91-8321-cec8f9eb73e4)|![image_1_enhance](https://github.com/user-attachments/assets/98f2d1b1-16e1-4c8f-b521-5cd68b567293)|

examples/EntityControl/entity_control.py

Lines changed: 53 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,26 @@
44
from PIL import Image
55
import torch
66

7+
def example(pipe, seeds, example_id, global_prompt, entity_prompts):
8+
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")
9+
masks = [Image.open(f"./data/examples/eligen/entity_control/example_{example_id}/{i}.png").convert('RGB') for i in range(len(entity_prompts))]
10+
negative_prompt = "worst quality, low quality, monochrome, zombie, interlocked fingers, Aissist, cleavage, nsfw,"
11+
for seed in seeds:
12+
# generate image
13+
image = pipe(
14+
prompt=global_prompt,
15+
cfg_scale=3.0,
16+
negative_prompt=negative_prompt,
17+
num_inference_steps=50,
18+
embedded_guidance=3.5,
19+
seed=seed,
20+
height=1024,
21+
width=1024,
22+
eligen_entity_prompts=entity_prompts,
23+
eligen_entity_masks=masks,
24+
)
25+
image.save(f"eligen_example_{example_id}_{seed}.png")
26+
visualize_masks(image, masks, entity_prompts, f"eligen_example_{example_id}_mask_{seed}.png")
727

828
# download and load model
929
model_manager = ModelManager(torch_dtype=torch.bfloat16, device="cuda", model_id_list=["FLUX.1-dev"])
@@ -17,27 +37,38 @@
1737
)
1838
pipe = FluxImagePipeline.from_model_manager(model_manager)
1939

20-
# download and load mask images
21-
dataset_snapshot_download(dataset_id="DiffSynth-Studio/examples_in_diffsynth", local_dir="./", allow_file_pattern="data/examples/eligen/mask*")
22-
masks = [Image.open(f"./data/examples/eligen/mask{i}.png") for i in range(1, 8)]
40+
# example 1
41+
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"
42+
entity_prompts = ["cliff", "sea", "moon", "sailing boat", "a seated beautiful woman", "pale blue long dress with soft glow"]
43+
example(pipe, [0], 1, global_prompt, entity_prompts)
2344

24-
entity_prompts = ["A beautiful woman", "mirror", "necklace", "glasses", "earring", "white dress", "jewelry headpiece"]
45+
# example 2
46+
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."
47+
entity_prompts = ["flowing hair", "sword glowing with red flame", "A cute bird", "blue belt"]
48+
example(pipe, [0], 2, global_prompt, entity_prompts)
49+
50+
# example 3
51+
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,"
52+
entity_prompts = ["ancient palace", "stone staircase with railings", "a traditional monk", "a traditional monk"]
53+
example(pipe, [27], 3, global_prompt, entity_prompts)
54+
55+
# example 4
56+
global_prompt = "A beautiful girl wearing shirt and shorts in the street, holding a sign 'Entity Control'"
57+
entity_prompts = ["A beautiful girl", "sign 'Entity Control'", "shorts", "shirt"]
58+
example(pipe, [21], 4, global_prompt, entity_prompts)
59+
60+
# example 5
61+
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."
62+
entity_prompts = ["crescent yellow moon", "a solitary woman", "water", "swirling blue clouds"]
63+
example(pipe, [0], 5, global_prompt, entity_prompts)
64+
65+
# example 6
66+
global_prompt = "Snow White and the 6 Dwarfs."
67+
entity_prompts = ["Dwarf 1", "Dwarf 2", "Dwarf 3", "Snow White", "Dwarf 4", "Dwarf 5", "Dwarf 6"]
68+
example(pipe, [8], 6, global_prompt, entity_prompts)
69+
70+
# example 7, same prompt with different seeds
71+
seeds = range(5, 9)
2572
global_prompt = "A beautiful woman wearing white dress, holding a mirror, with a warm light background;"
26-
negative_prompt = "worst quality, low quality, monochrome, zombie, interlocked fingers, Aissist, cleavage, nsfw"
27-
28-
# generate image
29-
image = pipe(
30-
prompt=global_prompt,
31-
cfg_scale=3.0,
32-
negative_prompt=negative_prompt,
33-
num_inference_steps=50,
34-
embedded_guidance=3.5,
35-
seed=4,
36-
height=1024,
37-
width=1024,
38-
eligen_entity_prompts=entity_prompts,
39-
eligen_entity_masks=masks,
40-
enable_eligen_on_negative=False,
41-
)
42-
image.save(f"entity_control.png")
43-
visualize_masks(image, masks, entity_prompts, f"entity_control_with_mask.png")
73+
entity_prompts = ["A beautiful woman", "mirror", "necklace", "glasses", "earring", "white dress", "jewelry headpiece"]
74+
example(pipe, seeds, 7, global_prompt, entity_prompts)

0 commit comments

Comments
 (0)