Abe commited on
Commit
1803c22
·
1 Parent(s): e72dc2e

clean deploy HF

Browse files
Files changed (6) hide show
  1. .gitignore +2 -0
  2. README.md +4 -2
  3. app.py +196 -0
  4. app_hf.py +194 -0
  5. pipeline.py +440 -0
  6. requirements.txt +14 -0
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ .idea
2
+ .venv
README.md CHANGED
@@ -5,9 +5,11 @@ colorFrom: indigo
5
  colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 5.29.0
8
- app_file: app.py
9
  pinned: false
10
  license: other
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
5
  colorTo: yellow
6
  sdk: gradio
7
  sdk_version: 5.29.0
8
+ app_file: app_hf.py
9
  pinned: false
10
  license: other
11
  ---
12
 
13
+ Flex.2-Preview experiment by [JustLab.ai](https://justlab.ai)
14
+
15
+ Credits to [Ostris](https://huggingface.co/ostris) for this amazing all-in-one model
app.py ADDED
@@ -0,0 +1,196 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import torch
3
+ from diffusers import DiffusionPipeline
4
+ import gc
5
+ from pipeline import Flex2Pipeline
6
+
7
+ # Global variable to store the pipeline
8
+ pipe = None
9
+
10
+ def load_model(model_id="ostris/Flex.2-preview", device="cuda"):
11
+ """Load and cache the model to avoid reloading for each inference"""
12
+ global pipe
13
+
14
+ if pipe is None:
15
+ print(f"Loading {model_id}...")
16
+ try:
17
+ # Load the model components directly using DiffusionPipeline
18
+ # This avoids trying to use custom_pipeline which is causing issues
19
+ components = DiffusionPipeline.from_pretrained(
20
+ model_id,
21
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32
22
+ ).components
23
+
24
+ # Create our custom Flex2Pipeline with the components
25
+ pipe = Flex2Pipeline(
26
+ scheduler=components["scheduler"],
27
+ vae=components["vae"],
28
+ text_encoder=components["text_encoder"],
29
+ tokenizer=components["tokenizer"],
30
+ text_encoder_2=components["text_encoder_2"],
31
+ tokenizer_2=components["tokenizer_2"],
32
+ transformer=components["transformer"],
33
+ )
34
+
35
+ # Move to device
36
+ pipe = pipe.to(device)
37
+ print("Model loaded successfully!")
38
+ except Exception as e:
39
+ print(f"Error loading model: {e}")
40
+ return None
41
+
42
+ # Enable TF32 precision if available
43
+ if torch.cuda.is_available():
44
+ torch.backends.cuda.matmul.allow_tf32 = True
45
+ torch.backends.cudnn.allow_tf32 = True
46
+
47
+ return pipe
48
+
49
+ def clear_gpu_memory():
50
+ """Clear GPU memory"""
51
+ global pipe
52
+ if pipe is not None:
53
+ del pipe
54
+ pipe = None
55
+ gc.collect()
56
+ if torch.cuda.is_available():
57
+ torch.cuda.empty_cache()
58
+ torch.cuda.ipc_collect()
59
+ return "GPU memory cleared"
60
+
61
+ def generate_image(
62
+ prompt,
63
+ prompt_2=None,
64
+ inpaint_image=None,
65
+ inpaint_mask=None,
66
+ control_image=None,
67
+ control_strength=1.0,
68
+ control_stop=1.0,
69
+ height=1024,
70
+ width=1024,
71
+ num_inference_steps=28,
72
+ guidance_scale=3.5,
73
+ seed=-1,
74
+ progress=gr.Progress()
75
+ ):
76
+ """Generate image using Flex2Pipeline"""
77
+ global pipe
78
+
79
+ # Load model if not already loaded
80
+ pipe = load_model()
81
+ if pipe is None:
82
+ return None, "Error: Failed to load the model. Please check logs."
83
+
84
+ # Prepare generator for deterministic output
85
+ generator = None
86
+ if seed != -1:
87
+ generator = torch.Generator("cuda" if torch.cuda.is_available() else "cpu").manual_seed(seed)
88
+ else:
89
+ # Generate a random seed
90
+ seed = torch.randint(0, 2**32 - 1, (1,)).item()
91
+ generator = torch.Generator("cuda" if torch.cuda.is_available() else "cpu").manual_seed(seed)
92
+
93
+ # Create callback for progress updates
94
+ def callback_on_step_end(pipe, i, t, callback_kwargs):
95
+ progress((i + 1) / pipe._num_timesteps)
96
+ return callback_kwargs
97
+
98
+ try:
99
+ # Run the pipeline
100
+ output = pipe(
101
+ prompt=prompt,
102
+ prompt_2=prompt_2 if prompt_2 and prompt_2.strip() else None,
103
+ inpaint_image=inpaint_image,
104
+ inpaint_mask=inpaint_mask,
105
+ control_image=control_image,
106
+ control_strength=float(control_strength),
107
+ control_stop=float(control_stop),
108
+ height=height,
109
+ width=width,
110
+ num_inference_steps=num_inference_steps,
111
+ guidance_scale=guidance_scale,
112
+ generator=generator,
113
+ callback_on_step_end=callback_on_step_end,
114
+ )
115
+
116
+ # Return the generated image and success message
117
+ return output.images[0], f"Successfully generated image with seed: {seed}"
118
+
119
+ except Exception as e:
120
+ error_message = f"Error during image generation: {str(e)}"
121
+ print(error_message)
122
+ return None, error_message
123
+
124
+ # Create Gradio Interface
125
+ with gr.Blocks() as demo:
126
+ gr.Markdown("# Flex.2 Image Generator")
127
+
128
+ with gr.Row():
129
+ with gr.Column(scale=1):
130
+ # Input parameters
131
+ prompt = gr.Textbox(label="Prompt", placeholder="Enter your prompt here...", lines=3)
132
+ prompt_2 = gr.Textbox(label="Secondary Prompt (Optional)", placeholder="Optional secondary prompt...", lines=2)
133
+
134
+ with gr.Accordion("Image Settings", open=True):
135
+ with gr.Row():
136
+ height = gr.Slider(minimum=256, maximum=1536, value=1024, step=64, label="Height")
137
+ width = gr.Slider(minimum=256, maximum=1536, value=1024, step=64, label="Width")
138
+ with gr.Row():
139
+ num_inference_steps = gr.Slider(minimum=1, maximum=100, value=28, step=1, label="Inference Steps")
140
+ guidance_scale = gr.Slider(minimum=1.0, maximum=20.0, value=3.5, step=0.1, label="Guidance Scale")
141
+ seed = gr.Number(label="Seed (-1 for random)", value=-1)
142
+
143
+ with gr.Accordion("Control Settings", open=False):
144
+ control_image = gr.Image(label="Control Image (Optional)", type="pil")
145
+ with gr.Row():
146
+ control_strength = gr.Slider(minimum=0.0, maximum=2.0, value=1.0, step=0.05, label="Control Strength")
147
+ control_stop = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.05, label="Control Stop")
148
+
149
+ with gr.Accordion("Inpainting Settings", open=False):
150
+ inpaint_image = gr.Image(label="Initial Image for Inpainting", type="pil")
151
+ inpaint_mask = gr.Image(label="Mask Image (White areas will be inpainted)", type="pil")
152
+
153
+ # Generate button
154
+ generate_button = gr.Button("Generate Image", variant="primary")
155
+
156
+ # Clear GPU memory button
157
+ clear_button = gr.Button("Clear GPU Memory")
158
+
159
+ # Status message
160
+ status_message = gr.Textbox(label="Status", interactive=False)
161
+
162
+ with gr.Column(scale=1):
163
+ # Output image
164
+ output_image = gr.Image(label="Generated Image")
165
+
166
+ # Connect buttons to functions
167
+ generate_button.click(
168
+ fn=generate_image,
169
+ inputs=[
170
+ prompt, prompt_2, inpaint_image, inpaint_mask, control_image,
171
+ control_strength, control_stop, height, width,
172
+ num_inference_steps, guidance_scale, seed
173
+ ],
174
+ outputs=[output_image, status_message]
175
+ )
176
+
177
+ clear_button.click(fn=clear_gpu_memory, outputs=status_message)
178
+
179
+ # Examples
180
+ gr.Examples(
181
+ [
182
+ ["A beautiful landscape with mountains and a lake", None, None, None, None, 1.0, 1.0, 1024, 1024, 28, 3.5, 42],
183
+ ["A cyberpunk cityscape at night with neon lights", "High quality, detailed", None, None, None, 1.0, 1.0, 1024, 1024, 28, 7.0, 1234],
184
+ ],
185
+ fn=generate_image,
186
+ inputs=[
187
+ prompt, prompt_2, inpaint_image, inpaint_mask, control_image,
188
+ control_strength, control_stop, height, width,
189
+ num_inference_steps, guidance_scale, seed
190
+ ],
191
+ outputs=[output_image, status_message],
192
+ )
193
+
194
+ # Launch the app with queue enabled
195
+ if __name__ == "__main__":
196
+ demo.queue(concurrency_count=1).launch(share=False)
app_hf.py ADDED
@@ -0,0 +1,194 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import spaces
3
+ import torch
4
+ from diffusers import DiffusionPipeline
5
+ import gc
6
+ from pipeline import Flex2Pipeline
7
+
8
+ # Global variable to store the pipeline
9
+ pipe = None
10
+
11
+ @spaces.GPU
12
+ def load_model(model_id="ostris/Flex.2-preview", device="cuda"):
13
+ """Load and cache the model to avoid reloading for each inference"""
14
+ global pipe
15
+
16
+ if pipe is None:
17
+ print(f"Loading {model_id}...")
18
+ try:
19
+ # Load the model components directly using DiffusionPipeline
20
+ # This avoids trying to use custom_pipeline which is causing issues
21
+ components = DiffusionPipeline.from_pretrained(
22
+ model_id,
23
+ torch_dtype=torch.bfloat16 if torch.cuda.is_available() else torch.float32
24
+ ).components
25
+
26
+ # Create our custom Flex2Pipeline with the components
27
+ pipe = Flex2Pipeline(
28
+ scheduler=components["scheduler"],
29
+ vae=components["vae"],
30
+ text_encoder=components["text_encoder"],
31
+ tokenizer=components["tokenizer"],
32
+ text_encoder_2=components["text_encoder_2"],
33
+ tokenizer_2=components["tokenizer_2"],
34
+ transformer=components["transformer"],
35
+ )
36
+
37
+ # Move to device
38
+ pipe = pipe.to(device)
39
+ print("Model loaded successfully!")
40
+ except Exception as e:
41
+ print(f"Error loading model: {e}")
42
+ return None
43
+
44
+ # Enable TF32 precision if available
45
+ if torch.cuda.is_available():
46
+ torch.backends.cuda.matmul.allow_tf32 = True
47
+ torch.backends.cudnn.allow_tf32 = True
48
+
49
+ return pipe
50
+
51
+ def clear_gpu_memory():
52
+ """Clear GPU memory"""
53
+ global pipe
54
+ if pipe is not None:
55
+ del pipe
56
+ pipe = None
57
+ gc.collect()
58
+ if torch.cuda.is_available():
59
+ torch.cuda.empty_cache()
60
+ torch.cuda.ipc_collect()
61
+ return "GPU memory cleared"
62
+
63
+ @spaces.GPU
64
+ def generate_image(
65
+ prompt,
66
+ prompt_2=None,
67
+ inpaint_image=None,
68
+ inpaint_mask=None,
69
+ control_image=None,
70
+ control_strength=1.0,
71
+ control_stop=1.0,
72
+ height=1024,
73
+ width=1024,
74
+ num_inference_steps=28,
75
+ guidance_scale=3.5,
76
+ seed=-1,
77
+ progress=gr.Progress()
78
+ ):
79
+ """Generate image using Flex2Pipeline"""
80
+ global pipe
81
+
82
+ # Load model if not already loaded
83
+ pipe = load_model()
84
+ if pipe is None:
85
+ return None, "Error: Failed to load the model. Please check logs."
86
+
87
+ # Prepare generator for deterministic output
88
+ generator = None
89
+ if seed != -1:
90
+ generator = torch.Generator("cuda" if torch.cuda.is_available() else "cpu").manual_seed(seed)
91
+ else:
92
+ # Generate a random seed
93
+ seed = torch.randint(0, 2**32 - 1, (1,)).item()
94
+ generator = torch.Generator("cuda" if torch.cuda.is_available() else "cpu").manual_seed(seed)
95
+
96
+ # Create callback for progress updates
97
+ def callback_on_step_end(pipe, i, t, callback_kwargs):
98
+ progress((i + 1) / pipe._num_timesteps)
99
+ return callback_kwargs
100
+
101
+ try:
102
+ # Run the pipeline
103
+ output = pipe(
104
+ prompt=prompt,
105
+ prompt_2=prompt_2 if prompt_2 and prompt_2.strip() else None,
106
+ inpaint_image=inpaint_image,
107
+ inpaint_mask=inpaint_mask,
108
+ control_image=control_image,
109
+ control_strength=float(control_strength),
110
+ control_stop=float(control_stop),
111
+ height=height,
112
+ width=width,
113
+ num_inference_steps=num_inference_steps,
114
+ guidance_scale=guidance_scale,
115
+ generator=generator,
116
+ callback_on_step_end=callback_on_step_end,
117
+ )
118
+
119
+ # Return the generated image and success message
120
+ return output.images[0], f"Successfully generated image with seed: {seed}"
121
+
122
+ except Exception as e:
123
+ error_message = f"Error during image generation: {str(e)}"
124
+ print(error_message)
125
+ return None, error_message
126
+
127
+ # Create Gradio Interface
128
+ with gr.Blocks() as demo:
129
+ gr.Markdown("# Flex.2 generator by [JustLab.ai](https://justlab.ai)")
130
+
131
+ with gr.Row():
132
+ with gr.Column(scale=1):
133
+ # Input parameters
134
+ prompt = gr.Textbox(label="Prompt", placeholder="Enter your prompt here...", lines=3)
135
+ prompt_2 = gr.Textbox(label="Secondary Prompt (Optional)", placeholder="Optional secondary prompt...", lines=2)
136
+
137
+ with gr.Accordion("Image Settings", open=True):
138
+ with gr.Row():
139
+ height = gr.Slider(minimum=256, maximum=1536, value=1024, step=64, label="Height")
140
+ width = gr.Slider(minimum=256, maximum=1536, value=1024, step=64, label="Width")
141
+ with gr.Row():
142
+ num_inference_steps = gr.Slider(minimum=1, maximum=100, value=28, step=1, label="Inference Steps")
143
+ guidance_scale = gr.Slider(minimum=1.0, maximum=20.0, value=3.5, step=0.1, label="Guidance Scale")
144
+ seed = gr.Number(label="Seed (-1 for random)", value=-1)
145
+
146
+ with gr.Accordion("Control Settings (You can use LoRA generated images.)", open=False):
147
+ control_image = gr.Image(label="Control Image (Optional)", type="pil")
148
+ with gr.Row():
149
+ control_strength = gr.Slider(minimum=0.0, maximum=2.0, value=1.0, step=0.05, label="Control Strength")
150
+ control_stop = gr.Slider(minimum=0.0, maximum=1.0, value=1.0, step=0.05, label="Control Stop")
151
+
152
+ with gr.Accordion("Inpainting Settings", open=False):
153
+ inpaint_image = gr.Image(label="Initial Image for Inpainting", type="pil")
154
+ inpaint_mask = gr.Image(label="Mask Image (White areas will be inpainted)", type="pil")
155
+
156
+ # Generate button
157
+ generate_button = gr.Button("Generate Image", variant="primary")
158
+
159
+ # Status message
160
+ status_message = gr.Textbox(label="Status", interactive=False)
161
+
162
+ with gr.Column(scale=1):
163
+ # Output image
164
+ output_image = gr.Image(label="Generated Image")
165
+
166
+ # Connect buttons to functions
167
+ generate_button.click(
168
+ fn=generate_image,
169
+ inputs=[
170
+ prompt, prompt_2, inpaint_image, inpaint_mask, control_image,
171
+ control_strength, control_stop, height, width,
172
+ num_inference_steps, guidance_scale, seed
173
+ ],
174
+ outputs=[output_image, status_message]
175
+ )
176
+
177
+ # Examples
178
+ gr.Examples(
179
+ [
180
+ ["A beautiful landscape with mountains and a lake", None, None, None, None, 1.0, 1.0, 1024, 1024, 28, 3.5, 42],
181
+ ["A cyberpunk cityscape at night with neon lights", "High quality, detailed", None, None, None, 1.0, 1.0, 1024, 1024, 28, 7.0, 1234],
182
+ ],
183
+ fn=generate_image,
184
+ inputs=[
185
+ prompt, prompt_2, inpaint_image, inpaint_mask, control_image,
186
+ control_strength, control_stop, height, width,
187
+ num_inference_steps, guidance_scale, seed
188
+ ],
189
+ outputs=[output_image, status_message],
190
+ )
191
+
192
+ # Configure for HF Spaces
193
+ # Disable API endpoints
194
+ demo.queue().launch(show_api=False)
pipeline.py ADDED
@@ -0,0 +1,440 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from diffusers import FluxControlPipeline, FluxTransformer2DModel
2
+ from typing import Any, Callable, Dict, List, Optional, Union
3
+ import torch
4
+
5
+ from diffusers.image_processor import PipelineImageInput
6
+ import numpy as np
7
+ import torch.nn.functional as F
8
+ from diffusers.pipelines.flux.pipeline_output import FluxPipelineOutput
9
+ from diffusers.pipelines.flux.pipeline_flux import calculate_shift, retrieve_timesteps, XLA_AVAILABLE
10
+
11
+
12
+ class Flex2Pipeline(FluxControlPipeline):
13
+ def __init__(
14
+ self,
15
+ scheduler,
16
+ vae,
17
+ text_encoder,
18
+ tokenizer,
19
+ text_encoder_2,
20
+ tokenizer_2,
21
+ transformer,
22
+ ):
23
+ super().__init__(scheduler, vae, text_encoder, tokenizer, text_encoder_2, tokenizer_2, transformer)
24
+
25
+ def check_inputs(
26
+ self,
27
+ prompt,
28
+ prompt_2,
29
+ height,
30
+ width,
31
+ prompt_embeds=None,
32
+ pooled_prompt_embeds=None,
33
+ callback_on_step_end_tensor_inputs=None,
34
+ max_sequence_length=None,
35
+ inpaint_image=None,
36
+ inpaint_mask=None,
37
+ control_image=None,
38
+ ):
39
+ super().check_inputs(
40
+ prompt,
41
+ prompt_2,
42
+ height,
43
+ width,
44
+ prompt_embeds=prompt_embeds,
45
+ pooled_prompt_embeds=pooled_prompt_embeds,
46
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
47
+ max_sequence_length=max_sequence_length,
48
+ )
49
+ if inpaint_image is not None and inpaint_mask is None:
50
+ raise ValueError(
51
+ "If `inpaint_image` is passed, `inpaint_mask` must be passed as well. "
52
+ "Please make sure to pass both `inpaint_image` and `inpaint_mask`."
53
+ )
54
+ if inpaint_mask is not None and inpaint_image is None:
55
+ raise ValueError(
56
+ "If `inpaint_mask` is passed, `inpaint_image` must be passed as well. "
57
+ "Please make sure to pass both `inpaint_image` and `inpaint_mask`."
58
+ )
59
+
60
+ @torch.no_grad()
61
+ def __call__(
62
+ self,
63
+ prompt: Union[str, List[str]] = None,
64
+ prompt_2: Optional[Union[str, List[str]]] = None,
65
+ inpaint_image: Optional[PipelineImageInput] = None,
66
+ inpaint_mask: Optional[PipelineImageInput] = None,
67
+ control_image: Optional[PipelineImageInput] = None,
68
+ control_strength: Optional[float] = 1.0,
69
+ control_stop: Optional[float] = 1.0,
70
+ height: Optional[int] = None,
71
+ width: Optional[int] = None,
72
+ num_inference_steps: int = 28,
73
+ sigmas: Optional[List[float]] = None,
74
+ guidance_scale: float = 3.5,
75
+ num_images_per_prompt: Optional[int] = 1,
76
+ generator: Optional[Union[torch.Generator, List[torch.Generator]]] = None,
77
+ latents: Optional[torch.FloatTensor] = None,
78
+ prompt_embeds: Optional[torch.FloatTensor] = None,
79
+ pooled_prompt_embeds: Optional[torch.FloatTensor] = None,
80
+ output_type: Optional[str] = "pil",
81
+ return_dict: bool = True,
82
+ joint_attention_kwargs: Optional[Dict[str, Any]] = None,
83
+ callback_on_step_end: Optional[Callable[[int, int, Dict], None]] = None,
84
+ callback_on_step_end_tensor_inputs: List[str] = ["latents"],
85
+ max_sequence_length: int = 512,
86
+ **kwargs,
87
+ ):
88
+ r"""
89
+ Function invoked when calling the pipeline for generation.
90
+
91
+ Args:
92
+ prompt (`str` or `List[str]`, *optional*):
93
+ The prompt or prompts to guide the image generation. If not defined, one has to pass `prompt_embeds`.
94
+ instead.
95
+ prompt_2 (`str` or `List[str]`, *optional*):
96
+ The prompt or prompts to be sent to `tokenizer_2` and `text_encoder_2`. If not defined, `prompt` is
97
+ will be used instead
98
+ inpaint_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
99
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
100
+ The image to be inpainted.
101
+ inpaint_mask (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
102
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
103
+ A black and white mask to be used for inpainting. The white pixels are the areas to be inpainted, while the
104
+ black pixels are the areas to be kept.
105
+ control_image (`torch.Tensor`, `PIL.Image.Image`, `np.ndarray`, `List[torch.Tensor]`, `List[PIL.Image.Image]`, `List[np.ndarray]`,:
106
+ `List[List[torch.Tensor]]`, `List[List[np.ndarray]]` or `List[List[PIL.Image.Image]]`):
107
+ The control image (line, depth, pose, etc.) to be used for the generation. The control image
108
+ control_strength (`float`, *optional*, defaults to 1.0):
109
+ The strength of the control image. The higher the value, the more the control image will be used to
110
+ guide the generation. The lower the value, the less the control image will be used to guide the
111
+ generation.
112
+ control_stop (`float`, *optional*, defaults to 1.0):
113
+ The percentage of the generation to drop out the control. 0.0 to 1.0. 0.5 mean the control will be dropped
114
+ out at 50% of the generation.
115
+ height (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
116
+ The height in pixels of the generated image. This is set to 1024 by default for the best results.
117
+ width (`int`, *optional*, defaults to self.unet.config.sample_size * self.vae_scale_factor):
118
+ The width in pixels of the generated image. This is set to 1024 by default for the best results.
119
+ num_inference_steps (`int`, *optional*, defaults to 50):
120
+ The number of denoising steps. More denoising steps usually lead to a higher quality image at the
121
+ expense of slower inference.
122
+ sigmas (`List[float]`, *optional*):
123
+ Custom sigmas to use for the denoising process with schedulers which support a `sigmas` argument in
124
+ their `set_timesteps` method. If not defined, the default behavior when `num_inference_steps` is passed
125
+ will be used.
126
+ guidance_scale (`float`, *optional*, defaults to 3.5):
127
+ Guidance scale as defined in [Classifier-Free Diffusion Guidance](https://arxiv.org/abs/2207.12598).
128
+ `guidance_scale` is defined as `w` of equation 2. of [Imagen
129
+ Paper](https://arxiv.org/pdf/2205.11487.pdf). Guidance scale is enabled by setting `guidance_scale >
130
+ 1`. Higher guidance scale encourages to generate images that are closely linked to the text `prompt`,
131
+ usually at the expense of lower image quality.
132
+ num_images_per_prompt (`int`, *optional*, defaults to 1):
133
+ The number of images to generate per prompt.
134
+ generator (`torch.Generator` or `List[torch.Generator]`, *optional*):
135
+ One or a list of [torch generator(s)](https://pytorch.org/docs/stable/generated/torch.Generator.html)
136
+ to make generation deterministic.
137
+ latents (`torch.FloatTensor`, *optional*):
138
+ Pre-generated noisy latents, sampled from a Gaussian distribution, to be used as inputs for image
139
+ generation. Can be used to tweak the same generation with different prompts. If not provided, a latents
140
+ tensor will ge generated by sampling using the supplied random `generator`.
141
+ prompt_embeds (`torch.FloatTensor`, *optional*):
142
+ Pre-generated text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting. If not
143
+ provided, text embeddings will be generated from `prompt` input argument.
144
+ pooled_prompt_embeds (`torch.FloatTensor`, *optional*):
145
+ Pre-generated pooled text embeddings. Can be used to easily tweak text inputs, *e.g.* prompt weighting.
146
+ If not provided, pooled text embeddings will be generated from `prompt` input argument.
147
+ output_type (`str`, *optional*, defaults to `"pil"`):
148
+ The output format of the generate image. Choose between
149
+ [PIL](https://pillow.readthedocs.io/en/stable/): `PIL.Image.Image` or `np.array`.
150
+ return_dict (`bool`, *optional*, defaults to `True`):
151
+ Whether or not to return a [`~pipelines.flux.FluxPipelineOutput`] instead of a plain tuple.
152
+ joint_attention_kwargs (`dict`, *optional*):
153
+ A kwargs dictionary that if specified is passed along to the `AttentionProcessor` as defined under
154
+ `self.processor` in
155
+ [diffusers.models.attention_processor](https://github.com/huggingface/diffusers/blob/main/src/diffusers/models/attention_processor.py).
156
+ callback_on_step_end (`Callable`, *optional*):
157
+ A function that calls at the end of each denoising steps during the inference. The function is called
158
+ with the following arguments: `callback_on_step_end(self: DiffusionPipeline, step: int, timestep: int,
159
+ callback_kwargs: Dict)`. `callback_kwargs` will include a list of all tensors as specified by
160
+ `callback_on_step_end_tensor_inputs`.
161
+ callback_on_step_end_tensor_inputs (`List`, *optional*):
162
+ The list of tensor inputs for the `callback_on_step_end` function. The tensors specified in the list
163
+ will be passed as `callback_kwargs` argument. You will only be able to include variables listed in the
164
+ `._callback_tensor_inputs` attribute of your pipeline class.
165
+ max_sequence_length (`int` defaults to 512): Maximum sequence length to use with the `prompt`.
166
+
167
+ Examples:
168
+
169
+ Returns:
170
+ [`~pipelines.flux.FluxPipelineOutput`] or `tuple`: [`~pipelines.flux.FluxPipelineOutput`] if `return_dict`
171
+ is True, otherwise a `tuple`. When returning a tuple, the first element is a list with the generated
172
+ images.
173
+ """
174
+
175
+ height = height or self.default_sample_size * self.vae_scale_factor
176
+ width = width or self.default_sample_size * self.vae_scale_factor
177
+
178
+ # 1. Check inputs. Raise error if not correct
179
+ self.check_inputs(
180
+ prompt,
181
+ prompt_2,
182
+ height,
183
+ width,
184
+ prompt_embeds=prompt_embeds,
185
+ pooled_prompt_embeds=pooled_prompt_embeds,
186
+ callback_on_step_end_tensor_inputs=callback_on_step_end_tensor_inputs,
187
+ max_sequence_length=max_sequence_length,
188
+ )
189
+
190
+ self._guidance_scale = guidance_scale
191
+ self._joint_attention_kwargs = joint_attention_kwargs
192
+ self._interrupt = False
193
+
194
+ # 2. Define call parameters
195
+ if prompt is not None and isinstance(prompt, str):
196
+ batch_size = 1
197
+ elif prompt is not None and isinstance(prompt, list):
198
+ batch_size = len(prompt)
199
+ else:
200
+ batch_size = prompt_embeds.shape[0]
201
+
202
+ device = self._execution_device
203
+
204
+ # 3. Prepare text embeddings
205
+ lora_scale = (
206
+ self.joint_attention_kwargs.get("scale", None) if self.joint_attention_kwargs is not None else None
207
+ )
208
+ (
209
+ prompt_embeds,
210
+ pooled_prompt_embeds,
211
+ text_ids,
212
+ ) = self.encode_prompt(
213
+ prompt=prompt,
214
+ prompt_2=prompt_2,
215
+ prompt_embeds=prompt_embeds,
216
+ pooled_prompt_embeds=pooled_prompt_embeds,
217
+ device=device,
218
+ num_images_per_prompt=num_images_per_prompt,
219
+ max_sequence_length=max_sequence_length,
220
+ lora_scale=lora_scale,
221
+ )
222
+
223
+ # 4. Prepare latent variables
224
+ num_channels_latents = self.transformer.config.in_channels // 4
225
+
226
+ # only prepare latents for non controls
227
+ # (16 + 1 + 16 )
228
+ num_control_channels = 33
229
+ num_channels_latents = num_channels_latents - num_control_channels
230
+
231
+ control_latents = None
232
+ inpaint_latents = None
233
+ inpaint_latents_mask = None
234
+
235
+ latent_height = height // self.vae_scale_factor
236
+ latent_width = width // self.vae_scale_factor
237
+
238
+ # process the control and inpaint channels
239
+
240
+ if control_image is None:
241
+ control_latents = torch.zeros(
242
+ batch_size * num_images_per_prompt,
243
+ 16,
244
+ latent_height,
245
+ latent_width,
246
+ device=device,
247
+ dtype=self.vae.dtype,
248
+ )
249
+ else:
250
+ control_image = self.prepare_image(
251
+ image=control_image,
252
+ width=width,
253
+ height=height,
254
+ batch_size=batch_size * num_images_per_prompt,
255
+ num_images_per_prompt=num_images_per_prompt,
256
+ device=device,
257
+ dtype=self.vae.dtype,
258
+ )
259
+ control_image = self.vae.encode(control_image).latent_dist.sample(generator=generator)
260
+ control_latents = (control_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
261
+
262
+ # apply control strength
263
+ control_latents = control_latents * control_strength
264
+
265
+ if inpaint_image is None and inpaint_mask is None:
266
+ inpaint_latents = torch.zeros(
267
+ batch_size * num_images_per_prompt,
268
+ 16,
269
+ latent_height,
270
+ latent_width,
271
+ device=device,
272
+ dtype=self.vae.dtype,
273
+ )
274
+ inpaint_latents_mask = torch.ones(
275
+ batch_size * num_images_per_prompt,
276
+ 1,
277
+ latent_height,
278
+ latent_width,
279
+ device=device,
280
+ dtype=self.vae.dtype,
281
+ )
282
+ else:
283
+ inpaint_image = self.prepare_image(
284
+ image=inpaint_image,
285
+ width=width,
286
+ height=height,
287
+ batch_size=batch_size * num_images_per_prompt,
288
+ num_images_per_prompt=num_images_per_prompt,
289
+ device=device,
290
+ dtype=self.vae.dtype,
291
+ )
292
+ inpaint_image = self.vae.encode(inpaint_image).latent_dist.sample(generator=generator)
293
+ inpaint_latents = (inpaint_image - self.vae.config.shift_factor) * self.vae.config.scaling_factor
294
+ height_inpaint_image, width_inpaint_image = control_image.shape[2:]
295
+
296
+ inpaint_mask = self.prepare_image(
297
+ image=inpaint_mask,
298
+ width=width,
299
+ height=height,
300
+ batch_size=batch_size * num_images_per_prompt,
301
+ num_images_per_prompt=num_images_per_prompt,
302
+ device=device,
303
+ dtype=self.vae.dtype,
304
+ )
305
+ # mask is 3 ch -1 to 1. make it 1ch, 0 to 1
306
+ inpaint_mask = inpaint_mask[:, 0:1, :, :] * 0.5 + 0.5
307
+ # resize to match height_inpaint_image and width_inpaint_image
308
+ inpaint_latents_mask = F.interpolate(inpaint_mask, size=(height_inpaint_image, width_inpaint_image), mode="bilinear", align_corners=False)
309
+
310
+ # apply inverted mask to inpaint latents
311
+ inpaint_latents = inpaint_latents * (1 - inpaint_latents_mask)
312
+
313
+ # concat the latent controls on the channel dimension every step
314
+ latent_controls = torch.cat([inpaint_latents, inpaint_latents_mask, control_latents], dim=1)
315
+ latent_no_controls = torch.cat([inpaint_latents, inpaint_latents_mask, torch.zeros_like(control_latents)], dim=1)
316
+
317
+ # pack the controls
318
+ height_latent_controls, width_latent_controls = latent_controls.shape[2:]
319
+ packed_latent_controls = self._pack_latents(
320
+ latent_controls,
321
+ batch_size * num_images_per_prompt,
322
+ num_control_channels,
323
+ height_latent_controls,
324
+ width_latent_controls,
325
+ )
326
+ packed_latent_no_controls = self._pack_latents(
327
+ latent_no_controls,
328
+ batch_size * num_images_per_prompt,
329
+ num_control_channels,
330
+ height_latent_controls,
331
+ width_latent_controls,
332
+ )
333
+
334
+ latents, latent_image_ids = self.prepare_latents(
335
+ batch_size * num_images_per_prompt,
336
+ num_channels_latents,
337
+ height,
338
+ width,
339
+ prompt_embeds.dtype,
340
+ device,
341
+ generator,
342
+ latents,
343
+ )
344
+
345
+ # 5. Prepare timesteps
346
+ sigmas = np.linspace(1.0, 1 / num_inference_steps, num_inference_steps) if sigmas is None else sigmas
347
+ image_seq_len = latents.shape[1]
348
+ mu = calculate_shift(
349
+ image_seq_len,
350
+ self.scheduler.config.get("base_image_seq_len", 256),
351
+ self.scheduler.config.get("max_image_seq_len", 4096),
352
+ self.scheduler.config.get("base_shift", 0.5),
353
+ self.scheduler.config.get("max_shift", 1.15),
354
+ )
355
+ timesteps, num_inference_steps = retrieve_timesteps(
356
+ self.scheduler,
357
+ num_inference_steps,
358
+ device,
359
+ sigmas=sigmas,
360
+ mu=mu,
361
+ )
362
+ num_warmup_steps = max(len(timesteps) - num_inference_steps * self.scheduler.order, 0)
363
+ self._num_timesteps = len(timesteps)
364
+
365
+ # handle guidance
366
+ if self.transformer.config.guidance_embeds:
367
+ guidance = torch.full([1], guidance_scale, device=device, dtype=torch.float32)
368
+ guidance = guidance.expand(latents.shape[0])
369
+ else:
370
+ guidance = None
371
+
372
+ control_cutoff = int(len(timesteps) * control_stop)
373
+
374
+ # 6. Denoising loop
375
+ with self.progress_bar(total=num_inference_steps) as progress_bar:
376
+ for i, t in enumerate(timesteps):
377
+ if self.interrupt:
378
+ continue
379
+
380
+ control_latents = packed_latent_controls if i < control_cutoff else packed_latent_no_controls
381
+
382
+ latent_model_input = torch.cat([latents, control_latents], dim=2)
383
+
384
+ # broadcast to batch dimension in a way that's compatible with ONNX/Core ML
385
+ timestep = t.expand(latents.shape[0]).to(latents.dtype)
386
+
387
+ noise_pred = self.transformer(
388
+ hidden_states=latent_model_input,
389
+ timestep=timestep / 1000,
390
+ guidance=guidance,
391
+ pooled_projections=pooled_prompt_embeds,
392
+ encoder_hidden_states=prompt_embeds,
393
+ txt_ids=text_ids,
394
+ img_ids=latent_image_ids,
395
+ joint_attention_kwargs=self.joint_attention_kwargs,
396
+ return_dict=False,
397
+ )[0]
398
+
399
+ # compute the previous noisy sample x_t -> x_t-1
400
+ latents_dtype = latents.dtype
401
+ latents = self.scheduler.step(noise_pred, t, latents, return_dict=False)[0]
402
+
403
+ if latents.dtype != latents_dtype:
404
+ if torch.backends.mps.is_available():
405
+ # some platforms (eg. apple mps) misbehave due to a pytorch bug: https://github.com/pytorch/pytorch/pull/99272
406
+ latents = latents.to(latents_dtype)
407
+
408
+ if callback_on_step_end is not None:
409
+ callback_kwargs = {}
410
+ for k in callback_on_step_end_tensor_inputs:
411
+ callback_kwargs[k] = locals()[k]
412
+ callback_outputs = callback_on_step_end(self, i, t, callback_kwargs)
413
+
414
+ latents = callback_outputs.pop("latents", latents)
415
+ prompt_embeds = callback_outputs.pop("prompt_embeds", prompt_embeds)
416
+
417
+ # call the callback, if provided
418
+ if i == len(timesteps) - 1 or ((i + 1) > num_warmup_steps and (i + 1) % self.scheduler.order == 0):
419
+ progress_bar.update()
420
+
421
+ if XLA_AVAILABLE:
422
+ xm.mark_step()
423
+
424
+ if output_type == "latent":
425
+ image = latents
426
+ else:
427
+ latents = self._unpack_latents(latents, height, width, self.vae_scale_factor)
428
+ latents = (latents / self.vae.config.scaling_factor) + self.vae.config.shift_factor
429
+ image = self.vae.decode(latents, return_dict=False)[0]
430
+ image = self.image_processor.postprocess(image, output_type=output_type)
431
+
432
+ # Offload all models
433
+ self.maybe_free_model_hooks()
434
+
435
+ if not return_dict:
436
+ return (image,)
437
+
438
+ return FluxPipelineOutput(images=image)
439
+
440
+
requirements.txt ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ torch>=2.0.0
2
+ transformers>=4.30.0
3
+ diffusers>=0.24.0
4
+ accelerate>=0.20.0
5
+ gradio>=5.29.0
6
+ pillow>=9.0.0
7
+ numpy>=1.20.0
8
+ safetensors>=0.3.0
9
+ ftfy>=6.1.0
10
+ xformers>=0.0.20
11
+ huggingface-hub>=0.19.0
12
+ torchao>=0.1.0
13
+ spaces
14
+ sentencepiece