Spaces:
Running on Zero

vtwo commited on
Commit
b4bac7c
·
verified ·
1 Parent(s): 265c2dc

Add SpaceTimeVLM demo (2B, 4B, 9B)

Browse files
Files changed (4) hide show
  1. README.md +29 -6
  2. app.py +337 -0
  3. packages.txt +1 -0
  4. requirements.txt +5 -0
README.md CHANGED
@@ -1,13 +1,36 @@
1
  ---
2
  title: SpaceTimeVLM
3
- emoji: 📉
4
- colorFrom: indigo
5
- colorTo: blue
6
  sdk: gradio
7
  sdk_version: 6.32.0
8
- python_version: '3.12'
9
  app_file: app.py
10
- pinned: false
 
 
 
 
 
 
 
11
  ---
12
 
13
- Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
  ---
2
  title: SpaceTimeVLM
3
+ emoji: 🧭
4
+ colorFrom: blue
5
+ colorTo: indigo
6
  sdk: gradio
7
  sdk_version: 6.32.0
 
8
  app_file: app.py
9
+ short_description: Spatial questions about a video, answered with 3D cues
10
+ python_version: "3.12"
11
+ startup_duration_timeout: 1h
12
+ license: cc-by-nc-4.0
13
+ models:
14
+ - DarioVajda/SpaceTimeVLM-2B
15
+ - DarioVajda/SpaceTimeVLM-4B
16
+ - DarioVajda/SpaceTimeVLM-9B
17
  ---
18
 
19
+ # SpaceTimeVLM demo
20
+
21
+ Upload a video of a scene, ask a spatial question and get the answer of
22
+ [SpaceTimeVLM-2B](https://huggingface.co/DarioVajda/SpaceTimeVLM-2B),
23
+ [4B](https://huggingface.co/DarioVajda/SpaceTimeVLM-4B) or
24
+ [9B](https://huggingface.co/DarioVajda/SpaceTimeVLM-9B), or of all three on the same frames.
25
+
26
+ - The video is decoded with ffmpeg (which applies the rotation flag of phone videos) and 8, 16 or 32 frames are
27
+ sampled uniformly.
28
+ - The video is prepared as soon as it is added, while the question is being written: the chosen model runs VGGT,
29
+ its vision encoder and its language model over the frames and keeps that cache, so the answer only runs the
30
+ question's tokens. If the cache is not there (a new GPU worker, an API call), the full path runs instead.
31
+ - "Short answer" wraps the question in the VSI-Bench prompt used for the benchmark scores on the model cards.
32
+ - The Space variable `SPACETIME_SIZES` (for example `2B,4B`) loads fewer models.
33
+
34
+ The models are under CC BY-NC 4.0 (non-commercial use). The example video is an excerpt of
35
+ [UE4Arch.com - Viennese apartment](https://commons.wikimedia.org/wiki/File:UE4Arch.com_-_Viennese_apartment.webm)
36
+ by UE4Arch.com (CC BY-SA 4.0).
app.py ADDED
@@ -0,0 +1,337 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """SpaceTimeVLM demo: ask a spatial question about a video and get the answer of the 2B, 4B or 9B model.
2
+
3
+ The three models are loaded once when the Space starts. The video is prepared while the question is being typed:
4
+
5
+ video added the frames are decoded and sampled (CPU), then the chosen model runs VGGT, its vision encoder and
6
+ its language model over [system][frames], and the GPU worker keeps that cache (prepare)
7
+ question sent only the question's tokens and the answer are run, on a copy of the cache (answer)
8
+
9
+ The prompt is [system][frames][question], so everything up to the last frame is the same for every question. This
10
+ is the prefix cache of src/mvp/serve/engine.py. The cache lives in the memory of the ZeroGPU worker; if a question
11
+ reaches a worker that does not have it (a new worker, another model, an API call), the model's own full path runs.
12
+ """
13
+ import os
14
+
15
+ os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
16
+
17
+ import spaces # before torch: on ZeroGPU it patches torch.cuda
18
+
19
+ import copy
20
+ import shutil
21
+ import subprocess
22
+ import tempfile
23
+ import time
24
+ import uuid
25
+ from collections import OrderedDict
26
+ from pathlib import Path
27
+
28
+ import gradio as gr
29
+ import numpy as np
30
+ import torch
31
+ from huggingface_hub import hf_hub_download
32
+ from PIL import Image
33
+ from transformers import AutoModel
34
+ from transformers.modeling_outputs import BaseModelOutputWithPooling
35
+
36
+ REPO = "DarioVajda/SpaceTimeVLM-{}"
37
+ # SPACETIME_SIZES (a Space variable, for example "2B,4B") loads fewer models if the hardware cannot hold all three.
38
+ SIZES = tuple(s.strip() for s in os.environ.get("SPACETIME_SIZES", "2B,4B,9B").split(",") if s.strip())
39
+ ALL = "All of them"
40
+ FRAME_CHOICES = [8, 16, 32] # the frame counts the models were trained with
41
+ CANDIDATE_FPS = 8 # frames ffmpeg writes per second of video; the model's frames are sampled from them
42
+ MAX_LONG_SIDE = 960 # larger videos are scaled down to this
43
+ MAX_VIDEO_SECONDS = 600 # only the first ten minutes of a video are read
44
+ MAX_NEW_TOKENS = 128
45
+ MAX_PREFIXES = 6 # prepared (video, model) pairs a GPU worker keeps
46
+ FRAMES_ROOT = Path(tempfile.gettempdir()) / "spacetime_frames" # one folder of sampled frames per prepared video
47
+ FRAMES_KEPT_SECONDS = 3600
48
+ # The VSI-Bench layout for open questions (lmms-eval), which the benchmark scores on the model cards use.
49
+ SHORT_ANSWER_PROMPT = "These are frames of a video.\n{}\nPlease answer the question using a single word or phrase."
50
+
51
+
52
+ def load(size):
53
+ """One model on the GPU. Qwen3.5 is in bfloat16; the model keeps its geometry branch (VGGT) in float32."""
54
+ t0 = time.time()
55
+ model = AutoModel.from_pretrained(REPO.format(size), trust_remote_code=True, dtype=torch.bfloat16)
56
+ model = model.eval().requires_grad_(False).to("cuda")
57
+ model.processor # built here, so that the GPU workers do not load it again on every cold start
58
+ print(f"loaded SpaceTimeVLM-{size} in {time.time() - t0:.0f}s", flush=True)
59
+ return model
60
+
61
+
62
+ MODELS = {size: load(size) for size in SIZES}
63
+ PREFIXES = OrderedDict() # (clip id, size) -> prefix cache. Filled in the GPU worker only; empty in the web process.
64
+
65
+
66
+ def sizes_of(model_choice):
67
+ return SIZES if model_choice == ALL else (model_choice,)
68
+
69
+
70
+ # ---- frames (CPU) ----
71
+ def example_video():
72
+ """The example of the model cards (a 29 s walkthrough of a dining room and kitchen), copied next to the app."""
73
+ target = Path(__file__).parent / "examples" / "room.mp4"
74
+ if not target.exists():
75
+ target.parent.mkdir(exist_ok=True)
76
+ shutil.copy(hf_hub_download(REPO.format(SIZES[0]), "examples/room.mp4"), target)
77
+ return str(target)
78
+
79
+
80
+ def save_frames(video, num_frames, out_dir):
81
+ """Writes num_frames uniformly spaced frames of the video to out_dir as JPEGs (all frames if it has fewer).
82
+
83
+ ffmpeg applies the rotation flag of phone videos and scales the long side down to MAX_LONG_SIDE.
84
+ """
85
+ long_side = f"trunc(min({MAX_LONG_SIDE},max(iw,ih))/2)*2"
86
+ scale = f"scale='if(gt(iw,ih),{long_side},-2)':'if(gt(iw,ih),-2,{long_side})'"
87
+ with tempfile.TemporaryDirectory() as d:
88
+ cmd = ["ffmpeg", "-v", "error", "-y", "-i", str(video), "-t", str(MAX_VIDEO_SECONDS),
89
+ "-vf", f"fps={CANDIDATE_FPS},{scale}", "-q:v", "2", str(Path(d) / "%05d.jpg")]
90
+ done = subprocess.run(cmd, capture_output=True, text=True)
91
+ paths = sorted(Path(d).glob("*.jpg"))
92
+ if done.returncode != 0 or not paths:
93
+ raise gr.Error(f"Could not read the video. {done.stderr.strip()[:300]}")
94
+ n = len(paths)
95
+ indices = np.arange(n) if n <= num_frames else np.linspace(0, n - 1, num_frames).astype(int)
96
+ Path(out_dir).mkdir(parents=True, exist_ok=True)
97
+ for k, i in enumerate(indices):
98
+ shutil.move(paths[i], Path(out_dir) / f"{k:03d}.jpg")
99
+
100
+
101
+ def load_frames(frames_dir):
102
+ return [Image.open(p).convert("RGB") for p in sorted(Path(frames_dir).glob("*.jpg"))]
103
+
104
+
105
+ def thumbnails(frames, long_side=320):
106
+ """Small copies of the frames for the gallery."""
107
+ small = [frame.copy() for frame in frames]
108
+ for frame in small:
109
+ frame.thumbnail((long_side, long_side))
110
+ return small
111
+
112
+
113
+ def clamp_frames(num_frames):
114
+ return min(max(int(num_frames), 1), 32)
115
+
116
+
117
+ def remove_old_frames():
118
+ if FRAMES_ROOT.is_dir():
119
+ for d in FRAMES_ROOT.iterdir():
120
+ if time.time() - d.stat().st_mtime > FRAMES_KEPT_SECONDS:
121
+ shutil.rmtree(d, ignore_errors=True)
122
+
123
+
124
+ def decode(video, num_frames):
125
+ """Runs when the video or the frame count changes: sample the frames once, on the CPU, and show them."""
126
+ if not video:
127
+ return None, None, ""
128
+ remove_old_frames()
129
+ clip = {"id": uuid.uuid4().hex, "video": video, "num_frames": clamp_frames(num_frames)}
130
+ clip["dir"] = str(FRAMES_ROOT / clip["id"])
131
+ save_frames(video, clip["num_frames"], clip["dir"])
132
+ return clip, thumbnails(load_frames(clip["dir"])), "Preparing the video while you write your question…"
133
+
134
+
135
+ def clip_matches(clip, video, num_frames):
136
+ return bool(clip) and clip.get("video") == video and clip.get("num_frames") == num_frames and Path(clip["dir"]).is_dir()
137
+
138
+
139
+ # ---- prefix cache (GPU worker) ----
140
+ @torch.no_grad()
141
+ def build_prefix(model, frames):
142
+ """Runs the model over [system][frames] once and returns what a question needs to continue from there: the
143
+ language model's cache (keys / values of the softmax-attention layers, state of the Gated DeltaNet layers)."""
144
+ vis = {k: v.to("cuda") for k, v in model.visual_inputs(frames).items()}
145
+ grid = vis["image_grid_thw"]
146
+ ids = model.text_inputs(["x"], grid.cpu())["input_ids"][0]
147
+ last_image_token = int((ids == model.config.image_token_id).nonzero()[-1])
148
+ n_prefix = last_image_token + 2 # through the token that closes the last frame
149
+ prefix_ids = ids[:n_prefix][None].to("cuda")
150
+ try:
151
+ model.set_geometry(vis["vggt_images"], grid)
152
+ feats = model.model.get_image_features(vis["pixel_values"], grid, return_dict=True)
153
+ with torch.autocast("cuda", dtype=torch.bfloat16):
154
+ out = model.model(
155
+ input_ids=prefix_ids, attention_mask=torch.ones_like(prefix_ids),
156
+ mm_token_type_ids=(prefix_ids == model.config.image_token_id).int(), image_grid_thw=grid,
157
+ mm_encoder_outputs={"image": BaseModelOutputWithPooling(pooler_output=tuple(feats.pooler_output))},
158
+ use_cache=True)
159
+ return {"grid": grid.cpu(), "prefix_ids": prefix_ids, "n_prefix": n_prefix, "cache": out.past_key_values,
160
+ "rope_deltas": model.model.rope_deltas.clone()}
161
+ finally:
162
+ model.clear_geometry()
163
+
164
+
165
+ @torch.no_grad()
166
+ def answer_from_prefix(model, prefix, prompt):
167
+ """The answer to one question from a prepared prefix, or None if this prompt does not start with that prefix
168
+ (for example a question with its own <image> placeholders). The prefix's cache is not changed."""
169
+ tok = model.processor.tokenizer
170
+ ids = model.text_inputs([prompt], prefix["grid"])["input_ids"].to("cuda")
171
+ n_prefix = prefix["n_prefix"]
172
+ if ids.shape[1] <= n_prefix or not torch.equal(ids[0, :n_prefix], prefix["prefix_ids"][0]):
173
+ return None
174
+ stop = [tok.convert_tokens_to_ids(t) for t in ("<|im_end|>", "<|endoftext|>")]
175
+ model.clear_geometry() # nothing to add: the question has no visual tokens
176
+ model.model.rope_deltas = prefix["rope_deltas"] # positions after the frames continue from this video's offset
177
+ with torch.autocast("cuda", dtype=torch.bfloat16):
178
+ out = model.generate(input_ids=ids, attention_mask=torch.ones_like(ids),
179
+ past_key_values=copy.deepcopy(prefix["cache"]), max_new_tokens=MAX_NEW_TOKENS,
180
+ do_sample=False, temperature=None, top_p=None, top_k=None, eos_token_id=stop,
181
+ pad_token_id=tok.pad_token_id)
182
+ return tok.decode(out[0, ids.shape[1]:], skip_special_tokens=True).strip()
183
+
184
+
185
+ def prepare_seconds(clip=None, model_choice=None, *args, **kwargs):
186
+ """GPU time to reserve for preparing a video. Placeholder values: set them from measured times on the Space."""
187
+ return 30 + 20 * (len(SIZES) - 1 if model_choice == ALL else 0)
188
+
189
+
190
+ @spaces.GPU(duration=prepare_seconds, size="xlarge")
191
+ def prepare(clip, model_choice):
192
+ """Runs after a video is added (and when the model changes): prepare the video for the chosen model, so that the
193
+ question only has to run its own tokens. A failure here is not an error: the answer then runs the full path."""
194
+ if not clip or not Path(clip["dir"]).is_dir() or (model_choice != ALL and model_choice not in MODELS):
195
+ return ""
196
+ try:
197
+ start = time.perf_counter()
198
+ frames = load_frames(clip["dir"])
199
+ for size in sizes_of(model_choice):
200
+ key = (clip["id"], size)
201
+ if key not in PREFIXES:
202
+ PREFIXES[key] = build_prefix(MODELS[size], frames)
203
+ PREFIXES.move_to_end(key)
204
+ while len(PREFIXES) > MAX_PREFIXES:
205
+ PREFIXES.popitem(last=False)
206
+ torch.cuda.synchronize()
207
+ seconds = time.perf_counter() - start
208
+ print("prepared", clip["id"][:8], model_choice, f"{len(frames)} frames", f"{seconds:.1f}s", flush=True)
209
+ return f"Video ready ({len(frames)} frames, prepared in {seconds:.1f} s)."
210
+ except Exception as e:
211
+ print(f"prepare failed: {type(e).__name__}: {e}", flush=True)
212
+ return ""
213
+
214
+
215
+ # ---- answer ----
216
+ def answers_table(rows, n_frames):
217
+ """Markdown: the answer alone for one model, a table for several. rows: (size, answer, seconds, from prefix)."""
218
+ how = lambda prepared: "from the prepared video" if prepared else "full run"
219
+ if len(rows) == 1:
220
+ size, text, seconds, prepared = rows[0]
221
+ return f"## {text}\n\nSpaceTimeVLM-{size}, {n_frames} frames, {seconds:.1f} s ({how(prepared)})"
222
+ lines = ["| Model | Answer | Seconds | |", "|---|---|---:|---|"]
223
+ for size, text, seconds, prepared in rows:
224
+ cell = text.replace("|", "\\|").replace("\n", " ")
225
+ lines.append(f"| SpaceTimeVLM-{size} | **{cell}** | {seconds:.1f} | {how(prepared)} |")
226
+ return "\n".join(lines) + f"\n\n{n_frames} frames, the same for every model."
227
+
228
+
229
+ def answer_seconds(video=None, question=None, model_choice=None, *args, **kwargs):
230
+ """GPU time to reserve for one answer (the full path, in case the video is not prepared). Placeholder values."""
231
+ return 45 + 30 * (len(SIZES) - 1 if model_choice == ALL else 0)
232
+
233
+
234
+ @spaces.GPU(duration=answer_seconds, size="xlarge")
235
+ def answer(video: str, question: str, model_choice: str = SIZES[0], num_frames: int = 32, short_answer: bool = False,
236
+ clip: dict | None = None):
237
+ """Answer a spatial question about a video of a scene with SpaceTimeVLM.
238
+
239
+ Args:
240
+ video: Path or URL of a video file, for example a walkthrough of a room.
241
+ question: The question, for example "How many chairs are in this room?".
242
+ model_choice: The model size ("2B", "4B" or "9B"), or "All of them" to compare the three answers.
243
+ num_frames: Number of frames sampled uniformly from the video (8, 16 or 32).
244
+ short_answer: Use the VSI-Bench prompt, which asks for a single word or phrase.
245
+
246
+ Returns:
247
+ The answer (a table of answers for "All of them") and the frames the model saw.
248
+ """
249
+ if not video:
250
+ raise gr.Error("Add a video first.")
251
+ if not question or not question.strip():
252
+ raise gr.Error("Write a question first.")
253
+ if model_choice != ALL and model_choice not in MODELS:
254
+ raise gr.Error(f"Unknown model: {model_choice}")
255
+ num_frames = clamp_frames(num_frames)
256
+ if clip_matches(clip, video, num_frames): # the frames sampled when the video was added
257
+ frames, clip_id = load_frames(clip["dir"]), clip["id"]
258
+ else: # an API call, or the video changed since
259
+ with tempfile.TemporaryDirectory() as d:
260
+ save_frames(video, num_frames, d)
261
+ frames, clip_id = load_frames(d), None
262
+ question = question.strip()
263
+ prompt = SHORT_ANSWER_PROMPT.format(question) if short_answer else question
264
+ rows = []
265
+ for size in sizes_of(model_choice):
266
+ model, prefix = MODELS[size], PREFIXES.get((clip_id, size))
267
+ start = time.perf_counter()
268
+ text = None
269
+ if prefix is not None:
270
+ try:
271
+ text = answer_from_prefix(model, prefix, prompt)
272
+ except Exception as e:
273
+ print(f"answer from prefix failed, running the full path: {type(e).__name__}: {e}", flush=True)
274
+ prepared = text is not None
275
+ if text is None:
276
+ (text,) = model.answer(model.prepare(frames, [prompt]), max_new_tokens=MAX_NEW_TOKENS)
277
+ torch.cuda.synchronize()
278
+ rows.append((size, text, time.perf_counter() - start, prepared))
279
+ print("answered", [(size, round(seconds, 1), prepared) for size, _, seconds, prepared in rows],
280
+ f"{len(frames)} frames", flush=True)
281
+ return answers_table(rows, len(frames)), thumbnails(frames)
282
+
283
+
284
+ INTRO = """# SpaceTimeVLM
285
+
286
+ Ask a spatial question about a video of a scene: how many objects there are, how far apart two objects are, how
287
+ large a room is. SpaceTimeVLM is Qwen3.5 with the frozen geometry encoder of VGGT-1B, read through a 3D-aware
288
+ cross-attention, so every visual token has a position in the scene.
289
+ Models: [2B](https://huggingface.co/DarioVajda/SpaceTimeVLM-2B),
290
+ [4B](https://huggingface.co/DarioVajda/SpaceTimeVLM-4B),
291
+ [9B](https://huggingface.co/DarioVajda/SpaceTimeVLM-9B).
292
+
293
+ The video is prepared as soon as you add it, while you write your question, so the answer only has to read the
294
+ question.
295
+ """
296
+
297
+ NOTES = """The models are released under CC BY-NC 4.0 (non-commercial use), because of the VGGT-1B weights.
298
+ The example video is an excerpt of
299
+ [UE4Arch.com - Viennese apartment](https://commons.wikimedia.org/wiki/File:UE4Arch.com_-_Viennese_apartment.webm)
300
+ by UE4Arch.com (CC BY-SA 4.0)."""
301
+
302
+ with gr.Blocks(title="SpaceTimeVLM") as demo:
303
+ gr.Markdown(INTRO)
304
+ clip = gr.State(None)
305
+ with gr.Row():
306
+ with gr.Column():
307
+ video = gr.Video(label="Video", sources=["upload"])
308
+ status = gr.Markdown()
309
+ question = gr.Textbox(label="Question", placeholder="How many chairs are in this room?", lines=2)
310
+ model_choice = gr.Radio(list(SIZES) + ([ALL] if len(SIZES) > 1 else []), value=SIZES[0], label="Model")
311
+ num_frames = gr.Radio(FRAME_CHOICES, value=32, label="Frames")
312
+ short_answer = gr.Checkbox(label="Short answer (VSI-Bench prompt)", value=False)
313
+ ask = gr.Button("Ask", variant="primary")
314
+ with gr.Column():
315
+ result = gr.Markdown(label="Answer")
316
+ seen = gr.Gallery(label="Frames the model saw", columns=4, height="auto")
317
+ gr.Examples(
318
+ examples=[[example_video(), "How many chairs are in this room?"],
319
+ [example_video(), "What is the size of this room in square meters?"]],
320
+ inputs=[video, question], cache_examples=False)
321
+ gr.Markdown(NOTES)
322
+
323
+ # The GPU steps share one queue, so a question sent while its video is still being prepared waits for it.
324
+ gpu = dict(concurrency_id="gpu", concurrency_limit=1)
325
+ in_background = dict(fn=prepare, inputs=[clip, model_choice], outputs=status, show_progress="hidden",
326
+ api_visibility="private", **gpu)
327
+ sample = dict(fn=decode, inputs=[video, num_frames], outputs=[clip, seen, status], api_visibility="private")
328
+ video.change(**sample).then(**in_background)
329
+ num_frames.change(**sample).then(**in_background)
330
+ model_choice.change(**in_background)
331
+
332
+ inputs = [video, question, model_choice, num_frames, short_answer, clip]
333
+ ask.click(answer, inputs, [result, seen], api_name="answer", **gpu)
334
+ question.submit(answer, inputs, [result, seen], api_visibility="private", **gpu)
335
+
336
+ if __name__ == "__main__":
337
+ demo.launch(mcp_server=True)
packages.txt ADDED
@@ -0,0 +1 @@
 
 
1
+ ffmpeg
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ transformers==5.20.1
2
+ accelerate
3
+ torchvision
4
+ pillow
5
+ numpy