jadechoghari commited on
Commit
c77781d
Β·
verified Β·
1 Parent(s): 33743fb

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +141 -77
app.py CHANGED
@@ -1,82 +1,146 @@
1
- import gradio as gr
2
- import torch
3
- import spaces
4
- from diffusers import FluxPipeline, DiffusionPipeline
5
- from torchao.quantization import autoquant
6
-
7
-
8
-
9
- # # # normal FluxPipeline
10
- # pipeline_normal = FluxPipeline.from_pretrained(
11
- # "sayakpaul/FLUX.1-merged",
12
- # torch_dtype=torch.bfloat16
13
- # ).to("cuda")
14
- # pipeline_normal.transformer.to(memory_format=torch.channels_last)
15
- # pipeline_normal.transformer = torch.compile(pipeline_normal.transformer, mode="max-autotune", fullgraph=True)
16
-
17
- pipeline_normal = DiffusionPipeline.from_pretrained("sayakpaul/FLUX.1-merged")
18
- pipeline_normal.enable_model_cpu_offload()
19
- pipeline_normal.load_lora_weights("DarkMoonDragon/TurboRender-flux-dev")
20
- # # optimized FluxPipeline
21
- # pipeline_optimized = FluxPipeline.from_pretrained(
22
- # "camenduru/FLUX.1-dev-diffusers",
23
- # torch_dtype=torch.bfloat16
24
- # ).to("cuda")
25
- # pipeline_optimized.transformer.to(memory_format=torch.channels_last)
26
- # pipeline_optimized.transformer = torch.compile(
27
- # pipeline_optimized.transformer,
28
- # mode="max-autotune",
29
- # fullgraph=True
30
- # )
31
- # # wrap the autoquant call in a try-except block to handle unsupported layers
32
- # for name, layer in pipeline_optimized.transformer.named_children():
33
- # try:
34
- # # apply autoquant to each layer
35
- # pipeline_optimized.transformer._modules[name] = autoquant(layer, error_on_unseen=False)
36
- # print(f"Successfully quantized {name}")
37
- # except AttributeError as e:
38
- # print(f"Skipping layer {name} due to error: {e}")
39
- # except Exception as e:
40
- # print(f"Unexpected error while quantizing {name}: {e}")
41
-
42
- # pipeline_optimized.transformer = autoquant(
43
- # pipeline_optimized.transformer,
44
- # error_on_unseen=False
45
- # )
46
- pipeline_optimized = pipeline_normal
47
-
48
- @spaces.GPU(duration=120)
49
- def generate_images(prompt, guidance_scale, num_inference_steps):
50
- # # generate image with normal pipeline
51
- # image_normal = pipeline_normal(
52
- # prompt=prompt,
53
- # guidance_scale=guidance_scale,
54
- # num_inference_steps=int(num_inference_steps)
55
- # ).images[0]
56
 
57
- # generate image with optimized pipeline
58
- image_optimized = pipeline_optimized(
59
- prompt=prompt,
60
- guidance_scale=guidance_scale,
61
- num_inference_steps=int(num_inference_steps)
62
- ).images[0]
63
 
64
- return image_optimized
65
-
66
- # set up Gradio interface
67
- demo = gr.Interface(
68
- fn=generate_images,
69
- inputs=[
70
- gr.Textbox(lines=2, placeholder="Enter your prompt here...", label="Prompt"),
71
- gr.Slider(1.0, 10.0, step=0.5, value=3.5, label="Guidance Scale"),
72
- gr.Slider(10, 100, step=1, value=50, label="Number of Inference Steps")
73
- ],
74
- outputs=[
75
- gr.Image(type="pil", label="Optimized FluxPipeline")
76
- ],
77
- title="FluxPipeline Comparison",
78
- description="Compare images generated by the normal FluxPipeline and the optimized one using torchao and torch.compile()."
79
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
80
 
81
  demo.launch()
82
 
 
1
+ # import gradio as gr
2
+ # import torch
3
+ # import spaces
4
+ # from diffusers import FluxPipeline, DiffusionPipeline
5
+ # from torchao.quantization import autoquant
6
+
7
+
8
+
9
+ # # # # normal FluxPipeline
10
+ # # pipeline_normal = FluxPipeline.from_pretrained(
11
+ # # "sayakpaul/FLUX.1-merged",
12
+ # # torch_dtype=torch.bfloat16
13
+ # # ).to("cuda")
14
+ # # pipeline_normal.transformer.to(memory_format=torch.channels_last)
15
+ # # pipeline_normal.transformer = torch.compile(pipeline_normal.transformer, mode="max-autotune", fullgraph=True)
16
+
17
+ # pipeline_normal = DiffusionPipeline.from_pretrained("sayakpaul/FLUX.1-merged")
18
+ # pipeline_normal.enable_model_cpu_offload()
19
+ # pipeline_normal.load_lora_weights("DarkMoonDragon/TurboRender-flux-dev")
20
+ # # # optimized FluxPipeline
21
+ # # pipeline_optimized = FluxPipeline.from_pretrained(
22
+ # # "camenduru/FLUX.1-dev-diffusers",
23
+ # # torch_dtype=torch.bfloat16
24
+ # # ).to("cuda")
25
+ # # pipeline_optimized.transformer.to(memory_format=torch.channels_last)
26
+ # # pipeline_optimized.transformer = torch.compile(
27
+ # # pipeline_optimized.transformer,
28
+ # # mode="max-autotune",
29
+ # # fullgraph=True
30
+ # # )
31
+ # # # wrap the autoquant call in a try-except block to handle unsupported layers
32
+ # # for name, layer in pipeline_optimized.transformer.named_children():
33
+ # # try:
34
+ # # # apply autoquant to each layer
35
+ # # pipeline_optimized.transformer._modules[name] = autoquant(layer, error_on_unseen=False)
36
+ # # print(f"Successfully quantized {name}")
37
+ # # except AttributeError as e:
38
+ # # print(f"Skipping layer {name} due to error: {e}")
39
+ # # except Exception as e:
40
+ # # print(f"Unexpected error while quantizing {name}: {e}")
41
+
42
+ # # pipeline_optimized.transformer = autoquant(
43
+ # # pipeline_optimized.transformer,
44
+ # # error_on_unseen=False
45
+ # # )
46
+ # pipeline_optimized = pipeline_normal
47
+
48
+ # @spaces.GPU(duration=120)
49
+ # def generate_images(prompt, guidance_scale, num_inference_steps):
50
+ # # # generate image with normal pipeline
51
+ # # image_normal = pipeline_normal(
52
+ # # prompt=prompt,
53
+ # # guidance_scale=guidance_scale,
54
+ # # num_inference_steps=int(num_inference_steps)
55
+ # # ).images[0]
56
 
57
+ # # generate image with optimized pipeline
58
+ # image_optimized = pipeline_optimized(
59
+ # prompt=prompt,
60
+ # guidance_scale=guidance_scale,
61
+ # num_inference_steps=int(num_inference_steps)
62
+ # ).images[0]
63
 
64
+ # return image_optimized
65
+
66
+ # # set up Gradio interface
67
+ # demo = gr.Interface(
68
+ # fn=generate_images,
69
+ # inputs=[
70
+ # gr.Textbox(lines=2, placeholder="Enter your prompt here...", label="Prompt"),
71
+ # gr.Slider(1.0, 10.0, step=0.5, value=3.5, label="Guidance Scale"),
72
+ # gr.Slider(10, 100, step=1, value=50, label="Number of Inference Steps")
73
+ # ],
74
+ # outputs=[
75
+ # gr.Image(type="pil", label="Optimized FluxPipeline")
76
+ # ],
77
+ # title="FluxPipeline Comparison",
78
+ # description="Compare images generated by the normal FluxPipeline and the optimized one using torchao and torch.compile()."
79
+ # )
80
+
81
+ # demo.launch()
82
+ import gradio as gr
83
+ import torch
84
+ from diffusers import FluxPipeline
85
+ from torchao import swap_conv2d_1x1_to_linear, apply_dynamic_quant
86
+
87
+ # Step 1: Enable PyTorch 2-specific optimizations
88
+ torch._inductor.config.conv_1x1_as_mm = True
89
+ torch._inductor.config.coordinate_descent_tuning = True
90
+ torch._inductor.config.epilogue_fusion = False
91
+ torch._inductor.config.coordinate_descent_check_all_directions = True
92
+ torch._inductor.config.force_fuse_int_mm_with_mul = True
93
+ torch._inductor.config.use_mixed_mm = True
94
+
95
+ # Step 2: Load the Flux pipeline with bfloat16 precision
96
+ pipe = FluxPipeline.from_pretrained(
97
+ "sayakpaul/FLUX.1-merged",
98
+ torch_dtype=torch.bfloat16
99
+ ).to("cuda")
100
+
101
+ # Step 3: Apply attention optimizations
102
+ pipe.fuse_qkv_projections()
103
+
104
+ # Step 4: Change memory layout for performance boost
105
+ pipe.unet.to(memory_format=torch.channels_last)
106
+ pipe.vae.to(memory_format=torch.channels_last)
107
+
108
+ # Step 5: Swap Conv2D 1x1 layers to Linear and apply dynamic quantization
109
+ def dynamic_quant_filter_fn(mod, *args):
110
+ return isinstance(mod, torch.nn.Linear) and mod.in_features > 16
111
+
112
+ def conv_filter_fn(mod, *args):
113
+ return isinstance(mod, torch.nn.Conv2d) and mod.kernel_size == (1, 1)
114
+
115
+ swap_conv2d_1x1_to_linear(pipe.unet, conv_filter_fn)
116
+ swap_conv2d_1x1_to_linear(pipe.vae, conv_filter_fn)
117
+
118
+ apply_dynamic_quant(pipe.unet, dynamic_quant_filter_fn)
119
+ apply_dynamic_quant(pipe.vae, dynamic_quant_filter_fn)
120
+
121
+ # Step 6: Compile the UNet and VAE for optimized kernels
122
+ pipe.unet = torch.compile(pipe.unet, mode="max-autotune", fullgraph=True)
123
+ pipe.vae.decode = torch.compile(pipe.vae.decode, mode="max-autotune", fullgraph=True)
124
+
125
+ # Image generation function
126
+ def generate_image(prompt, guidance_scale, num_inference_steps):
127
+ # Generate the image using the optimized pipeline
128
+ image = pipe(prompt, guidance_scale=guidance_scale, num_inference_steps=num_inference_steps).images[0]
129
+ return image
130
+
131
+ # Gradio UI
132
+ with gr.Blocks() as demo:
133
+ gr.Markdown("# Optimized Flux Model Inference")
134
+
135
+ with gr.Row():
136
+ prompt = gr.Textbox(label="Prompt", placeholder="Enter your text prompt here")
137
+ guidance_scale = gr.Slider(0.0, 15.0, value=7.5, step=0.1, label="Guidance Scale")
138
+ steps = gr.Slider(5, 50, value=30, step=1, label="Inference Steps")
139
+
140
+ image_output = gr.Image(type="pil", label="Generated Image")
141
+
142
+ generate_button = gr.Button("Generate Image")
143
+ generate_button.click(generate_image, inputs=[prompt, guidance_scale, steps], outputs=image_output)
144
 
145
  demo.launch()
146