aburzio-nv commited on
Commit
f233ff6
·
verified ·
1 Parent(s): 0fd8007

Adapt GPU reservations to workload and remaining quota; keep visualization on CPU

Browse files
Files changed (2) hide show
  1. README.md +8 -4
  2. src/dvlt/scripts/gradio_demo.py +82 -4
README.md CHANGED
@@ -24,10 +24,14 @@ Displayed throughput FPS is input frame count divided by network forward seconds
24
  Visualization-only changes retain the last timing; cached examples do not
25
  run the network or display a newly measured time.
26
 
27
- Reconstruction declares an 80-second ZeroGPU function duration. The current
28
- Blackwell hardware applies a 1.5x duration factor, giving a 120-second quota
29
- reservation. Visualization updates declare 60 seconds (90 quota seconds).
30
- The visitor's remaining quota must cover the reservation before execution.
 
 
 
 
31
 
32
  The deployed Space uses **Public** visibility. The app and its source repository
33
  are publicly accessible. Visibility is a Space setting, not controlled by this README.
 
24
  Visualization-only changes retain the last timing; cached examples do not
25
  run the network or display a newly measured time.
26
 
27
+ Reconstruction estimates its GPU callback budget from image count, inference
28
+ steps and sky filtering, with a safety margin and a 12–80 second range. On the
29
+ current Blackwell factor of 1.5 this reserves about 18–120 quota seconds. If the
30
+ scheduler rejects the reservation and reports remaining quota, the app can retry
31
+ once with less safety margin when the estimated work still fits. It never retries
32
+ a runtime failure or changes the input count/inference quality. No visitor billing
33
+ permissions are requested. Visualization updates reuse CPU predictions and do not
34
+ reserve a GPU slot. The hidden model-loading callback retains its 80-second cap.
35
 
36
  The deployed Space uses **Public** visibility. The app and its source repository
37
  are publicly accessible. Visibility is a Space setting, not controlled by this README.
src/dvlt/scripts/gradio_demo.py CHANGED
@@ -41,12 +41,17 @@ Usage::
41
  """
42
 
43
  import gc
 
44
  import json
45
  import logging
 
46
  import os
 
47
  import tempfile
48
  import threading
49
  import time
 
 
50
  from pathlib import Path
51
  from typing import Optional
52
 
@@ -80,6 +85,68 @@ from dvlt.viz.scene_rerun import visualize_scene
80
 
81
  logger = get_logger(__name__)
82
  HOSTED_MAX_FRAMES = 300
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
83
 
84
 
85
  EXTRA_CLI_ARGS = [
@@ -520,6 +587,7 @@ def build_app(
520
  )
521
 
522
  def _run(max_pts, conf_thresh, frustum_scale_pct, inference_steps, state, sky=True, black=False, white=False):
 
523
  if os.getenv("SPACES_ZERO_GPU"):
524
  print("DVLT ZeroGPU: inference worker entered", flush=True)
525
  frames = state.get("frames") or []
@@ -565,6 +633,12 @@ def build_app(
565
  state["pts"], state["rgb"] = pts, rgb
566
  glb_path = _export_glb(pts, rgb, frustum_scale_pct, state)
567
  rrd_path = pointcloud_to_rrd(pts, rgb, predictions, batch, output_path=_output_path(".rrd"))
 
 
 
 
 
 
568
  return glb_path, rrd_path, gr.update(value=depth_gallery(predictions, batch), visible=True), _timing_notice(state), None, state
569
 
570
  def _run_if_frames_loaded(
@@ -627,10 +701,14 @@ def build_app(
627
  if os.getenv("SPACES_ZERO_GPU"):
628
  import spaces
629
 
630
- # Blackwell ZeroGPU applies a 1.5x quota factor: 80s reserves 120s.
631
- _run = spaces.GPU(duration=80)(_run)
632
- _on_model_change = spaces.GPU(duration=80)(_on_model_change)
633
- _update_viz = spaces.GPU(duration=60)(_update_viz)
 
 
 
 
634
 
635
  with gr.Blocks(
636
  title="Déjà View · 3D Reconstruction",
 
41
  """
42
 
43
  import gc
44
+ import inspect
45
  import json
46
  import logging
47
+ import math
48
  import os
49
+ import re
50
  import tempfile
51
  import threading
52
  import time
53
+ from contextvars import ContextVar
54
+ from functools import wraps
55
  from pathlib import Path
56
  from typing import Optional
57
 
 
85
 
86
  logger = get_logger(__name__)
87
  HOSTED_MAX_FRAMES = 300
88
+ GPU_TIME_MARGIN = 1.5
89
+ GPU_MAX_SECONDS = 80 # Current Blackwell quota factor is 1.5: reserve at most 120s.
90
+ GPU_DURATION_CAP = ContextVar("dvlt_gpu_duration_cap", default=GPU_MAX_SECONDS)
91
+
92
+
93
+ def estimate_gpu_seconds(num_frames: int, inference_steps: Optional[int], sky: bool = True) -> int:
94
+ """Conservative callback budget, including CPU filtering/export inside the slot.
95
+
96
+ Initial coefficients cover small live runs with headroom; larger attention
97
+ workloads get a quadratic allowance. This is an estimate, not a benchmark.
98
+ """
99
+ frames = min(HOSTED_MAX_FRAMES, max(1, num_frames))
100
+ steps = min(16, max(8, float(inference_steps or 16)))
101
+ network_seconds = (0.12 * frames + 0.0008 * frames**2) * steps / 16
102
+ sky_seconds = 0.35 * frames if sky else 0
103
+ return min(GPU_MAX_SECONDS, max(12, math.ceil(GPU_TIME_MARGIN * (6 + network_seconds + sky_seconds))))
104
+
105
+
106
+ def with_quota_retry(gpu_fn, duration_fn):
107
+ """Retry one scheduler rejection with less headroom when remaining time fits.
108
+
109
+ Only the SDK's pre-execution quota rejection is eligible. Runtime failures
110
+ are never retried. wraps preserves Gradio's signature and ZeroGPU marker.
111
+ """
112
+ signature = inspect.signature(gpu_fn)
113
+
114
+ @wraps(gpu_fn)
115
+ def run(*args, **kwargs):
116
+ state = signature.bind(*args, **kwargs).arguments["state"]
117
+ frames = state.get("frames") or []
118
+ if not frames:
119
+ raise gr.Error("Upload at least one image or video.")
120
+ if len(frames) > HOSTED_MAX_FRAMES:
121
+ raise gr.Error(f"Use at most {HOSTED_MAX_FRAMES} images or sampled video frames for live inference.")
122
+ seconds = duration_fn(*args, **kwargs)
123
+ print(f"DVLT GPU callback budget: {seconds}s for {len(frames)} frames", flush=True)
124
+ try:
125
+ return gpu_fn(*args, **kwargs)
126
+ except gr.Error as exc:
127
+ match = re.search(r"ZeroGPU quota \((\d+)s requested vs\.\s*(\d+)s left\)", str(exc))
128
+ if match is None:
129
+ raise
130
+ requested, remaining = map(int, match.groups())
131
+ if requested <= 0 or remaining >= requested:
132
+ raise
133
+ # Use the scheduler's actual quota/runtime ratio and leave one
134
+ # quota second for rounding. Do not query the owner's quota/token.
135
+ available = math.floor((min(120, remaining) - 1) * seconds / requested)
136
+ if not math.ceil(seconds / GPU_TIME_MARGIN) <= available < seconds:
137
+ raise gr.Error(
138
+ "Not enough GPU quota for this input. Try fewer images or 8 inference steps. "
139
+ + str(exc)
140
+ ) from exc
141
+ gr.Info("Retrying with a smaller GPU reservation that fits your remaining quota.")
142
+ print(f"DVLT GPU quota retry budget: {available}s", flush=True)
143
+ budget_token = GPU_DURATION_CAP.set(available)
144
+ try:
145
+ return gpu_fn(*args, **kwargs)
146
+ finally:
147
+ GPU_DURATION_CAP.reset(budget_token)
148
+
149
+ return run
150
 
151
 
152
  EXTRA_CLI_ARGS = [
 
587
  )
588
 
589
  def _run(max_pts, conf_thresh, frustum_scale_pct, inference_steps, state, sky=True, black=False, white=False):
590
+ callback_started = time.perf_counter()
591
  if os.getenv("SPACES_ZERO_GPU"):
592
  print("DVLT ZeroGPU: inference worker entered", flush=True)
593
  frames = state.get("frames") or []
 
633
  state["pts"], state["rgb"] = pts, rgb
634
  glb_path = _export_glb(pts, rgb, frustum_scale_pct, state)
635
  rrd_path = pointcloud_to_rrd(pts, rgb, predictions, batch, output_path=_output_path(".rrd"))
636
+ if os.getenv("SPACES_ZERO_GPU"):
637
+ print(
638
+ f"DVLT callback processing: {time.perf_counter() - callback_started:.3f} s "
639
+ f"for {len(frames)} frames at {inference_steps} steps",
640
+ flush=True,
641
+ )
642
  return glb_path, rrd_path, gr.update(value=depth_gallery(predictions, batch), visible=True), _timing_notice(state), None, state
643
 
644
  def _run_if_frames_loaded(
 
701
  if os.getenv("SPACES_ZERO_GPU"):
702
  import spaces
703
 
704
+ def _gpu_duration(max_pts, conf_thresh, frustum_scale_pct, inference_steps, state, sky=True, black=False, white=False):
705
+ estimated = estimate_gpu_seconds(len(state.get("frames") or []), inference_steps, sky)
706
+ return min(estimated, GPU_DURATION_CAP.get())
707
+
708
+ _run = with_quota_retry(spaces.GPU(duration=_gpu_duration)(_run), _gpu_duration)
709
+ _on_model_change = spaces.GPU(duration=GPU_MAX_SECONDS)(_on_model_change)
710
+ # ZeroGPU inference returns predictions/batch on CPU; visualization
711
+ # updates require no GPU slot or visitor GPU quota.
712
 
713
  with gr.Blocks(
714
  title="Déjà View · 3D Reconstruction",