Skip to content

Commit 564079f

Browse files
authored
[feat]: implement "local" caption upsampling for Flux.2 (#12718)
* feat: implement caption upsampling for flux.2. * doc * up * fix * up * fix system prompts 🤷‍ * up * up * up
1 parent 394a48d commit 564079f

File tree

5 files changed

+255
-23
lines changed

5 files changed

+255
-23
lines changed

docs/source/en/api/pipelines/flux2.md

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,12 @@ Original model checkpoints for Flux can be found [here](https://huggingface.co/b
2626
>
2727
> [Caching](../../optimization/cache) may also speed up inference by storing and reusing intermediate outputs.
2828
29+
## Caption upsampling
30+
31+
Flux.2 can potentially generate better better outputs with better prompts. We can "upsample"
32+
an input prompt by setting the `caption_upsample_temperature` argument in the pipeline call arguments.
33+
The [official implementation](https://github.com/black-forest-labs/flux2/blob/5a5d316b1b42f6b59a8c9194b77c8256be848432/src/flux2/text_encoder.py#L140) recommends this value to be 0.15.
34+
2935
## Flux2Pipeline
3036

3137
[[autodoc]] Flux2Pipeline

pyproject.toml

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
[tool.ruff]
22
line-length = 119
3+
extend-exclude = [
4+
"src/diffusers/pipelines/flux2/system_messages.py",
5+
]
36

47
[tool.ruff.lint]
58
# Never enforce `E501` (line length violations).

src/diffusers/pipelines/flux2/image_processor.py

Lines changed: 42 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@
1313
# limitations under the License.
1414

1515
import math
16-
from typing import Tuple
16+
from typing import List
1717

1818
import PIL.Image
1919

@@ -98,7 +98,7 @@ def check_image_input(
9898
return image
9999

100100
@staticmethod
101-
def _resize_to_target_area(image: PIL.Image.Image, target_area: int = 1024 * 1024) -> Tuple[int, int]:
101+
def _resize_to_target_area(image: PIL.Image.Image, target_area: int = 1024 * 1024) -> PIL.Image.Image:
102102
image_width, image_height = image.size
103103

104104
scale = math.sqrt(target_area / (image_width * image_height))
@@ -107,6 +107,14 @@ def _resize_to_target_area(image: PIL.Image.Image, target_area: int = 1024 * 102
107107

108108
return image.resize((width, height), PIL.Image.Resampling.LANCZOS)
109109

110+
@staticmethod
111+
def _resize_if_exceeds_area(image, target_area=1024 * 1024) -> PIL.Image.Image:
112+
image_width, image_height = image.size
113+
pixel_count = image_width * image_height
114+
if pixel_count <= target_area:
115+
return image
116+
return Flux2ImageProcessor._resize_to_target_area(image, target_area)
117+
110118
def _resize_and_crop(
111119
self,
112120
image: PIL.Image.Image,
@@ -136,3 +144,35 @@ def _resize_and_crop(
136144
bottom = top + height
137145

138146
return image.crop((left, top, right, bottom))
147+
148+
# Taken from
149+
# https://github.com/black-forest-labs/flux2/blob/5a5d316b1b42f6b59a8c9194b77c8256be848432/src/flux2/sampling.py#L310C1-L339C19
150+
@staticmethod
151+
def concatenate_images(images: List[PIL.Image.Image]) -> PIL.Image.Image:
152+
"""
153+
Concatenate a list of PIL images horizontally with center alignment and white background.
154+
"""
155+
156+
# If only one image, return a copy of it
157+
if len(images) == 1:
158+
return images[0].copy()
159+
160+
# Convert all images to RGB if not already
161+
images = [img.convert("RGB") if img.mode != "RGB" else img for img in images]
162+
163+
# Calculate dimensions for horizontal concatenation
164+
total_width = sum(img.width for img in images)
165+
max_height = max(img.height for img in images)
166+
167+
# Create new image with white background
168+
background_color = (255, 255, 255)
169+
new_img = PIL.Image.new("RGB", (total_width, max_height), background_color)
170+
171+
# Paste images with center alignment
172+
x_offset = 0
173+
for img in images:
174+
y_offset = (max_height - img.height) // 2
175+
new_img.paste(img, (x_offset, y_offset))
176+
x_offset += img.width
177+
178+
return new_img

src/diffusers/pipelines/flux2/pipeline_flux2.py

Lines changed: 171 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from ..pipeline_utils import DiffusionPipeline
2929
from .image_processor import Flux2ImageProcessor
3030
from .pipeline_output import Flux2PipelineOutput
31+
from .system_messages import SYSTEM_MESSAGE, SYSTEM_MESSAGE_UPSAMPLING_I2I, SYSTEM_MESSAGE_UPSAMPLING_T2I
3132

3233

3334
if is_torch_xla_available():
@@ -56,25 +57,105 @@
5657
```
5758
"""
5859

60+
UPSAMPLING_MAX_IMAGE_SIZE = 768**2
5961

60-
def format_text_input(prompts: List[str], system_message: str = None):
62+
63+
# Adapted from
64+
# https://github.com/black-forest-labs/flux2/blob/5a5d316b1b42f6b59a8c9194b77c8256be848432/src/flux2/text_encoder.py#L68
65+
def format_input(
66+
prompts: List[str],
67+
system_message: str = SYSTEM_MESSAGE,
68+
images: Optional[Union[List[PIL.Image.Image], List[List[PIL.Image.Image]]]] = None,
69+
):
70+
"""
71+
Format a batch of text prompts into the conversation format expected by apply_chat_template. Optionally, add images
72+
to the input.
73+
74+
Args:
75+
prompts: List of text prompts
76+
system_message: System message to use (default: CREATIVE_SYSTEM_MESSAGE)
77+
images (optional): List of images to add to the input.
78+
79+
Returns:
80+
List of conversations, where each conversation is a list of message dicts
81+
"""
6182
# Remove [IMG] tokens from prompts to avoid Pixtral validation issues
6283
# when truncation is enabled. The processor counts [IMG] tokens and fails
6384
# if the count changes after truncation.
6485
cleaned_txt = [prompt.replace("[IMG]", "") for prompt in prompts]
6586

66-
return [
67-
[
68-
{
69-
"role": "system",
70-
"content": [{"type": "text", "text": system_message}],
71-
},
72-
{"role": "user", "content": [{"type": "text", "text": prompt}]},
87+
if images is None or len(images) == 0:
88+
return [
89+
[
90+
{
91+
"role": "system",
92+
"content": [{"type": "text", "text": system_message}],
93+
},
94+
{"role": "user", "content": [{"type": "text", "text": prompt}]},
95+
]
96+
for prompt in cleaned_txt
7397
]
74-
for prompt in cleaned_txt
98+
else:
99+
assert len(images) == len(prompts), "Number of images must match number of prompts"
100+
messages = [
101+
[
102+
{
103+
"role": "system",
104+
"content": [{"type": "text", "text": system_message}],
105+
},
106+
]
107+
for _ in cleaned_txt
108+
]
109+
110+
for i, (el, images) in enumerate(zip(messages, images)):
111+
# optionally add the images per batch element.
112+
if images is not None:
113+
el.append(
114+
{
115+
"role": "user",
116+
"content": [{"type": "image", "image": image_obj} for image_obj in images],
117+
}
118+
)
119+
# add the text.
120+
el.append(
121+
{
122+
"role": "user",
123+
"content": [{"type": "text", "text": cleaned_txt[i]}],
124+
}
125+
)
126+
127+
return messages
128+
129+
130+
# Adapted from
131+
# https://github.com/black-forest-labs/flux2/blob/5a5d316b1b42f6b59a8c9194b77c8256be848432/src/flux2/text_encoder.py#L49C5-L66C19
132+
def _validate_and_process_images(
133+
images: List[List[PIL.Image.Image]] | List[PIL.Image.Image],
134+
image_processor: Flux2ImageProcessor,
135+
upsampling_max_image_size: int,
136+
) -> List[List[PIL.Image.Image]]:
137+
# Simple validation: ensure it's a list of PIL images or list of lists of PIL images
138+
if not images:
139+
return []
140+
141+
# Check if it's a list of lists or a list of images
142+
if isinstance(images[0], PIL.Image.Image):
143+
# It's a list of images, convert to list of lists
144+
images = [[im] for im in images]
145+
146+
# potentially concatenate multiple images to reduce the size
147+
images = [[image_processor.concatenate_images(img_i)] if len(img_i) > 1 else img_i for img_i in images]
148+
149+
# cap the pixels
150+
images = [
151+
[image_processor._resize_if_exceeds_area(img_i, upsampling_max_image_size) for img_i in img_i]
152+
for img_i in images
75153
]
154+
return images
76155

77156

157+
# Taken from
158+
# https://github.com/black-forest-labs/flux2/blob/5a5d316b1b42f6b59a8c9194b77c8256be848432/src/flux2/sampling.py#L251
78159
def compute_empirical_mu(image_seq_len: int, num_steps: int) -> float:
79160
a1, b1 = 8.73809524e-05, 1.89833333
80161
a2, b2 = 0.00016927, 0.45666666
@@ -214,9 +295,10 @@ def __init__(
214295
self.tokenizer_max_length = 512
215296
self.default_sample_size = 128
216297

217-
# fmt: off
218-
self.system_message = "You are an AI that reasons about image descriptions. You give structured responses focusing on object relationships, object attribution and actions without speculation."
219-
# fmt: on
298+
self.system_message = SYSTEM_MESSAGE
299+
self.system_message_upsampling_t2i = SYSTEM_MESSAGE_UPSAMPLING_T2I
300+
self.system_message_upsampling_i2i = SYSTEM_MESSAGE_UPSAMPLING_I2I
301+
self.upsampling_max_image_size = UPSAMPLING_MAX_IMAGE_SIZE
220302

221303
@staticmethod
222304
def _get_mistral_3_small_prompt_embeds(
@@ -226,9 +308,7 @@ def _get_mistral_3_small_prompt_embeds(
226308
dtype: Optional[torch.dtype] = None,
227309
device: Optional[torch.device] = None,
228310
max_sequence_length: int = 512,
229-
# fmt: off
230-
system_message: str = "You are an AI that reasons about image descriptions. You give structured responses focusing on object relationships, object attribution and actions without speculation.",
231-
# fmt: on
311+
system_message: str = SYSTEM_MESSAGE,
232312
hidden_states_layers: List[int] = (10, 20, 30),
233313
):
234314
dtype = text_encoder.dtype if dtype is None else dtype
@@ -237,7 +317,7 @@ def _get_mistral_3_small_prompt_embeds(
237317
prompt = [prompt] if isinstance(prompt, str) else prompt
238318

239319
# Format input messages
240-
messages_batch = format_text_input(prompts=prompt, system_message=system_message)
320+
messages_batch = format_input(prompts=prompt, system_message=system_message)
241321

242322
# Process all messages at once
243323
inputs = tokenizer.apply_chat_template(
@@ -426,6 +506,68 @@ def _unpack_latents_with_ids(x: torch.Tensor, x_ids: torch.Tensor) -> list[torch
426506

427507
return torch.stack(x_list, dim=0)
428508

509+
def upsample_prompt(
510+
self,
511+
prompt: Union[str, List[str]],
512+
images: Union[List[PIL.Image.Image], List[List[PIL.Image.Image]]] = None,
513+
temperature: float = 0.15,
514+
device: torch.device = None,
515+
) -> List[str]:
516+
prompt = [prompt] if isinstance(prompt, str) else prompt
517+
device = self.text_encoder.device if device is None else device
518+
519+
# Set system message based on whether images are provided
520+
if images is None or len(images) == 0 or images[0] is None:
521+
system_message = SYSTEM_MESSAGE_UPSAMPLING_T2I
522+
else:
523+
system_message = SYSTEM_MESSAGE_UPSAMPLING_I2I
524+
525+
# Validate and process the input images
526+
if images:
527+
images = _validate_and_process_images(images, self.image_processor, self.upsampling_max_image_size)
528+
529+
# Format input messages
530+
messages_batch = format_input(prompts=prompt, system_message=system_message, images=images)
531+
532+
# Process all messages at once
533+
# with image processing a too short max length can throw an error in here.
534+
inputs = self.tokenizer.apply_chat_template(
535+
messages_batch,
536+
add_generation_prompt=True,
537+
tokenize=True,
538+
return_dict=True,
539+
return_tensors="pt",
540+
padding="max_length",
541+
truncation=True,
542+
max_length=2048,
543+
)
544+
545+
# Move to device
546+
inputs["input_ids"] = inputs["input_ids"].to(device)
547+
inputs["attention_mask"] = inputs["attention_mask"].to(device)
548+
549+
if "pixel_values" in inputs:
550+
inputs["pixel_values"] = inputs["pixel_values"].to(device, self.text_encoder.dtype)
551+
552+
# Generate text using the model's generate method
553+
generated_ids = self.text_encoder.generate(
554+
**inputs,
555+
max_new_tokens=512,
556+
do_sample=True,
557+
temperature=temperature,
558+
use_cache=True,
559+
)
560+
561+
# Decode only the newly generated tokens (skip input tokens)
562+
# Extract only the generated portion
563+
input_length = inputs["input_ids"].shape[1]
564+
generated_tokens = generated_ids[:, input_length:]
565+
566+
upsampled_prompt = self.tokenizer.tokenizer.batch_decode(
567+
generated_tokens, skip_special_tokens=True, clean_up_tokenization_spaces=True
568+
)
569+
return upsampled_prompt
570+
429571
def encode_prompt(
430572
self,
431573
prompt: Union[str, List[str]],
@@ -620,6 +762,7 @@ def __call__(
620762
callback_on_step_end_tensor_inputs: List[str] = ["latents"],
621763
max_sequence_length: int = 512,
622764
text_encoder_out_layers: Tuple[int] = (10, 20, 30),
765+
caption_upsample_temperature: float = None,
623766
):
624767
r"""
625768
Function invoked when calling the pipeline for generation.
@@ -635,11 +778,11 @@ def __call__(
635778
The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
636779
instead.
637780
guidance_scale (`float`, *optional*, defaults to 1.0):
638-
Guidance scale as defined in [Classifier-Free Diffusion
639-
Guidance](https://huggingface.co/papers/2207.12598). `guidance_scale` is defined as `w` of equation 2.
640-
of [Imagen Paper](https://huggingface.co/papers/2205.11487). Guidance scale is enabled by setting
641-
`guidance_scale > 1`. Higher guidance scale encourages to generate images that are closely linked to
642-
the text `prompt`, usually at the expense of lower image quality.
781+
Embedded guiddance scale is enabled by setting `guidance_scale` > 1. Higher `guidance_scale` encourages
782+
a model to generate images more aligned with `prompt` at the expense of lower image quality.
783+
784+
Guidance-distilled models approximates true classifer-free guidance for `guidance_scale` > 1. Refer to
785+
the [paper](https://huggingface.co/papers/2210.03142) to learn more.
643786
height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
644787
The height in pixels of the generated image. This is set to 1024 by default for the best results.
645788
width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
@@ -684,6 +827,9 @@ def __call__(
684827
max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
685828
text_encoder_out_layers (`Tuple[int]`):
686829
Layer indices to use in the `text_encoder` to derive the final prompt embeddings.
830+
caption_upsample_temperature (`float`):
831+
When specified, we will try to perform caption upsampling for potentially improved outputs. We
832+
recommend setting it to 0.15 if caption upsampling is to be performed.
687833
688834
Examples:
689835
@@ -718,6 +864,10 @@ def __call__(
718864
device = self._execution_device
719865

720866
# 3. prepare text embeddings
867+
if caption_upsample_temperature:
868+
prompt = self.upsample_prompt(
869+
prompt, images=image, temperature=caption_upsample_temperature, device=device
870+
)
721871
prompt_embeds, text_ids = self.encode_prompt(
722872
prompt=prompt,
723873
prompt_embeds=prompt_embeds,
Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
# docstyle-ignore
2+
"""
3+
These system prompts come from:
4+
https://github.com/black-forest-labs/flux2/blob/5a5d316b1b42f6b59a8c9194b77c8256be848432/src/flux2/system_messages.py#L54
5+
"""
6+
7+
# docstyle-ignore
8+
SYSTEM_MESSAGE = """You are an AI that reasons about image descriptions. You give structured responses focusing on object relationships, object
9+
attribution and actions without speculation."""
10+
11+
# docstyle-ignore
12+
SYSTEM_MESSAGE_UPSAMPLING_T2I = """You are an expert prompt engineer for FLUX.2 by Black Forest Labs. Rewrite user prompts to be more descriptive while strictly preserving their core subject and intent.
13+
14+
Guidelines:
15+
1. Structure: Keep structured inputs structured (enhance within fields). Convert natural language to detailed paragraphs.
16+
2. Details: Add concrete visual specifics - form, scale, textures, materials, lighting (quality, direction, color), shadows, spatial relationships, and environmental context.
17+
3. Text in Images: Put ALL text in quotation marks, matching the prompt's language. Always provide explicit quoted text for objects that would contain text in reality (signs, labels, screens, etc.) - without it, the model generates gibberish.
18+
19+
Output only the revised prompt and nothing else."""
20+
21+
# docstyle-ignore
22+
SYSTEM_MESSAGE_UPSAMPLING_I2I = """You are FLUX.2 by Black Forest Labs, an image-editing expert. You convert editing requests into one concise instruction (50-80 words, ~30 for brief requests).
23+
24+
Rules:
25+
- Single instruction only, no commentary
26+
- Use clear, analytical language (avoid "whimsical," "cascading," etc.)
27+
- Specify what changes AND what stays the same (face, lighting, composition)
28+
- Reference actual image elements
29+
- Turn negatives into positives ("don't change X" → "keep X")
30+
- Make abstractions concrete ("futuristic" → "glowing cyan neon, metallic panels")
31+
- Keep content PG-13
32+
33+
Output only the final instruction in plain text and nothing else."""

0 commit comments

Comments
 (0)