onnew commited on
Commit
3105137
·
verified ·
1 Parent(s): e7efd92

Update app.py

Browse files
Files changed (1) hide show
  1. app.py +88 -68
app.py CHANGED
@@ -1,66 +1,77 @@
1
  import gradio as gr
2
  import numpy as np
3
  import random
4
- import spaces
5
  import torch
6
- from diffusers import DiffusionPipeline, FlowMatchEulerDiscreteScheduler, AutoencoderTiny, AutoencoderKL
7
- from transformers import CLIPTextModel, CLIPTokenizer,T5EncoderModel, T5TokenizerFast
8
- from live_preview_helpers import calculate_shift, retrieve_timesteps, flux_pipe_call_that_returns_an_iterable_of_images
9
 
10
- dtype = torch.bfloat16
11
  device = "cuda" if torch.cuda.is_available() else "cpu"
 
12
 
13
- taef1 = AutoencoderTiny.from_pretrained("madebyollin/taef1", torch_dtype=dtype).to(device)
14
- good_vae = AutoencoderKL.from_pretrained("black-forest-labs/FLUX.1-dev", subfolder="vae", torch_dtype=dtype).to(device)
15
- pipe = DiffusionPipeline.from_pretrained("black-forest-labs/FLUX.1-dev", torch_dtype=dtype, vae=taef1).to(device)
16
- torch.cuda.empty_cache()
17
 
18
- MAX_SEED = np.iinfo(np.int32).max
19
- MAX_IMAGE_SIZE = 2048
20
 
21
- pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
 
 
22
 
23
- @spaces.GPU(duration=75)
24
- def infer(prompt, seed=42, randomize_seed=False, width=1024, height=1024, guidance_scale=3.5, num_inference_steps=28, progress=gr.Progress(track_tqdm=True)):
 
 
 
 
 
 
 
 
 
 
 
25
  if randomize_seed:
26
  seed = random.randint(0, MAX_SEED)
27
- generator = torch.Generator().manual_seed(seed)
28
-
29
- for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
 
 
 
 
30
  prompt=prompt,
 
31
  guidance_scale=guidance_scale,
32
  num_inference_steps=num_inference_steps,
33
  width=width,
34
  height=height,
35
  generator=generator,
36
- output_type="pil",
37
- good_vae=good_vae,
38
- ):
39
- yield img, seed
40
-
 
41
  examples = [
42
- "a tiny astronaut hatching from an egg on the moon",
43
- "a cat holding a sign that says hello world",
44
- "an anime illustration of a wiener schnitzel",
45
  ]
46
 
47
- css="""
48
  #col-container {
49
  margin: 0 auto;
50
- max-width: 520px;
51
  }
52
  """
53
 
54
  with gr.Blocks(css=css) as demo:
55
-
56
  with gr.Column(elem_id="col-container"):
57
- gr.Markdown(f"""# FLUX.1 [dev]
58
- 12B param rectified flow transformer guidance-distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/)
59
- [[non-commercial license](https://huggingface.co/black-forest-labs/FLUX.1-dev/blob/main/LICENSE.md)] [[blog](https://blackforestlabs.ai/announcing-black-forest-labs/)] [[model](https://huggingface.co/black-forest-labs/FLUX.1-dev)]
60
- """)
61
-
62
  with gr.Row():
63
-
64
  prompt = gr.Text(
65
  label="Prompt",
66
  show_label=False,
@@ -68,13 +79,19 @@ with gr.Blocks(css=css) as demo:
68
  placeholder="Enter your prompt",
69
  container=False,
70
  )
71
-
72
- run_button = gr.Button("Run", scale=0)
73
-
74
  result = gr.Image(label="Result", show_label=False)
75
-
76
  with gr.Accordion("Advanced Settings", open=False):
77
-
 
 
 
 
 
 
78
  seed = gr.Slider(
79
  label="Seed",
80
  minimum=0,
@@ -82,59 +99,62 @@ with gr.Blocks(css=css) as demo:
82
  step=1,
83
  value=0,
84
  )
85
-
86
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
87
-
88
  with gr.Row():
89
-
90
  width = gr.Slider(
91
  label="Width",
92
  minimum=256,
93
  maximum=MAX_IMAGE_SIZE,
94
  step=32,
95
- value=1024,
96
  )
97
-
98
  height = gr.Slider(
99
  label="Height",
100
- minimum=256,
101
  maximum=MAX_IMAGE_SIZE,
102
  step=32,
103
- value=1024,
104
  )
105
-
106
- with gr.Row():
107
 
 
108
  guidance_scale = gr.Slider(
109
- label="Guidance Scale",
110
- minimum=1,
111
- maximum=15,
112
  step=0.1,
113
- value=3.5,
114
  )
115
-
116
  num_inference_steps = gr.Slider(
117
- label="Number of inference steps",
118
  minimum=1,
119
- maximum=50,
120
  step=1,
121
- value=28,
122
  )
123
-
124
- gr.Examples(
125
- examples = examples,
126
- fn = infer,
127
- inputs = [prompt],
128
- outputs = [result, seed],
129
- cache_examples="lazy"
130
- )
131
 
132
  gr.on(
133
  triggers=[run_button.click, prompt.submit],
134
- fn = infer,
135
- inputs = [prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
136
- outputs = [result, seed]
 
 
 
 
 
 
 
 
 
137
  )
138
 
139
- demo.launch()
 
 
140
 
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
 
4
  import torch
5
+ from diffusers import DiffusionPipeline
6
+ from torch import autocast # Usando autocast para otimizar operações em float16
 
7
 
8
+ # Verifica se a GPU está disponível
9
  device = "cuda" if torch.cuda.is_available() else "cpu"
10
+ model_repo_id = "stabilityai/sdxl-turbo" # Modelo otimizado para velocidade
11
 
12
+ # Usando float16 para otimizar a execução na GPU
13
+ torch_dtype = torch.float16 if torch.cuda.is_available() else torch.float32
 
 
14
 
15
+ # Carregando o modelo com otimizações
16
+ pipe = DiffusionPipeline.from_pretrained(model_repo_id, torch_dtype=torch_dtype).to(device)
17
 
18
+ # Max seed
19
+ MAX_SEED = np.iinfo(np.int32).max
20
+ MAX_IMAGE_SIZE = 512 # Dimensões menores para acelerar
21
 
22
+ # Função de inferência otimizada
23
+ def infer(
24
+ prompt,
25
+ negative_prompt,
26
+ seed,
27
+ randomize_seed,
28
+ width,
29
+ height,
30
+ guidance_scale,
31
+ num_inference_steps,
32
+ progress=gr.Progress(track_tqdm=True),
33
+ ):
34
+ # Randomiza a semente, se necessário
35
  if randomize_seed:
36
  seed = random.randint(0, MAX_SEED)
37
+
38
+ generator = torch.Generator(device).manual_seed(seed)
39
+
40
+ # Usando autocast para acelerar o cálculo com float16 em GPUs
41
+ with autocast("cuda"):
42
+ # Geração da imagem com um número reduzido de passos (para acelerar)
43
+ image = pipe(
44
  prompt=prompt,
45
+ negative_prompt=negative_prompt,
46
  guidance_scale=guidance_scale,
47
  num_inference_steps=num_inference_steps,
48
  width=width,
49
  height=height,
50
  generator=generator,
51
+ ).images[0]
52
+
53
+ return image, seed
54
+
55
+
56
+ # Exemplos para o Gradio
57
  examples = [
58
+ "Astronaut in a jungle, cold color palette, muted colors, detailed, 2k",
59
+ "An astronaut riding a green horse",
60
+ "A delicious ceviche cheesecake slice",
61
  ]
62
 
63
+ css = """
64
  #col-container {
65
  margin: 0 auto;
66
+ max-width: 640px;
67
  }
68
  """
69
 
70
  with gr.Blocks(css=css) as demo:
 
71
  with gr.Column(elem_id="col-container"):
72
+ gr.Markdown(" # Text-to-Image Gradio Template")
73
+
 
 
 
74
  with gr.Row():
 
75
  prompt = gr.Text(
76
  label="Prompt",
77
  show_label=False,
 
79
  placeholder="Enter your prompt",
80
  container=False,
81
  )
82
+
83
+ run_button = gr.Button("Run", scale=0, variant="primary")
84
+
85
  result = gr.Image(label="Result", show_label=False)
86
+
87
  with gr.Accordion("Advanced Settings", open=False):
88
+ negative_prompt = gr.Text(
89
+ label="Negative prompt",
90
+ max_lines=1,
91
+ placeholder="Enter a negative prompt",
92
+ visible=False,
93
+ )
94
+
95
  seed = gr.Slider(
96
  label="Seed",
97
  minimum=0,
 
99
  step=1,
100
  value=0,
101
  )
102
+
103
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
104
+
105
  with gr.Row():
 
106
  width = gr.Slider(
107
  label="Width",
108
  minimum=256,
109
  maximum=MAX_IMAGE_SIZE,
110
  step=32,
111
+ value=512, # Dimensões reduzidas para otimizar
112
  )
113
+
114
  height = gr.Slider(
115
  label="Height",
116
+ minimum=576,
117
  maximum=MAX_IMAGE_SIZE,
118
  step=32,
119
+ value=1024, # Dimensões reduzidas para otimizar
120
  )
 
 
121
 
122
+ with gr.Row():
123
  guidance_scale = gr.Slider(
124
+ label="Guidance scale",
125
+ minimum=0.0,
126
+ maximum=10.0,
127
  step=0.1,
128
+ value=7.5, # Valor adequado para controle
129
  )
130
+
131
  num_inference_steps = gr.Slider(
132
+ label="Inference steps",
133
  minimum=1,
134
+ maximum=30, # Menos passos para otimizar a velocidade
135
  step=1,
136
+ value=20, # Um valor equilibrado
137
  )
138
+
139
+ gr.Examples(examples=examples, inputs=[prompt])
 
 
 
 
 
 
140
 
141
  gr.on(
142
  triggers=[run_button.click, prompt.submit],
143
+ fn=infer,
144
+ inputs=[
145
+ prompt,
146
+ negative_prompt,
147
+ seed,
148
+ randomize_seed,
149
+ width,
150
+ height,
151
+ guidance_scale,
152
+ num_inference_steps,
153
+ ],
154
+ outputs=[result, seed],
155
  )
156
 
157
+ if __name__ == "__main__":
158
+ demo.launch()
159
+
160