cuio commited on
Commit
27be6a6
·
verified ·
1 Parent(s): f295564

Rename app (5).py to app.py

Browse files
Files changed (1) hide show
  1. app (5).py → app.py +151 -43
app (5).py → app.py RENAMED
@@ -1,12 +1,16 @@
1
- """FLUX.2-klein 1-step RDM — ZeroGPU demo Space (epfl-vita).
2
 
3
- Serves epfl-vita/flux2-klein-1step-rdm (our strongest 1-step student, geALLcoco-w1 s180:
4
- GenEval 0.826 vs 4-step teacher 0.794; PickScore-cv 22.76 vs 22.58). Pipeline mirrors the
5
- measured eval exactly: prompt -> Qwen3-4B ctx (adaptive len, base 48 cap 512) -> fresh noise
6
- -> 1-step flow-matching Euler -> native FLUX.2 VAE decode.
 
7
 
8
- ZeroGPU: models are lazy-loaded inside the first @spaces.GPU call and cached in-process
9
- (FP8 Qwen3 must load with a GPU present). Cold first click ~1-2 min; then a few seconds/image on ZeroGPU.
 
 
 
10
  """
11
  from __future__ import annotations
12
 
@@ -15,16 +19,21 @@ import math
15
  import os
16
  import time
17
 
18
- import spaces # must be imported before any CUDA use
19
  import gradio as gr
20
  import numpy as np
21
  import torch
22
  from huggingface_hub import hf_hub_download
23
  from PIL import Image
 
24
 
 
 
 
25
  WEIGHTS_REPO = "epfl-vita/flux2-klein-1step-rdm"
26
- AE_REPO, AE_FILE = "black-forest-labs/FLUX.2-dev", "ae.safetensors" # gated-auto; HF_TOKEN secret
27
- RES = 512
 
28
  BASE_CTX_LEN = 48
29
  TOKEN = os.environ.get("HF_TOKEN")
30
 
@@ -32,73 +41,171 @@ with open(os.path.join(os.path.dirname(__file__), "presets.json")) as f:
32
  PRESETS = json.load(f)
33
  DEFAULT_PROMPT = PRESETS[0]["prompt"]
34
 
35
- # ---- module-level downloads (network only, no GPU) ----
36
  MODEL_PATH = hf_hub_download(WEIGHTS_REPO, "model.safetensors")
37
  AE_PATH = hf_hub_download(AE_REPO, AE_FILE, token=TOKEN)
38
 
39
  _state: dict = {}
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  def _ensure_loaded():
43
  if _state:
44
  return
 
45
  from safetensors.torch import load_file
46
- from flux2.text_encoder import load_qwen3_embedder
47
  from flux2_adapter import Flux2AdapterModel, Flux2VAETokenizer
48
 
 
49
  sd = load_file(MODEL_PATH, device="cpu")
50
- model = Flux2AdapterModel(state_dict=sd, image_resolution=RES,
51
- param_dtype=torch.bfloat16).to("cpu").eval()
 
 
 
 
 
 
 
 
 
 
52
  vae = Flux2VAETokenizer(AE_PATH, device="cpu")
53
- emb = load_qwen3_embedder("4B", device="cpu")
 
 
54
  emb.eval()
 
55
  _state.update(model=model, vae=vae, emb=emb)
 
56
 
57
-
 
 
58
  def _encode(prompt: str) -> torch.Tensor:
59
  emb = _state["emb"]
60
  tok = emb.tokenizer
61
- text = tok.apply_chat_template([{"role": "user", "content": prompt}],
62
- tokenize=False, add_generation_prompt=True,
63
- enable_thinking=False)
 
 
 
 
 
 
64
  real_len = len(tok(text)["input_ids"])
 
65
  emb.max_length = min(512, max(BASE_CTX_LEN, int(math.ceil((real_len + 4) / 8) * 8)))
 
66
  with torch.no_grad():
67
- return emb([prompt]) # (1, L, 7680)
68
 
69
-
70
- @spaces.GPU(duration=120)
71
  def generate(prompt: str, seed: int, randomize: bool):
72
  prompt = (prompt or "").strip()
73
  if not prompt:
74
  raise gr.Error("Please enter a prompt (or click a preset below).")
 
75
  try:
76
  _ensure_loaded()
 
77
  if randomize:
78
  seed = int(torch.randint(0, 2**31 - 1, (1,)).item())
79
  seed = int(seed)
80
- gpu = torch.cpu.get_device_name(0).replace("NVIDIA ", "")
 
81
  torch.cpu.synchronize()
82
- t0 = time.time() # time the whole generation
83
- ctx = _encode(prompt).to("cpu") # text encode (Qwen3 ctx)
 
 
84
  g = torch.Generator(device="cpu").manual_seed(seed)
85
- noise = torch.randn(1, 128, RES // 16, RES // 16,
86
- generator=g, dtype=torch.float32, device="cpu")
 
 
 
 
 
 
 
87
  with torch.no_grad(), torch.autocast("cpu", dtype=torch.bfloat16):
88
  lat = _state["model"].sample_images_with_grad(noise, ctx, {"num_steps": 1})
89
- pix = _state["vae"].detokenize(lat) # (1,3,H,W) [0,1]
90
- arr = (pix[0].float().clamp(0, 1) * 255).round().byte().permute(1, 2, 0).cpu().numpy()
 
 
 
91
  torch.cpu.synchronize()
92
  s = time.time() - t0
93
- # generation compute only (text encode + 1-step forward + VAE decode + readback);
94
- # excludes ZeroGPU queue/attach, so the felt wait can be a few seconds longer.
 
 
95
  return Image.fromarray(arr), seed, f"{s:.1f} s · 1 step · {gpu}"
 
96
  except gr.Error:
97
  raise
98
- except Exception as e: # surface runtime errors in the UI
99
  raise gr.Error(f"{type(e).__name__}: {e}")
100
 
101
-
 
 
102
  HEADER = """
103
  <div style="text-align:center; max-width: 780px; margin: 0 auto;">
104
  <h1 style="margin-bottom: 0.2em; font-size: 2.1em;">⚡ FLUX.2-klein · <span style="
@@ -107,15 +214,15 @@ HEADER = """
107
  <p style="font-size: 1.05em; margin-top: 0.3em; opacity: 0.85;">
108
  One diffusion step, distilled with <b>Representation Distribution Matching</b> at
109
  <a href="https://www.epfl.ch/labs/vita/" target="_blank">EPFL&nbsp;VITA</a> —
110
- and it <b>beats its 4-step teacher</b>.
111
  </p>
112
  <p style="margin-top: 0.5em;">
113
  <span style="display:inline-block; background: rgba(139,92,246,.12); border: 1px solid rgba(139,92,246,.35);
114
- border-radius: 999px; padding: 3px 12px; margin: 2px;">GenEval <b>0.826</b> vs 0.794</span>
115
  <span style="display:inline-block; background: rgba(236,72,153,.10); border: 1px solid rgba(236,72,153,.35);
116
- border-radius: 999px; padding: 3px 12px; margin: 2px;">PickScore-COCO <b>22.76</b> vs 22.58</span>
117
- <span style="display:inline-block; background: rgba(16,185,129,.10); border: 1px solid rgba(16,185,129,.35);
118
- border-radius: 999px; padding: 3px 12px; margin: 2px;">single step · 1 NFE</span>
119
  <a href="https://huggingface.co/epfl-vita/flux2-klein-1step-rdm" target="_blank"
120
  style="display:inline-block; border: 1px solid rgba(120,120,120,.4); border-radius: 999px;
121
  padding: 3px 12px; margin: 2px; text-decoration: none;">🤗 model card</a>
@@ -134,7 +241,7 @@ footer { visibility: hidden; }
134
 
135
  theme = gr.themes.Soft(primary_hue="violet", secondary_hue="pink", neutral_hue="slate")
136
 
137
- with gr.Blocks(title="FLUX.2-klein 1-step RDM", theme=theme, css=CSS) as demo:
138
  gr.HTML(HEADER)
139
  with gr.Row(equal_height=False):
140
  with gr.Column(scale=5):
@@ -149,13 +256,14 @@ with gr.Blocks(title="FLUX.2-klein 1-step RDM", theme=theme, css=CSS) as demo:
149
  gr.Examples(examples=[[p["prompt"]] for p in PRESETS], inputs=[prompt],
150
  label=None, examples_per_page=8)
151
  with gr.Column(scale=4):
152
- out = gr.Image(label="512 × 512 · one step", type="pil", elem_id="out-img", height=520)
153
  with gr.Row():
154
  latency = gr.Textbox(label="Latency", interactive=False, elem_id="latency", scale=2)
155
  used_seed = gr.Number(label="Seed used", precision=0, interactive=False, scale=1)
156
- gr.HTML('<div class="pfooter">FLUX.2-klein-4B distilled 4→1 steps · first generation loads the models (~1-2 min), '
157
- 'afterwards it is instant · EPFL VITA lab</div>')
 
158
  btn.click(generate, inputs=[prompt, seed, randomize], outputs=[out, used_seed, latency])
159
  prompt.submit(generate, inputs=[prompt, seed, randomize], outputs=[out, used_seed, latency])
160
 
161
- demo.queue(max_size=40).launch()
 
1
+ """FLUX.2-klein 1-step RDM — CPU-Optimized Demo (Qwen3-0.6B)
2
 
3
+ This is a modified version of epfl-vita/flux2-klein-1step-rdm.
4
+ Changes:
5
+ 1. Replaced Qwen3-4B (8GB, FP8-dependent) with Qwen3-0.6B (1.2GB, CPU-safe).
6
+ 2. Adjusted memory handling for 16GB CPU environments.
7
+ 3. Kept 512px support (borderline on 16GB, see warnings below).
8
 
9
+ Performance expectation on 16GB CPU:
10
+ - Cold start: ~2-3 minutes (download + load).
11
+ - First generation: 60-120 seconds.
12
+ - Subsequent generations: 30-60 seconds.
13
+ - OOM Risk: High at 512px. If crashes occur, change RES to 256.
14
  """
15
  from __future__ import annotations
16
 
 
19
  import os
20
  import time
21
 
22
+ import spaces
23
  import gradio as gr
24
  import numpy as np
25
  import torch
26
  from huggingface_hub import hf_hub_download
27
  from PIL import Image
28
+ from transformers import AutoModelForCausalLM, AutoTokenizer
29
 
30
+ # =========================
31
+ # Configuration
32
+ # =========================
33
  WEIGHTS_REPO = "epfl-vita/flux2-klein-1step-rdm"
34
+ AE_REPO, AE_FILE = "black-forest-labs/FLUX.2-dev", "ae.safetensors"
35
+ RES = 512 # WARNING: 512px is borderline on 16GB CPU.
36
+ # Change to 256 if OOM occurs.
37
  BASE_CTX_LEN = 48
38
  TOKEN = os.environ.get("HF_TOKEN")
39
 
 
41
  PRESETS = json.load(f)
42
  DEFAULT_PROMPT = PRESETS[0]["prompt"]
43
 
44
+ # ---- Module-level downloads (network only, no GPU) ----
45
  MODEL_PATH = hf_hub_download(WEIGHTS_REPO, "model.safetensors")
46
  AE_PATH = hf_hub_download(AE_REPO, AE_FILE, token=TOKEN)
47
 
48
  _state: dict = {}
49
 
50
+ # ============================================================
51
+ # Qwen3-0.6B Embedder (Replacement for 4B FP8 version)
52
+ # ============================================================
53
+ class Qwen3_0_6B_Embedder:
54
+ """
55
+ CPU-safe replacement for flux2.text_encoder.load_qwen3_embedder("4B").
56
+ Uses Qwen3-0.6B (~1.2GB) instead of 4B (~8GB FP8).
57
+ Returns (1, 1, 7680) tensor to match FLUX.2 Klein expectations.
58
+ """
59
+ def __init__(self, device="cpu", torch_dtype=torch.bfloat16):
60
+ self.device = device
61
+ self.torch_dtype = torch_dtype
62
+ self.max_length = 512 # Interface compatibility with original embedder
63
+
64
+ self.tokenizer = AutoTokenizer.from_pretrained(
65
+ "Qwen/Qwen3-0.6B",
66
+ padding_side="left",
67
+ trust_remote_code=True
68
+ )
69
+ self.model = AutoModelForCausalLM.from_pretrained(
70
+ "Qwen/Qwen3-0.6B",
71
+ torch_dtype=torch_dtype,
72
+ device_map={"": device},
73
+ low_cpu_mem_usage=True,
74
+ trust_remote_code=True,
75
+ ).eval()
76
 
77
+ def __call__(self, prompts):
78
+ """
79
+ Args: prompts: list[str] (length 1)
80
+ Returns: Tensor of shape (1, 1, 7680)
81
+ """
82
+ enc = self.tokenizer(
83
+ prompts,
84
+ padding=True,
85
+ truncation=True,
86
+ max_length=self.max_length,
87
+ return_tensors="pt",
88
+ ).to(self.device)
89
+
90
+ with torch.no_grad():
91
+ out = self.model(**enc, output_hidden_states=True)
92
+ # Use second-to-last layer, last real token (standard for Qwen embedding)
93
+ hidden = out.hidden_states[-2][:, -1, :] # (1, 1024)
94
+
95
+ # FLUX.2 expects 7680-dim context.
96
+ # Original uses 3 different layers from 4B model (3x2560=7680).
97
+ # Here we repeat 0.6B hidden (1024) 3x and pad to 7680.
98
+ hidden = hidden.repeat(1, 3) # (1, 3072)
99
+ hidden = torch.nn.functional.pad(hidden, (0, 7680 - 3072)) # (1, 7680)
100
+ return hidden.unsqueeze(1) # (1, 1, 7680)
101
+
102
+ # ============================================================
103
+ # Model Loading (Cached)
104
+ # ============================================================
105
  def _ensure_loaded():
106
  if _state:
107
  return
108
+
109
  from safetensors.torch import load_file
 
110
  from flux2_adapter import Flux2AdapterModel, Flux2VAETokenizer
111
 
112
+ print("[Load] Loading FLUX.2 Klein-4B weights...")
113
  sd = load_file(MODEL_PATH, device="cpu")
114
+
115
+ model = (
116
+ Flux2AdapterModel(
117
+ state_dict=sd,
118
+ image_resolution=RES,
119
+ param_dtype=torch.bfloat16
120
+ )
121
+ .to("cpu")
122
+ .eval()
123
+ )
124
+
125
+ print("[Load] Loading VAE...")
126
  vae = Flux2VAETokenizer(AE_PATH, device="cpu")
127
+
128
+ print("[Load] Loading Qwen3-0.6B Embedder (CPU-safe)...")
129
+ emb = Qwen3_0_6B_Embedder(device="cpu", torch_dtype=torch.bfloat16)
130
  emb.eval()
131
+
132
  _state.update(model=model, vae=vae, emb=emb)
133
+ print("[Load] All models ready.")
134
 
135
+ # ============================================================
136
+ # Encoding & Generation
137
+ # ============================================================
138
  def _encode(prompt: str) -> torch.Tensor:
139
  emb = _state["emb"]
140
  tok = emb.tokenizer
141
+
142
+ # Apply Qwen3 chat template (same as original logic)
143
+ text = tok.apply_chat_template(
144
+ [{"role": "user", "content": prompt}],
145
+ tokenize=False,
146
+ add_generation_prompt=True,
147
+ enable_thinking=False
148
+ )
149
+
150
  real_len = len(tok(text)["input_ids"])
151
+ # Adaptive context length (interface compatibility)
152
  emb.max_length = min(512, max(BASE_CTX_LEN, int(math.ceil((real_len + 4) / 8) * 8)))
153
+
154
  with torch.no_grad():
155
+ return emb([prompt]) # (1, 1, 7680)
156
 
157
+ @spaces.GPU(duration=180) # Increased duration for slower CPU
 
158
  def generate(prompt: str, seed: int, randomize: bool):
159
  prompt = (prompt or "").strip()
160
  if not prompt:
161
  raise gr.Error("Please enter a prompt (or click a preset below).")
162
+
163
  try:
164
  _ensure_loaded()
165
+
166
  if randomize:
167
  seed = int(torch.randint(0, 2**31 - 1, (1,)).item())
168
  seed = int(seed)
169
+
170
+ # Use CPU timing since we are forcing CPU execution
171
  torch.cpu.synchronize()
172
+ t0 = time.time()
173
+
174
+ ctx = _encode(prompt).to("cpu")
175
+
176
  g = torch.Generator(device="cpu").manual_seed(seed)
177
+
178
+ # IMPORTANT: Use bfloat16 directly to avoid extra casting memory overhead
179
+ noise = torch.randn(
180
+ 1, 128, RES // 16, RES // 16,
181
+ generator=g,
182
+ dtype=torch.bfloat16,
183
+ device="cpu"
184
+ )
185
+
186
  with torch.no_grad(), torch.autocast("cpu", dtype=torch.bfloat16):
187
  lat = _state["model"].sample_images_with_grad(noise, ctx, {"num_steps": 1})
188
+ pix = _state["vae"].detokenize(lat)
189
+
190
+ arr = (pix[0].float().clamp(0, 1) * 255).round().byte()
191
+ arr = arr.permute(1, 2, 0).cpu().numpy()
192
+
193
  torch.cpu.synchronize()
194
  s = time.time() - t0
195
+
196
+ # Note: ZeroGPU might still show GPU name if container has GPU access,
197
+ # but computations are forced to CPU by device="cpu".
198
+ gpu = "CPU (16GB Mode)"
199
  return Image.fromarray(arr), seed, f"{s:.1f} s · 1 step · {gpu}"
200
+
201
  except gr.Error:
202
  raise
203
+ except Exception as e:
204
  raise gr.Error(f"{type(e).__name__}: {e}")
205
 
206
+ # ============================================================
207
+ # UI (Mostly unchanged from original)
208
+ # ============================================================
209
  HEADER = """
210
  <div style="text-align:center; max-width: 780px; margin: 0 auto;">
211
  <h1 style="margin-bottom: 0.2em; font-size: 2.1em;">⚡ FLUX.2-klein · <span style="
 
214
  <p style="font-size: 1.05em; margin-top: 0.3em; opacity: 0.85;">
215
  One diffusion step, distilled with <b>Representation Distribution Matching</b> at
216
  <a href="https://www.epfl.ch/labs/vita/" target="_blank">EPFL&nbsp;VITA</a> —
217
+ Running on <b>CPU (Qwen3-0.6B)</b>.
218
  </p>
219
  <p style="margin-top: 0.5em;">
220
  <span style="display:inline-block; background: rgba(139,92,246,.12); border: 1px solid rgba(139,92,246,.35);
221
+ border-radius: 999px; padding: 3px 12px; margin: 2px;">GenEval <b>0.826</b></span>
222
  <span style="display:inline-block; background: rgba(236,72,153,.10); border: 1px solid rgba(236,72,153,.35);
223
+ border-radius: 999px; padding: 3px 12px; margin: 2px;">PickScore-COCO <b>22.76</b></span>
224
+ <span style="display:inline-block; background: rgba(245,158,11,.10); border: 1px solid rgba(245,158,11,.35);
225
+ border-radius: 999px; padding: 3px 12px; margin: 2px;">⚠️ 512px Borderline</span>
226
  <a href="https://huggingface.co/epfl-vita/flux2-klein-1step-rdm" target="_blank"
227
  style="display:inline-block; border: 1px solid rgba(120,120,120,.4); border-radius: 999px;
228
  padding: 3px 12px; margin: 2px; text-decoration: none;">🤗 model card</a>
 
241
 
242
  theme = gr.themes.Soft(primary_hue="violet", secondary_hue="pink", neutral_hue="slate")
243
 
244
+ with gr.Blocks(title="FLUX.2-klein 1-step RDM (CPU)", theme=theme, css=CSS) as demo:
245
  gr.HTML(HEADER)
246
  with gr.Row(equal_height=False):
247
  with gr.Column(scale=5):
 
256
  gr.Examples(examples=[[p["prompt"]] for p in PRESETS], inputs=[prompt],
257
  label=None, examples_per_page=8)
258
  with gr.Column(scale=4):
259
+ out = gr.Image(label=f"{RES} × {RES} · one step", type="pil", elem_id="out-img", height=520)
260
  with gr.Row():
261
  latency = gr.Textbox(label="Latency", interactive=False, elem_id="latency", scale=2)
262
  used_seed = gr.Number(label="Seed used", precision=0, interactive=False, scale=1)
263
+ gr.HTML('<div class="pfooter">FLUX.2-klein-4B distilled 4→1 steps · Qwen3-0.6B for CPU · '
264
+ 'First generation loads models (~2-3 min) · EPFL VITA lab</div>')
265
+
266
  btn.click(generate, inputs=[prompt, seed, randomize], outputs=[out, used_seed, latency])
267
  prompt.submit(generate, inputs=[prompt, seed, randomize], outputs=[out, used_seed, latency])
268
 
269
+ demo.queue(max_size=40).launch()