ming0531 commited on
Commit
9c00052
·
verified ·
1 Parent(s): 1e5e985

One GPU call per clip; depth and rendering in batches of 8 frames

Browse files
Files changed (2) hide show
  1. app.py +8 -23
  2. engine.py +63 -24
app.py CHANGED
@@ -20,26 +20,13 @@ MAX_SECONDS = 5.0
20
  GREEN = np.array([72, 164, 63], np.float32)
21
 
22
 
23
- def _track_seconds(frames, *args): # measured on ZeroGPU: about 0.27 s per frame (150 frames at 768 px: 40 s)
24
- return int(min(120, 15 + 0.35 * len(frames)))
25
 
26
 
27
- def _render_seconds(frames, *args): # about 0.11 s per frame at 768 px, plus ~10 s to build the Triton kernel once
28
- return int(min(120, 25 + 0.15 * len(frames)))
29
-
30
-
31
- @spaces.GPU(duration=_track_seconds)
32
- def gpu_track(frames, prompt, point):
33
- t0 = time.perf_counter()
34
- subject, others = engine.track(frames, prompt, point)
35
- return subject, others, time.perf_counter() - t0
36
-
37
-
38
- @spaces.GPU(duration=_render_seconds)
39
- def gpu_spotlight(frames, subject, others, strength, gap):
40
- t0 = time.perf_counter()
41
- out, depth = engine.spotlight(frames, subject, others, strength=strength, gap=gap)
42
- return out, depth, time.perf_counter() - t0
43
 
44
 
45
  def mark(image, point):
@@ -101,14 +88,12 @@ def run(state, prompt, start, seconds, long_side, strength, gap, progress=gr.Pro
101
  frames, fps = engine.read_clip(state["video"], seconds, int(long_side), start=start)
102
  if len(frames) == 0:
103
  raise gr.Error("No frames in this part of the clip.")
104
- progress(0.15, desc=f"Tracking '{prompt or 'person'}' with SAM 3 ({len(frames)} frames)")
105
  point = state.get("point") if start == 0 else None
106
- subject, others, t_track = gpu_track(frames, prompt or "person", point)
107
  found = subject.reshape(len(subject), -1).any(1)
108
- if not found.any():
109
  raise gr.Error(f"SAM 3 found no '{prompt or 'person'}' to keep sharp in this clip.")
110
- progress(0.55, desc="Depth, spotlight edit and rendering")
111
- out, depth, t_render = gpu_spotlight(frames, subject, others, float(strength), float(gap))
112
  progress(0.9, desc="Encoding")
113
  tmp = Path(tempfile.mkdtemp())
114
  audio = engine.cut_audio(state["video"], seconds, tmp / "audio.m4a", start=start)
 
20
  GREEN = np.array([72, 164, 63], np.float32)
21
 
22
 
23
+ def _gpu_seconds(frames, *args): # ZeroGPU at 768 px: SAM 3 ~0.27 s per frame, depth + rendering ~0.1 s per
24
+ return int(min(120, 30 + 0.4 * len(frames))) # frame, plus ~10 s to build the Triton kernel once per container
25
 
26
 
27
+ @spaces.GPU(duration=_gpu_seconds)
28
+ def gpu_process(frames, prompt, point, strength, gap):
29
+ return engine.process(frames, prompt, point, strength, gap)
 
 
 
 
 
 
 
 
 
 
 
 
 
30
 
31
 
32
  def mark(image, point):
 
88
  frames, fps = engine.read_clip(state["video"], seconds, int(long_side), start=start)
89
  if len(frames) == 0:
90
  raise gr.Error("No frames in this part of the clip.")
91
+ progress(0.15, desc=f"Tracking '{prompt or 'person'}' with SAM 3 and rendering {len(frames)} frames")
92
  point = state.get("point") if start == 0 else None
93
+ subject, out, depth, t_track, t_render = gpu_process(frames, prompt or "person", point, float(strength), float(gap))
94
  found = subject.reshape(len(subject), -1).any(1)
95
+ if out is None:
96
  raise gr.Error(f"SAM 3 found no '{prompt or 'person'}' to keep sharp in this clip.")
 
 
97
  progress(0.9, desc="Encoding")
98
  tmp = Path(tempfile.mkdtemp())
99
  audio = engine.cut_audio(state["video"], seconds, tmp / "audio.m4a", start=start)
engine.py CHANGED
@@ -82,7 +82,7 @@ def read_clip(path, seconds, long_side, max_fps=30.0, start=0.0):
82
  cmd = [FFMPEG, "-v", "error", "-ss", f"{start:.3f}", "-t", f"{seconds:.3f}", "-i", str(path),
83
  "-vf", f"fps={fps2:.6f},scale={w2}:{h2}:flags=lanczos", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
84
  raw = subprocess.run(cmd, capture_output=True, check=True).stdout
85
- frames = np.frombuffer(raw, np.uint8).reshape(-1, h2, w2, 3)
86
  return frames, fps2
87
 
88
 
@@ -103,47 +103,86 @@ def track(frames, prompt="person", point=None):
103
  return subject.numpy(), others.numpy()
104
 
105
 
106
- def _render(scene, strength, focal_depth, depth):
 
107
  try:
108
- return refocuser.render(scene, strength, focal_depth, depth=depth)
109
- except Exception as e: # the Triton kernel failed to build here: use the reference attention
110
  if not any("forward" in vars(m) for m in refocuser.renderer.modules()):
111
  raise
112
  print(f"fused attention unavailable ({type(e).__name__}: {e}); using the reference attention")
113
  for m in refocuser.renderer.modules():
114
  vars(m).pop("forward", None)
115
- return refocuser.render(scene, strength, focal_depth, depth=depth)
116
 
117
 
118
  @torch.no_grad()
119
- def spotlight(frames, subject, others, strength=1.5, gap=0.6, grow=10, depth_smoothing=0.7, focus_smoothing=0.6):
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  """Spotlight video (n, h, w, 3) uint8 and the edited depth of the first frame (h, w; 1 = far).
121
 
122
  Depth is smoothed over frames with an exponential moving average (depth_smoothing), the focal depth is the median
123
  depth inside the subject mask (smoothed with focus_smoothing), and frames where the subject is missing are
124
- rendered with their own depth and the last focal depth."""
 
125
  out = np.empty_like(frames)
126
  prev, d_f, first_depth = None, None, None
127
- for i, frame in enumerate(frames):
128
- image = image_to_tensor(frame).cuda()
129
- depth = refocuser.depth_estimator(image)
130
- prev = depth if prev is None or depth_smoothing <= 0 else depth_smoothing * prev + (1 - depth_smoothing) * depth
131
- m = torch.from_numpy(subject[i]).cuda()
132
- present = int(m.sum()) > 50
133
- target = float(prev[0][m].median()) if present else (d_f if d_f is not None else float(prev.median()))
134
- d_f = target if d_f is None or focus_smoothing <= 0 else focus_smoothing * d_f + (1 - focus_smoothing) * target
135
- if present:
136
- o = torch.from_numpy(others[i]).cuda()
137
- edited, _ = depth_edits.spotlight(prev, m[None], d_f, gap, others=o[None], grow=grow)
138
- else:
139
- edited = prev
140
- y = _render(Scene(image, prev), strength, d_f, edited)
141
- out[i] = (y[0].clamp(0, 1).permute(1, 2, 0) * 255).round().byte().cpu().numpy()
142
- if first_depth is None:
143
- first_depth = edited[0].float().cpu().numpy()
 
 
 
 
144
  return out, first_depth
145
 
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  def write_video(frames, fps, path, audio=None):
148
  """H.264 (yuv420p, plays in browsers) with the audio track, if any."""
149
  from flashrefocus.video import VideoWriter
 
82
  cmd = [FFMPEG, "-v", "error", "-ss", f"{start:.3f}", "-t", f"{seconds:.3f}", "-i", str(path),
83
  "-vf", f"fps={fps2:.6f},scale={w2}:{h2}:flags=lanczos", "-f", "rawvideo", "-pix_fmt", "rgb24", "-"]
84
  raw = subprocess.run(cmd, capture_output=True, check=True).stdout
85
+ frames = np.frombuffer(bytearray(raw), np.uint8).reshape(-1, h2, w2, 3) # writable, for torch.from_numpy
86
  return frames, fps2
87
 
88
 
 
103
  return subject.numpy(), others.numpy()
104
 
105
 
106
+ def _fallback(fn):
107
+ """Run fn(); if the fused Triton kernel fails to build here, switch the renderer back to the reference attention."""
108
  try:
109
+ return fn()
110
+ except Exception as e:
111
  if not any("forward" in vars(m) for m in refocuser.renderer.modules()):
112
  raise
113
  print(f"fused attention unavailable ({type(e).__name__}: {e}); using the reference attention")
114
  for m in refocuser.renderer.modules():
115
  vars(m).pop("forward", None)
116
+ return fn()
117
 
118
 
119
  @torch.no_grad()
120
+ def depth_batch(images):
121
+ """Depth Anything V2 on a batch (b, 3, H, W) in [0, 1] -> D (b, H, W), each frame normalised on its own, as
122
+ DepthEstimator does for one image."""
123
+ import torch.nn.functional as F
124
+
125
+ from flashrefocus.rendering.depth import disparity_to_depth
126
+ de = refocuser.depth_estimator
127
+ h, w = images.shape[-2:]
128
+ x = F.interpolate(images, de._network_size(h, w), mode="bicubic", align_corners=False)
129
+ x = (x - de.mean.to(x)) / de.std.to(x)
130
+ with torch.autocast("cuda", dtype=torch.float16):
131
+ disparity = de.model(x)
132
+ disparity = F.interpolate(disparity[:, None].float(), (h, w), mode="bilinear", align_corners=True)[:, 0]
133
+ return torch.stack([disparity_to_depth(d) for d in disparity])
134
+
135
+
136
+ @torch.no_grad()
137
+ def spotlight(frames, subject, others, strength=1.5, gap=0.6, grow=10, depth_smoothing=0.7, focus_smoothing=0.6,
138
+ batch=8):
139
  """Spotlight video (n, h, w, 3) uint8 and the edited depth of the first frame (h, w; 1 = far).
140
 
141
  Depth is smoothed over frames with an exponential moving average (depth_smoothing), the focal depth is the median
142
  depth inside the subject mask (smoothed with focus_smoothing), and frames where the subject is missing are
143
+ rendered with their own depth and the last focal depth. Depth estimation and rendering run `batch` frames at a
144
+ time; the result is the same as frame by frame."""
145
  out = np.empty_like(frames)
146
  prev, d_f, first_depth = None, None, None
147
+ for s in range(0, len(frames), batch):
148
+ images = torch.from_numpy(frames[s:s + batch]).cuda().permute(0, 3, 1, 2).float().div(255)
149
+ depths = depth_batch(images)
150
+ masks = torch.from_numpy(subject[s:s + batch]).cuda()
151
+ other = torch.from_numpy(others[s:s + batch]).cuda()
152
+ scene_depths, edited, focal = [], [], []
153
+ for k in range(len(images)):
154
+ prev = depths[k:k + 1] if prev is None or depth_smoothing <= 0 else \
155
+ depth_smoothing * prev + (1 - depth_smoothing) * depths[k:k + 1]
156
+ m = masks[k]
157
+ present = int(m.sum()) > 50
158
+ target = float(prev[0][m].median()) if present else (d_f if d_f is not None else float(prev.median()))
159
+ d_f = target if d_f is None or focus_smoothing <= 0 else focus_smoothing * d_f + (1 - focus_smoothing) * target
160
+ e = depth_edits.spotlight(prev, m[None], d_f, gap, others=other[k][None], grow=grow)[0] if present else prev
161
+ scene_depths.append(prev)
162
+ edited.append(e)
163
+ focal.append(d_f)
164
+ if first_depth is None:
165
+ first_depth = e[0].float().cpu().numpy()
166
+ y = _fallback(lambda: refocuser.render_batch(images, torch.cat(edited), strength, focal))
167
+ out[s:s + len(images)] = (y.clamp(0, 1) * 255).round().byte().permute(0, 2, 3, 1).cpu().numpy()
168
  return out, first_depth
169
 
170
 
171
+ @torch.no_grad()
172
+ def process(frames, prompt="person", point=None, strength=1.5, gap=0.6):
173
+ """Tracking and rendering in one call (one GPU allocation on ZeroGPU). Returns the subject masks, the spotlight
174
+ video, the edited depth of the first frame and the two timings."""
175
+ import time
176
+ t0 = time.perf_counter()
177
+ subject, others = track(frames, prompt, point)
178
+ t1 = time.perf_counter()
179
+ if not subject.reshape(len(subject), -1).any():
180
+ return subject, None, None, t1 - t0, 0.0
181
+ out, depth = spotlight(frames, subject, others, strength=strength, gap=gap)
182
+ torch.cuda.synchronize()
183
+ return subject, out, depth, t1 - t0, time.perf_counter() - t1
184
+
185
+
186
  def write_video(frames, fps, path, audio=None):
187
  """H.264 (yuv420p, plays in browsers) with the audio track, if any."""
188
  from flashrefocus.video import VideoWriter