multimodalart HF Staff commited on
Commit
eb54a52
·
verified ·
1 Parent(s): ef503fc

Upload app.py with huggingface_hub

Browse files
Files changed (1) hide show
  1. app.py +696 -0
app.py ADDED
@@ -0,0 +1,696 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+
3
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
4
+
5
+ import spaces # noqa: E402 -- must precede torch / CUDA imports
6
+ import torch # noqa: E402
7
+
8
+ # PersonaLive ships full-pickle .pth checkpoints; torch>=2.6 defaults weights_only=True.
9
+ _orig_torch_load = torch.load
10
+ def _patched_torch_load(*args, **kwargs):
11
+ kwargs.setdefault("weights_only", False)
12
+ return _orig_torch_load(*args, **kwargs)
13
+ torch.load = _patched_torch_load
14
+
15
+ # diffusers 0.27 / transformers 4.36 reference huggingface_hub symbols removed in
16
+ # hub>=1.0 (forced upon us by gradio 6). Re-inject them before those libs import.
17
+ import huggingface_hub as _hub # noqa: E402
18
+ if not hasattr(_hub, "cached_download"):
19
+ _hub.cached_download = _hub.hf_hub_download
20
+ if not hasattr(_hub, "HfFolder"):
21
+ class _HfFolder:
22
+ @staticmethod
23
+ def get_token():
24
+ return _hub.get_token()
25
+ _hub.HfFolder = _HfFolder
26
+
27
+ import sys # noqa: E402
28
+ import time # noqa: E402
29
+ from types import SimpleNamespace # noqa: E402
30
+
31
+ import cv2 # noqa: E402
32
+ import numpy as np # noqa: E402
33
+ import gradio as gr # noqa: E402
34
+ from PIL import Image # noqa: E402
35
+
36
+ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
37
+
38
+ # ---- weights (downloaded once at startup, no GPU needed) ----
39
+ from tools.download_weights import prepare_base_model, prepare_vae, prepare_personalive # noqa: E402
40
+
41
+ prepare_base_model()
42
+ prepare_vae()
43
+ prepare_personalive()
44
+
45
+ CONFIG_PATH = "./configs/prompts/personalive_online.yaml"
46
+ ARGS = SimpleNamespace(config_path=CONFIG_PATH, acceleration="none")
47
+ CHUNK = 4 # temporal_window_size: frames consumed/produced per diffusion call
48
+
49
+ _model = None
50
+ def get_model():
51
+ """Lazy, in-worker init. This is a held-session model, so the init cost is
52
+ paid once per cold GPU worker and amortized across the whole session -
53
+ module-scope init would gain nothing here and risks main-process CUDA init."""
54
+ global _model
55
+ if _model is None:
56
+ from src.wrapper import PersonaLive
57
+ t0 = time.perf_counter()
58
+ _model = PersonaLive(ARGS, device="cuda")
59
+ print(f"[model] loaded in {time.perf_counter() - t0:.1f}s", flush=True)
60
+ return _model
61
+
62
+
63
+ AOTI_REPO = "multimodalart/PersonaLive-aoti"
64
+ _aoti_lazy = None
65
+ _aoti_bank_map = None
66
+
67
+
68
+ def _load_aoti():
69
+ """Download + open the AoTI kernel package once. The .pt2 holds only
70
+ hardware-specific kernels (no weights); constants are supplied per-fuse."""
71
+ global _aoti_lazy, _aoti_bank_map
72
+ if _aoti_lazy is None:
73
+ import json
74
+ from pathlib import Path
75
+ from huggingface_hub import snapshot_download
76
+ from spaces.zero.torch.aoti import LazyAOTIModel
77
+
78
+ repo = snapshot_download(AOTI_REPO, allow_patterns="package/*")
79
+ pkg = Path(repo) / "package"
80
+ meta = json.loads((pkg / "bank_constants.json").read_text())
81
+ _aoti_bank_map = meta["bank_constants"]
82
+ _aoti_lazy = LazyAOTIModel(str(pkg / "submodules" / "denoising_unet" / "package.pt2"))
83
+ print(f"[aoti] loaded kernels, {len(_aoti_bank_map)} bank constants", flush=True)
84
+ return _aoti_lazy, _aoti_bank_map
85
+
86
+
87
+ def patch_unet_aoti(model):
88
+ """Patch denoising_unet.forward with the AoTI kernel. Must run AFTER fuse_reference
89
+ (reference banks populated) and with keyframes disabled (model.num_khf=3) so the
90
+ bank set matches the compiled graph. Reference banks (the 16 lifted constants) are
91
+ supplied live from each block's bank[0] -> portrait-agnostic kernel."""
92
+ lazy, bank_map = _load_aoti()
93
+ unet = model.denoising_unet
94
+ weights = {}
95
+ for n, p in unet.named_parameters(remove_duplicate=False):
96
+ weights[n] = p
97
+ for n, b in unet.named_buffers(remove_duplicate=False):
98
+ weights[n] = b
99
+ # The compiled model references the reference banks as flat constants
100
+ # `_tensor_constant{i}` (NOT the export-time `lifted_tensor_N` FQN). Supply both
101
+ # names; LazyAOTIModel filters to the set the kernel actually wants. Order the
102
+ # blocks by the lifted index so `_tensor_constant{i}` gets block i's bank.
103
+ ordered_blocks = [bank_map[k] for k in sorted(
104
+ bank_map, key=lambda k: int(k.rsplit("lifted_tensor_", 1)[1]))]
105
+ for fqn, block_path in bank_map.items():
106
+ weights[fqn] = unet.get_submodule(block_path).bank[0]
107
+ for i, block_path in enumerate(ordered_blocks):
108
+ weights[f"_tensor_constant{i}"] = unet.get_submodule(block_path).bank[0]
109
+ unet.forward = lazy.with_weights(weights)
110
+
111
+
112
+ def _frame_to_input(rgb: np.ndarray) -> torch.Tensor:
113
+ """RGB uint8 HxWx3 -> (1,3,512,512) float in [-1,1] on cuda. Mirrors the
114
+ transform the original websocket server applied to driving frames."""
115
+ rgb = cv2.resize(rgb, (512, 512), interpolation=cv2.INTER_AREA)
116
+ t = torch.from_numpy(rgb).to("cuda").float() / 255.0
117
+ t = t * 2.0 - 1.0
118
+ return t.permute(2, 0, 1).unsqueeze(0)
119
+
120
+
121
+ @spaces.GPU(duration=180)
122
+ def selftest(num_frames: int):
123
+ """Validate the model end-to-end on the bundled demo assets: fuse the demo
124
+ reference portrait, then animate it with the demo driving video. Returns a
125
+ few output frames plus timing so we can size GPU duration / measure fps."""
126
+ model = get_model()
127
+ model.reset()
128
+
129
+ ref = Image.open("demo/ref_image.png").convert("RGB")
130
+ t0 = time.perf_counter()
131
+ model.fuse_reference(ref)
132
+ fuse_s = time.perf_counter() - t0
133
+
134
+ cap = cv2.VideoCapture("demo/driving_video.mp4")
135
+ frames = []
136
+ while len(frames) < num_frames:
137
+ ok, bgr = cap.read()
138
+ if not ok:
139
+ break
140
+ frames.append(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
141
+ cap.release()
142
+
143
+ outputs = []
144
+ gen_t0 = time.perf_counter()
145
+ n_chunks = len(frames) // CHUNK
146
+ for c in range(n_chunks):
147
+ batch = [_frame_to_input(frames[c * CHUNK + i]) for i in range(CHUNK)]
148
+ video = model.process_input(torch.cat(batch, dim=0)) # (CHUNK,h,w,c) in [0,1]
149
+ for img in video:
150
+ outputs.append(Image.fromarray((img * 255.0).astype(np.uint8)))
151
+ gen_s = time.perf_counter() - gen_t0
152
+
153
+ produced = len(outputs)
154
+ fps = produced / gen_s if gen_s > 0 else 0.0
155
+ report = (
156
+ f"fuse: {fuse_s:.1f}s | generated {produced} frames in {gen_s:.1f}s "
157
+ f"({fps:.1f} fps) | per-chunk {gen_s / max(n_chunks,1):.2f}s"
158
+ )
159
+ print("[selftest]", report, flush=True)
160
+ return outputs[:8], report
161
+
162
+
163
+ def _describe(x):
164
+ if torch.is_tensor(x):
165
+ return f"T{tuple(x.shape)}:{x.dtype}"
166
+ if isinstance(x, (list, tuple)):
167
+ return [_describe(i) for i in x]
168
+ if isinstance(x, dict):
169
+ return {k: _describe(v) for k, v in x.items()}
170
+ return repr(x)
171
+
172
+
173
+ @spaces.GPU(duration=300)
174
+ def export_probe():
175
+ """Feasibility probe: capture the real denoising_unet inputs during a live
176
+ chunk, then attempt torch.export.export on it. denoising_unet is the per-chunk
177
+ bottleneck and the AoTI target; its hacked attention reads reference banks
178
+ (self.bank/self.kv_bank) so we need to know empirically whether it traces."""
179
+ import traceback
180
+
181
+ model = get_model()
182
+ model.reset()
183
+ model.fuse_reference(Image.open("demo/ref_image.png").convert("RGB"))
184
+
185
+ cap = cv2.VideoCapture("demo/driving_video.mp4")
186
+ frames = []
187
+ while len(frames) < CHUNK:
188
+ ok, bgr = cap.read()
189
+ if not ok:
190
+ break
191
+ frames.append(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
192
+ cap.release()
193
+ batch = torch.cat([_frame_to_input(frames[i]) for i in range(CHUNK)], dim=0)
194
+
195
+ unet = model.denoising_unet
196
+ with spaces.aoti_capture(unet) as call:
197
+ model.process_input(batch)
198
+ args, kwargs = call.args, call.kwargs
199
+
200
+ log = [
201
+ f"torch {torch.__version__}",
202
+ f"captured args: {_describe(list(args))}",
203
+ f"captured kwargs: {_describe(kwargs)}",
204
+ ]
205
+ try:
206
+ ep = torch.export.export(unet, args, kwargs)
207
+ n_nodes = len(list(ep.graph.nodes))
208
+ log.append(f"EXPORT OK — graph nodes: {n_nodes}")
209
+
210
+ # Lifted constants: non-buffer tensor attributes (the reference banks live
211
+ # here). For one .pt2 to serve any portrait these must be swappable at load.
212
+ consts = dict(getattr(ep, "constants", {}) or {})
213
+ lifted = {k: v for k, v in consts.items()
214
+ if torch.is_tensor(v) and k.rsplit(".", 1)[-1].startswith("lifted_tensor")}
215
+ log.append(f"#constants: {len(consts)} | #lifted_tensor: {len(lifted)}")
216
+
217
+ # For each lifted constant, derive its block path and compare against that
218
+ # block's live self.bank — this validates the loader's FQN->bank mapping.
219
+ match = mismatch = 0
220
+ for fqn, ct in list(lifted.items()):
221
+ block_path = fqn.rsplit(".", 1)[0]
222
+ try:
223
+ blk = unet.get_submodule(block_path)
224
+ except Exception as e:
225
+ log.append(f" {fqn}: get_submodule FAIL {e}")
226
+ mismatch += 1
227
+ continue
228
+ bank = getattr(blk, "bank", None)
229
+ kvb = getattr(blk, "kv_bank", None)
230
+ blen = len(bank) if isinstance(bank, list) else ("None" if bank is None else "?")
231
+ bshape = tuple(bank[0].shape) if isinstance(bank, list) and bank else None
232
+ ok = bshape == tuple(ct.shape)
233
+ match += int(ok)
234
+ mismatch += int(not ok)
235
+ if len(lifted) <= 4 or mismatch <= 3 or match <= 2:
236
+ log.append(f" {fqn} const{tuple(ct.shape)} | bank len={blen} "
237
+ f"bank0={bshape} kv_bank={'None' if kvb is None else tuple(kvb.shape)} "
238
+ f"{'OK' if ok else 'MISMATCH'}")
239
+ log.append(f"bank-shape match: {match}/{len(lifted)}")
240
+ except Exception:
241
+ log.append("EXPORT FAILED:\n" + traceback.format_exc()[-3500:])
242
+
243
+ report = "\n".join(log)
244
+ print("[export_probe]\n" + report, flush=True)
245
+ return report
246
+
247
+
248
+ def _read_frames(n):
249
+ cap = cv2.VideoCapture("demo/driving_video.mp4")
250
+ frames = []
251
+ while len(frames) < n:
252
+ ok, bgr = cap.read()
253
+ if not ok:
254
+ break
255
+ frames.append(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
256
+ cap.release()
257
+ return frames
258
+
259
+
260
+ @spaces.GPU(duration=300)
261
+ def aoti_test(num_frames: int):
262
+ """Verify the AoTI kernel: (1) numerical match vs eager on one captured chunk,
263
+ (2) end-to-end animated frames + fps with AoTI patched in."""
264
+ model = get_model()
265
+ model.reset()
266
+ model.fuse_reference(Image.open("demo/ref_image.png").convert("RGB"))
267
+ model.num_khf = 3 # disable keyframes (match compile-time bank set)
268
+
269
+ frames = _read_frames(max(num_frames, CHUNK))
270
+ unet = model.denoising_unet
271
+ # Once patch_unet_aoti overwrites unet.forward (instance attr), the eager path is
272
+ # only reachable via the class method. Bind it so each portrait's eager reference
273
+ # is the real network, not a stale AoTI wrapper from a previous portrait.
274
+ eager_forward = type(unet).forward
275
+
276
+ def check(tag, ref_img):
277
+ model.reset()
278
+ model.fuse_reference(ref_img)
279
+ model.num_khf = 3
280
+ batch = torch.cat([_frame_to_input(frames[i]) for i in range(CHUNK)], dim=0)
281
+ with spaces.aoti_capture(unet) as cap:
282
+ model.process_input(batch)
283
+ a, k = cap.args, cap.kwargs
284
+ with torch.no_grad():
285
+ eager = eager_forward(unet, *a, **k)[0].float()
286
+ patch_unet_aoti(model) # supplies THIS portrait's banks live
287
+ with torch.no_grad():
288
+ aoti = unet(*a, **k)[0].float()
289
+ d = (eager - aoti).abs()
290
+ rel = (d.max() / (eager.abs().max() + 1e-6)).item()
291
+ return (f"[{tag}] max|eager-aoti|={d.max().item():.4e} mean={d.mean().item():.4e} "
292
+ f"rel={rel:.4e} | eager range [{eager.min():.3f},{eager.max():.3f}]")
293
+
294
+ # demo-ref = the portrait the kernel was COMPILED against (baked-on-disk constants
295
+ # happen to equal these banks). alt-ref = a different portrait; a small diff there
296
+ # proves the 16 banks are supplied live per-fuse, not baked into the kernel.
297
+ log = [check("demo-ref", Image.open("demo/ref_image.png").convert("RGB"))]
298
+ log.append(check("alt-ref ", Image.fromarray(frames[len(frames) // 2])))
299
+
300
+ # End-to-end AoTI generation + fps (fresh session, AoTI stays patched).
301
+ model.reset()
302
+ model.fuse_reference(Image.open("demo/ref_image.png").convert("RGB"))
303
+ model.num_khf = 3
304
+ patch_unet_aoti(model) # rebuild bank map for the fresh fuse
305
+ outputs = []
306
+ n_chunks = len(frames) // CHUNK
307
+ t0 = time.perf_counter()
308
+ for c in range(n_chunks):
309
+ batch = torch.cat([_frame_to_input(frames[c * CHUNK + i]) for i in range(CHUNK)], dim=0)
310
+ video = model.process_input(batch)
311
+ for img in video:
312
+ outputs.append(Image.fromarray((img * 255.0).astype(np.uint8)))
313
+ gen_s = time.perf_counter() - t0
314
+ fps = len(outputs) / gen_s if gen_s > 0 else 0.0
315
+ log.append(f"AoTI e2e: {len(outputs)} frames in {gen_s:.1f}s ({fps:.1f} fps) "
316
+ f"| per-chunk {gen_s/max(n_chunks,1):.2f}s")
317
+ report = "\n".join(log)
318
+ print("[aoti_test]\n" + report, flush=True)
319
+ return outputs[:8], report
320
+
321
+
322
+ @spaces.GPU(duration=180)
323
+ def aoti_fqns():
324
+ """Diagnostic: what constant FQNs does the compiled package actually demand,
325
+ and do they intersect the names I supply (params/buffers/lifted/_tensor_constant)?
326
+ Also dump the baked-on-disk constant values' fingerprint to see if a no-op
327
+ load_constants would silently fall back to compile-time (demo) banks."""
328
+ import json
329
+ from pathlib import Path
330
+ from huggingface_hub import snapshot_download
331
+
332
+ model = get_model()
333
+ model.reset()
334
+ model.fuse_reference(Image.open("demo/ref_image.png").convert("RGB"))
335
+ model.num_khf = 3
336
+ unet = model.denoising_unet
337
+
338
+ repo = snapshot_download(AOTI_REPO, allow_patterns="package/*")
339
+ pkg = Path(repo) / "package"
340
+ bank_map = json.loads((pkg / "bank_constants.json").read_text())["bank_constants"]
341
+ pt2 = str(pkg / "submodules" / "denoising_unet" / "package.pt2")
342
+
343
+ cm = torch._inductor.aoti_load_package(pt2)
344
+ fqns = list(cm.get_constant_fqns())
345
+
346
+ supplied = set()
347
+ for n, _ in unet.named_parameters(remove_duplicate=False):
348
+ supplied.add(n)
349
+ for n, _ in unet.named_buffers(remove_duplicate=False):
350
+ supplied.add(n)
351
+ supplied |= set(bank_map.keys())
352
+ supplied |= {f"_tensor_constant{i}" for i in range(len(bank_map))}
353
+
354
+ missing = [f for f in fqns if f not in supplied]
355
+ log = [
356
+ f"#constant_fqns={len(fqns)} | #supplied_names={len(supplied)} | #missing={len(missing)}",
357
+ f"sample fqns: {fqns[:8]}",
358
+ f"tail fqns: {fqns[-8:]}",
359
+ f"#_tensor_constant in fqns: {sum(1 for f in fqns if f.startswith('_tensor_constant'))}",
360
+ f"#lifted_tensor in fqns: {sum(1 for f in fqns if 'lifted_tensor' in f)}",
361
+ f"missing (first 20): {missing[:20]}",
362
+ ]
363
+ report = "\n".join(log)
364
+ print("[aoti_fqns]\n" + report, flush=True)
365
+ return report
366
+
367
+
368
+ import multiprocessing as _mp # noqa: E402
369
+ import threading as _threading # noqa: E402
370
+
371
+ # Fork-context queues created at import (in the main process). The spaces lib forks its
372
+ # GPU worker with multiprocessing.get_context('fork'), so a worker forked AFTER these
373
+ # exist inherits the live pipe fds -> the parent (WS handler) can feed a held GPU worker.
374
+ _QCTX = _mp.get_context("fork")
375
+ PROBE_IN = _QCTX.Queue()
376
+ PROBE_OUT = _QCTX.Queue()
377
+
378
+
379
+ @spaces.GPU(duration=40)
380
+ def _queue_worker():
381
+ """Held GPU worker: block waiting for an item the PARENT pushes AFTER we've forked.
382
+ If this receives it, module-global fork-queues bridge the ZeroGPU fork boundary -
383
+ which is the whole basis for feeding live WS frames into a held @spaces.GPU session."""
384
+ t0 = time.time()
385
+ got = PROBE_IN.get(timeout=25)
386
+ PROBE_OUT.put(f"worker pid={os.getpid()} got={got!r} after {time.time()-t0:.1f}s")
387
+ return "ok"
388
+
389
+
390
+ def queue_probe():
391
+ """Parent side: fork the GPU worker (in a thread so it blocks on get), then push a
392
+ live item and confirm the worker received it across the fork boundary."""
393
+ th = _threading.Thread(target=_queue_worker, daemon=True)
394
+ th.start()
395
+ time.sleep(4) # let the worker fork and reach PROBE_IN.get()
396
+ PROBE_IN.put(f"live-{int(time.time())}-from-pid-{os.getpid()}")
397
+ th.join(timeout=30)
398
+ try:
399
+ res = PROBE_OUT.get(timeout=8)
400
+ except Exception as e:
401
+ res = f"NO OUTPUT FROM WORKER: {type(e).__name__} {e}"
402
+ report = f"parent pid={os.getpid()}\n{res}"
403
+ print("[queue_probe]\n" + report, flush=True)
404
+ return report
405
+
406
+
407
+ # ---- Held-session machinery (the real WS backend runs on these) ----
408
+ # Parent (WS handler) <-> held GPU worker, bridged by fork-inherited queues.
409
+ SESS_IN = _QCTX.Queue() # parent->worker: driving RGB frames (np.uint8 HxWx3)
410
+ SESS_OUT = _QCTX.Queue() # worker->parent: ("ready"|"frame"|"error", payload)
411
+ SESS_REF = _QCTX.Queue() # parent->worker: reference PIL.Image to fuse
412
+
413
+
414
+ @spaces.GPU(duration=120)
415
+ def session_worker():
416
+ """Held GPU session: the original generate_process loop, AoTI-accelerated, fed live
417
+ via fork-queues instead of a raw mp.Process. Inits the model, blocks for a reference,
418
+ fuses + AoTI-patches, then consumes driving frames in CHUNK batches and emits frames.
419
+ Holds the GPU only as long as the session runs (early-returns on the stop sentinel)."""
420
+ import traceback
421
+ try:
422
+ model = get_model()
423
+ model.reset()
424
+ ref = SESS_REF.get() # block until parent supplies a reference
425
+ model.fuse_reference(ref)
426
+ model.num_khf = 3 # pin keyframes off (AoTI bank set is fixed)
427
+ patch_unet_aoti(model)
428
+ SESS_OUT.put(("ready", os.getpid()))
429
+ buf = []
430
+ while True:
431
+ item = SESS_IN.get()
432
+ if item is None: # stop sentinel
433
+ break
434
+ buf.append(item)
435
+ if len(buf) >= CHUNK:
436
+ chunk, buf = buf[:CHUNK], buf[CHUNK:]
437
+ batch = torch.cat([_frame_to_input(f) for f in chunk], dim=0)
438
+ video = model.process_input(batch)
439
+ for img in video:
440
+ SESS_OUT.put(("frame", (img * 255.0).astype(np.uint8)))
441
+ except Exception:
442
+ SESS_OUT.put(("error", traceback.format_exc()[-2000:]))
443
+ finally:
444
+ SESS_OUT.put(("done", None))
445
+
446
+
447
+ @spaces.GPU(duration=120)
448
+ def gpu_fuse():
449
+ """Cross-call state experiment, step 1: init model + fuse a reference inside one
450
+ @spaces.GPU call, then RETURN (releasing the GPU). Records the worker pid and the
451
+ model object id so step 2 can tell whether the worker (and its CUDA state) persists."""
452
+ global _model
453
+ model = get_model()
454
+ model.reset()
455
+ model.fuse_reference(Image.open("demo/ref_image.png").convert("RGB"))
456
+ model.num_khf = 3
457
+ report = (f"pid={os.getpid()} id(_model)={id(_model)} "
458
+ f"ref_latents={hasattr(model, 'ref_image_latents')} "
459
+ f"motion_bank={'set' if getattr(model, 'motion_bank', None) is not None else 'None'}")
460
+ print("[gpu_fuse]", report, flush=True)
461
+ return report
462
+
463
+
464
+ @spaces.GPU(duration=120)
465
+ def gpu_step():
466
+ """Cross-call state experiment, step 2: in a SEPARATE @spaces.GPU call, try to run
467
+ process_input WITHOUT re-fusing. If the worker persisted, _model is already fused
468
+ and this produces a valid frame -> per-chunk @spaces.GPU architecture is viable
469
+ (state survives across calls). If the worker is fresh, _model is None / unfused and
470
+ this reveals that we need a held session instead."""
471
+ global _model
472
+ was_none = _model is None
473
+ log = [f"pid={os.getpid()} _model_was_none={was_none}"]
474
+ try:
475
+ model = get_model()
476
+ log.append(f"id(_model)={id(_model)} ref_latents={hasattr(model, 'ref_image_latents')}")
477
+ frames = _read_frames(CHUNK)
478
+ batch = torch.cat([_frame_to_input(frames[i]) for i in range(CHUNK)], dim=0)
479
+ video = model.process_input(batch)
480
+ log.append(f"process_ok frames={len(video)} mean={float(np.mean(video)):.4f} "
481
+ f"range=[{float(np.min(video)):.3f},{float(np.max(video)):.3f}]")
482
+ except Exception as e:
483
+ import traceback
484
+ log.append("PROCESS FAILED:\n" + traceback.format_exc()[-1500:])
485
+ report = "\n".join(log)
486
+ print("[gpu_step]\n" + report, flush=True)
487
+ return report
488
+
489
+
490
+ # ==================== Real-time WebSocket backend ====================
491
+ # Keeps PersonaLive's own Svelte frontend + WS transport. The held GPU session
492
+ # (session_worker) runs in a parent-side thread fed by the fork-queues above; the
493
+ # visitor's X-IP-Token (minted by the huggingface.co parent via postMessage and
494
+ # forwarded over the WS) is injected into LocalContext.request so spaces.schedule
495
+ # bills the right HF account instead of falling back to the Space's IP quota.
496
+ import asyncio # noqa: E402
497
+ import json # noqa: E402
498
+ import queue as _queue # noqa: E402
499
+ from io import BytesIO # noqa: E402
500
+
501
+ from fastapi import File, UploadFile, WebSocket, WebSocketDisconnect # noqa: E402
502
+ from fastapi.responses import JSONResponse # noqa: E402
503
+ from fastapi.staticfiles import StaticFiles # noqa: E402
504
+ from gradio.context import LocalContext # noqa: E402
505
+
506
+
507
+ class _IPHeaders(dict):
508
+ """spaces._get_headers requires request.headers to have BOTH __dict__ (a plain
509
+ dict lacks it) AND .get -> a dict SUBCLASS satisfies both. See
510
+ reference_zerogpu_xiptoken_handshake."""
511
+
512
+
513
+ def _ip_request(token):
514
+ if not token:
515
+ return None
516
+ req = SimpleNamespace()
517
+ req.headers = _IPHeaders()
518
+ req.headers["x-ip-token"] = token
519
+ return req
520
+
521
+
522
+ def _drain(q):
523
+ try:
524
+ while True:
525
+ q.get_nowait()
526
+ except Exception:
527
+ pass
528
+
529
+
530
+ _PENDING_REF = None # set by /api/upload_reference_image, fused at WS open
531
+ _session_busy = _threading.Lock()
532
+
533
+
534
+ def _run_session(token):
535
+ """Background thread: set the GPU-quota context for THIS thread (contextvars don't
536
+ propagate across threads), then enter the held @spaces.GPU session_worker."""
537
+ req = _ip_request(token)
538
+ if req is not None:
539
+ LocalContext.request.set(req)
540
+ session_worker()
541
+
542
+
543
+ # gr.Server (gradio 6) inherits from FastAPI, so .get/.post/.websocket/.mount work
544
+ # directly while keeping Gradio's queue + ZeroGPU scheduling. demo=app below; the HF
545
+ # runtime launches it (no separate uvicorn -> avoids the 7860 double-bind).
546
+ app = gr.Server(title="PersonaLive")
547
+
548
+
549
+ @app.get("/api/settings")
550
+ async def settings():
551
+ # Minimal shape the Svelte frontend reads (image input mode, no extra params).
552
+ return JSONResponse({
553
+ "info": {"properties": {"input_mode": {"default": "image"}}},
554
+ "input_params": {"properties": {}},
555
+ "max_queue_size": 1,
556
+ "page_content": "",
557
+ })
558
+
559
+
560
+ @app.get("/api/queue")
561
+ async def queue_size():
562
+ return JSONResponse({"queue_size": 1 if _session_busy.locked() else 0})
563
+
564
+
565
+ @app.post("/api/upload_reference_image")
566
+ async def upload_reference_image(ref_image: UploadFile = File(...)):
567
+ global _PENDING_REF
568
+ data = await ref_image.read()
569
+ _PENDING_REF = Image.open(BytesIO(data)).convert("RGB")
570
+ return JSONResponse({"status": "ok"})
571
+
572
+
573
+ @app.post("/api/reset")
574
+ async def reset():
575
+ global _PENDING_REF
576
+ _PENDING_REF = None
577
+ return JSONResponse({"status": "ok"})
578
+
579
+
580
+ @app.websocket("/api/ws/{user_id}")
581
+ async def ws_endpoint(websocket: WebSocket, user_id: str):
582
+ await websocket.accept()
583
+ if not _session_busy.acquire(blocking=False):
584
+ await websocket.send_text(json.dumps({"status": "timeout"}))
585
+ await websocket.close()
586
+ return
587
+
588
+ loop = asyncio.get_event_loop()
589
+ send_task = None
590
+ try:
591
+ # 1. first text frame carries the visitor's X-IP-Token (for GPU quota).
592
+ token = None
593
+ try:
594
+ first = await asyncio.wait_for(websocket.receive_text(), timeout=15)
595
+ token = json.loads(first).get("x_ip_token")
596
+ except Exception:
597
+ pass
598
+
599
+ ref = _PENDING_REF
600
+ if ref is None:
601
+ await websocket.send_text(json.dumps(
602
+ {"status": "error", "message": "Upload a reference portrait first."}))
603
+ return
604
+
605
+ # 2. start the held GPU session and wait for it to fuse + be ready.
606
+ _drain(SESS_IN); _drain(SESS_OUT); _drain(SESS_REF)
607
+ SESS_REF.put(ref)
608
+ _threading.Thread(target=_run_session, args=(token,), daemon=True).start()
609
+
610
+ # Cold start loads the model in-worker (~21s). Send heartbeats while we
611
+ # wait so the client's WS keepalive ping doesn't time out on the silence.
612
+ ready = None
613
+ while ready is None:
614
+ try:
615
+ ready = await loop.run_in_executor(
616
+ None, lambda: SESS_OUT.get(timeout=2))
617
+ except _queue.Empty:
618
+ await websocket.send_text(json.dumps({"status": "loading"}))
619
+ if ready[0] != "ready":
620
+ await websocket.send_text(json.dumps(
621
+ {"status": "error", "message": f"session start failed: {ready}"}))
622
+ return
623
+ await websocket.send_text(json.dumps({"status": "connected"}))
624
+ await websocket.send_text(json.dumps({"status": "send_frame"}))
625
+
626
+ # 3. worker -> client: stream generated frames as JPEG.
627
+ async def sender():
628
+ while True:
629
+ kind, payload = await loop.run_in_executor(None, SESS_OUT.get)
630
+ if kind == "frame":
631
+ bgr = cv2.cvtColor(payload, cv2.COLOR_RGB2BGR)
632
+ ok, jpg = cv2.imencode(".jpg", bgr)
633
+ if ok:
634
+ await websocket.send_bytes(jpg.tobytes())
635
+ elif kind == "error":
636
+ await websocket.send_text(json.dumps(
637
+ {"status": "error", "message": str(payload)[:500]}))
638
+ break
639
+ elif kind == "done":
640
+ break
641
+
642
+ send_task = asyncio.create_task(sender())
643
+
644
+ # 4. client -> worker: decode driving JPEGs, prefer-latest (drop backlog so the
645
+ # ~20fps client doesn't outrun the ~6.8fps model and pile up latency).
646
+ while True:
647
+ msg = await websocket.receive()
648
+ if msg.get("type") == "websocket.disconnect":
649
+ break
650
+ if msg.get("bytes"):
651
+ arr = np.frombuffer(msg["bytes"], np.uint8)
652
+ bgr = cv2.imdecode(arr, cv2.IMREAD_COLOR)
653
+ if bgr is not None:
654
+ if SESS_IN.qsize() <= CHUNK * 2:
655
+ SESS_IN.put(cv2.cvtColor(bgr, cv2.COLOR_BGR2RGB))
656
+ elif msg.get("text"):
657
+ try:
658
+ if json.loads(msg["text"]).get("status") == "resume":
659
+ await websocket.send_text(json.dumps({"status": "send_frame"}))
660
+ except Exception:
661
+ pass
662
+ except WebSocketDisconnect:
663
+ pass
664
+ except Exception as e:
665
+ print(f"[ws] error: {e}", flush=True)
666
+ finally:
667
+ SESS_IN.put(None) # stop sentinel -> worker exits -> releases GPU slot
668
+ if send_task is not None:
669
+ send_task.cancel()
670
+ _session_busy.release()
671
+
672
+
673
+ @app.get("/api/health")
674
+ async def health():
675
+ # Quick liveness probe (no GPU): confirms the server + routes are up.
676
+ return JSONResponse({"status": "ok", "session_busy": _session_busy.locked()})
677
+
678
+
679
+ @app.get("/api/selftest")
680
+ async def selftest_route(num_frames: int = 16):
681
+ # Debug-only: run the eager self-test (no X-IP-Token -> creator IP quota) so the
682
+ # model path can be validated via curl without the frontend.
683
+ loop = asyncio.get_event_loop()
684
+ _, report = await loop.run_in_executor(None, selftest, num_frames)
685
+ return JSONResponse({"report": report})
686
+
687
+
688
+ # Serve PersonaLive's Svelte build at "/". Registered last so the /api routes above win.
689
+ # Requires GRADIO_SSR_MODE=false (env) for gr.Server to yield "/" to a custom handler.
690
+ _FRONTEND_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), "frontend_public")
691
+ if os.path.isdir(_FRONTEND_DIR):
692
+ app.mount("/", StaticFiles(directory=_FRONTEND_DIR, html=True), name="frontend")
693
+
694
+ demo = app # HF runtime launches `demo`
695
+ if __name__ == "__main__":
696
+ demo.launch(ssr_mode=False)