Files changed (1) hide show
  1. app.py +36 -33
app.py CHANGED
@@ -1,58 +1,66 @@
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/)
@@ -60,7 +68,6 @@ with gr.Blocks(css=css) as demo:
60
  """)
61
 
62
  with gr.Row():
63
-
64
  prompt = gr.Text(
65
  label="Prompt",
66
  show_label=False,
@@ -68,13 +75,11 @@ 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,
@@ -86,7 +91,6 @@ with gr.Blocks(css=css) as demo:
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,
@@ -104,7 +108,6 @@ with gr.Blocks(css=css) as demo:
104
  )
105
 
106
  with gr.Row():
107
-
108
  guidance_scale = gr.Slider(
109
  label="Guidance Scale",
110
  minimum=1,
@@ -122,18 +125,18 @@ with gr.Blocks(css=css) as demo:
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()
 
1
  import gradio as gr
2
  import numpy as np
3
  import random
 
4
  import torch
5
+ from diffusers import DiffusionPipeline, AutoencoderTiny, AutoencoderKL
6
+ from transformers import CLIPTextModel, CLIPTokenizer
7
+ from live_preview_helpers import flux_pipe_call_that_returns_an_iterable_of_images
8
 
9
+ # Definindo variáveis e carregando modelos
10
+ dtype = torch.float16 # Usando float16 para melhorar a performance
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
+ pipe.flux_pipe_call_that_returns_an_iterable_of_images = flux_pipe_call_that_returns_an_iterable_of_images.__get__(pipe)
17
+
18
  torch.cuda.empty_cache()
19
 
20
  MAX_SEED = np.iinfo(np.int32).max
21
  MAX_IMAGE_SIZE = 2048
22
 
23
+ # Função de inferência otimizada
24
+ @torch.inference_mode() # Desabilitando cálculo de gradientes para acelerar a inferência
25
  @spaces.GPU(duration=75)
26
  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)):
27
  if randomize_seed:
28
  seed = random.randint(0, MAX_SEED)
 
29
 
30
+ generator = torch.Generator(device).manual_seed(seed)
31
+
32
+ # Usando autograd em precisão reduzida (float16) para acelerar a inferência
33
+ with torch.autocast("cuda", dtype=torch.float16):
34
+ for img in pipe.flux_pipe_call_that_returns_an_iterable_of_images(
35
+ prompt=prompt,
36
+ guidance_scale=guidance_scale,
37
+ num_inference_steps=num_inference_steps,
38
+ width=width,
39
+ height=height,
40
+ generator=generator,
41
+ output_type="pil",
42
+ good_vae=good_vae,
43
+ ):
44
  yield img, seed
45
 
46
+ torch.cuda.empty_cache() # Limpar a memória após a inferência para liberar recursos
47
+
48
+ # Exemplos
49
  examples = [
50
  "a tiny astronaut hatching from an egg on the moon",
51
  "a cat holding a sign that says hello world",
52
  "an anime illustration of a wiener schnitzel",
53
  ]
54
 
55
+ css = """
56
  #col-container {
57
  margin: 0 auto;
58
  max-width: 520px;
59
  }
60
  """
61
 
62
+ # Interface Gradio
63
  with gr.Blocks(css=css) as demo:
 
64
  with gr.Column(elem_id="col-container"):
65
  gr.Markdown(f"""# FLUX.1 [dev]
66
  12B param rectified flow transformer guidance-distilled from [FLUX.1 [pro]](https://blackforestlabs.ai/)
 
68
  """)
69
 
70
  with gr.Row():
 
71
  prompt = gr.Text(
72
  label="Prompt",
73
  show_label=False,
 
75
  placeholder="Enter your prompt",
76
  container=False,
77
  )
 
78
  run_button = gr.Button("Run", scale=0)
79
 
80
  result = gr.Image(label="Result", show_label=False)
81
 
82
  with gr.Accordion("Advanced Settings", open=False):
 
83
  seed = gr.Slider(
84
  label="Seed",
85
  minimum=0,
 
91
  randomize_seed = gr.Checkbox(label="Randomize seed", value=True)
92
 
93
  with gr.Row():
 
94
  width = gr.Slider(
95
  label="Width",
96
  minimum=256,
 
108
  )
109
 
110
  with gr.Row():
 
111
  guidance_scale = gr.Slider(
112
  label="Guidance Scale",
113
  minimum=1,
 
125
  )
126
 
127
  gr.Examples(
128
+ examples=examples,
129
+ fn=infer,
130
+ inputs=[prompt],
131
+ outputs=[result, seed],
132
  cache_examples="lazy"
133
  )
134
 
135
  gr.on(
136
  triggers=[run_button.click, prompt.submit],
137
+ fn=infer,
138
+ inputs=[prompt, seed, randomize_seed, width, height, guidance_scale, num_inference_steps],
139
+ outputs=[result, seed]
140
  )
141
 
142
+ demo.launch()