SpaceTimeVLM / app.py
vtwo's picture
Placeholder text in the empty frames gallery
e63fb1d verified
Raw History Blame Contribute Delete
23.7 kB
"""SpaceTimeVLM demo: ask a spatial question about a video and get the answer of the 2B, 4B or 9B model.
The three models are loaded once when the Space starts. When a video is added, its frames are decoded and sampled
on the CPU straight away, so that work is done before the question arrives.
Optional (Space variable SPACETIME_PREPARE=1): the video is also prepared on the GPU while the question is typed.
video added the chosen model runs VGGT, its vision encoder and its language model over [system][frames], and
the GPU worker keeps that cache (prepare)
question sent only the question's tokens and the answer are run, on a copy of the cache (answer)
This is the prefix cache of src/mvp/serve/engine.py. The cache lives in the memory of the ZeroGPU worker; if a
question reaches a worker that does not have it, the model's own full path runs and the answer says why.
"""
import os
os.environ.setdefault("PYTORCH_CUDA_ALLOC_CONF", "expandable_segments:True")
import spaces # before torch: on ZeroGPU it patches torch.cuda
import copy
import shutil
import subprocess
import tempfile
import time
import uuid
from collections import OrderedDict
from pathlib import Path
import gradio as gr
import numpy as np
import torch
from huggingface_hub import hf_hub_download
from PIL import Image
from transformers import AutoModel
from transformers.modeling_outputs import BaseModelOutputWithPooling
REPO = "DarioVajda/SpaceTimeVLM-{}"
# SPACETIME_SIZES (a Space variable, for example "2B,4B") loads fewer models if the hardware cannot hold all three.
SIZES = tuple(s.strip() for s in os.environ.get("SPACETIME_SIZES", "2B,4B,9B").split(",") if s.strip())
ALL = "All of them"
FRAME_CHOICES = [8, 16, 32] # the frame counts the models were trained with
CANDIDATE_FPS = 8 # frames ffmpeg writes per second of video; the model's frames are sampled from them
MAX_LONG_SIDE = 960 # larger videos are scaled down to this
MAX_VIDEO_SECONDS = 600 # only the first ten minutes of a video are read
MAX_NEW_TOKENS = 128
MAX_PREFIXES = 6 # prepared (video, model) pairs a GPU worker keeps
# Preparing the video on the GPU ahead of the question is off unless the Space variable SPACETIME_PREPARE is 1.
# On the first test (2026-11-29) the answer still took the full path after a successful prepare, so it only cost
# GPU quota. The frames are always sampled ahead, on the CPU.
PREPARE_AHEAD = os.environ.get("SPACETIME_PREPARE", "0") == "1"
FRAMES_ROOT = Path(tempfile.gettempdir()) / "spacetime_frames" # one folder of sampled frames per prepared video
FRAMES_KEPT_SECONDS = 3600
# The VSI-Bench layout for open questions (lmms-eval), which the benchmark scores on the model cards use.
SHORT_ANSWER_PROMPT = "These are frames of a video.\n{}\nPlease answer the question using a single word or phrase."
def load(size):
"""One model on the GPU. Qwen3.5 is in bfloat16; the model keeps its geometry branch (VGGT) in float32."""
t0 = time.time()
model = AutoModel.from_pretrained(REPO.format(size), trust_remote_code=True, dtype=torch.bfloat16)
model = model.eval().requires_grad_(False).to("cuda")
model.processor # built here, so that the GPU workers do not load it again on every cold start
print(f"loaded SpaceTimeVLM-{size} in {time.time() - t0:.0f}s", flush=True)
return model
MODELS = {size: load(size) for size in SIZES}
PREFIXES = OrderedDict() # (clip id, size) -> prefix cache. Filled in the GPU worker only; empty in the web process.
def sizes_of(model_choice):
return SIZES if model_choice == ALL else (model_choice,)
# ---- frames (CPU) ----
def example_video():
"""The example of the model cards (a 29 s walkthrough of a dining room and kitchen), copied next to the app."""
target = Path(__file__).parent / "examples" / "room.mp4"
if not target.exists():
target.parent.mkdir(exist_ok=True)
shutil.copy(hf_hub_download(REPO.format(SIZES[0]), "examples/room.mp4"), target)
return str(target)
def save_frames(video, num_frames, out_dir):
"""Writes num_frames uniformly spaced frames of the video to out_dir as JPEGs (all frames if it has fewer).
ffmpeg applies the rotation flag of phone videos and scales the long side down to MAX_LONG_SIDE.
"""
long_side = f"trunc(min({MAX_LONG_SIDE},max(iw,ih))/2)*2"
scale = f"scale='if(gt(iw,ih),{long_side},-2)':'if(gt(iw,ih),-2,{long_side})'"
with tempfile.TemporaryDirectory() as d:
cmd = ["ffmpeg", "-v", "error", "-y", "-i", str(video), "-t", str(MAX_VIDEO_SECONDS),
"-vf", f"fps={CANDIDATE_FPS},{scale}", "-q:v", "2", str(Path(d) / "%05d.jpg")]
done = subprocess.run(cmd, capture_output=True, text=True)
paths = sorted(Path(d).glob("*.jpg"))
if done.returncode != 0 or not paths:
raise gr.Error(f"Could not read the video. {done.stderr.strip()[:300]}")
n = len(paths)
indices = np.arange(n) if n <= num_frames else np.linspace(0, n - 1, num_frames).astype(int)
Path(out_dir).mkdir(parents=True, exist_ok=True)
for k, i in enumerate(indices):
shutil.move(paths[i], Path(out_dir) / f"{k:03d}.jpg")
def load_frames(frames_dir):
return [Image.open(p).convert("RGB") for p in sorted(Path(frames_dir).glob("*.jpg"))]
def thumbnails(frames, long_side=320):
"""Small copies of the frames for the gallery."""
small = [frame.copy() for frame in frames]
for frame in small:
frame.thumbnail((long_side, long_side))
return small
def clamp_frames(num_frames):
return min(max(int(num_frames), 1), 32)
def remove_old_frames():
if FRAMES_ROOT.is_dir():
for d in FRAMES_ROOT.iterdir():
if time.time() - d.stat().st_mtime > FRAMES_KEPT_SECONDS:
shutil.rmtree(d, ignore_errors=True)
def decode(video, num_frames):
"""Runs when the video or the frame count changes: sample the frames once, on the CPU, and show them."""
if not video:
return None, None, ""
remove_old_frames()
clip = {"id": uuid.uuid4().hex, "video": video, "num_frames": clamp_frames(num_frames)}
clip["dir"] = str(FRAMES_ROOT / clip["id"])
save_frames(video, clip["num_frames"], clip["dir"])
status = "Preparing the video while you write your question…" if PREPARE_AHEAD else "Video ready."
return clip, thumbnails(load_frames(clip["dir"])), status
def clip_matches(clip, video, num_frames):
return bool(clip) and clip.get("video") == video and clip.get("num_frames") == num_frames and Path(clip["dir"]).is_dir()
# ---- prefix cache (GPU worker) ----
@torch.no_grad()
def build_prefix(model, frames):
"""Runs the model over [system][frames] once and returns what a question needs to continue from there: the
language model's cache (keys / values of the softmax-attention layers, state of the Gated DeltaNet layers)."""
vis = {k: v.to("cuda") for k, v in model.visual_inputs(frames).items()}
grid = vis["image_grid_thw"]
ids = model.text_inputs(["x"], grid.cpu())["input_ids"][0]
last_image_token = int((ids == model.config.image_token_id).nonzero()[-1])
n_prefix = last_image_token + 2 # through the token that closes the last frame
prefix_ids = ids[:n_prefix][None].to("cuda")
try:
model.set_geometry(vis["vggt_images"], grid)
feats = model.model.get_image_features(vis["pixel_values"], grid, return_dict=True)
with torch.autocast("cuda", dtype=torch.bfloat16):
out = model.model(
input_ids=prefix_ids, attention_mask=torch.ones_like(prefix_ids),
mm_token_type_ids=(prefix_ids == model.config.image_token_id).int(), image_grid_thw=grid,
mm_encoder_outputs={"image": BaseModelOutputWithPooling(pooler_output=tuple(feats.pooler_output))},
use_cache=True)
return {"grid": grid.cpu(), "prefix_ids": prefix_ids, "n_prefix": n_prefix, "cache": out.past_key_values,
"rope_deltas": model.model.rope_deltas.clone()}
finally:
model.clear_geometry()
@torch.no_grad()
def answer_from_prefix(model, prefix, prompt):
"""The answer to one question from a prepared prefix, or None if this prompt does not start with that prefix
(for example a question with its own <image> placeholders). The prefix's cache is not changed."""
tok = model.processor.tokenizer
ids = model.text_inputs([prompt], prefix["grid"])["input_ids"].to("cuda")
n_prefix = prefix["n_prefix"]
if ids.shape[1] <= n_prefix or not torch.equal(ids[0, :n_prefix], prefix["prefix_ids"][0]):
return None
stop = [tok.convert_tokens_to_ids(t) for t in ("<|im_end|>", "<|endoftext|>")]
model.clear_geometry() # nothing to add: the question has no visual tokens
model.model.rope_deltas = prefix["rope_deltas"] # positions after the frames continue from this video's offset
with torch.autocast("cuda", dtype=torch.bfloat16):
out = model.generate(input_ids=ids, attention_mask=torch.ones_like(ids),
past_key_values=copy.deepcopy(prefix["cache"]), max_new_tokens=MAX_NEW_TOKENS,
do_sample=False, temperature=None, top_p=None, top_k=None, eos_token_id=stop,
pad_token_id=tok.pad_token_id)
return tok.decode(out[0, ids.shape[1]:], skip_special_tokens=True).strip()
def prepare_seconds(clip=None, model_choice=None, *args, **kwargs):
"""GPU time to reserve for preparing a video: 10 s per model (measured: 5.8 s for 2B, 6.8 s for 4B, 32 frames)."""
return 10 * (len(SIZES) if model_choice == ALL else 1)
@spaces.GPU(duration=prepare_seconds, size="xlarge")
def prepare(clip, model_choice):
"""Runs after a video is added (and when the model changes): prepare the video for the chosen model, so that the
question only has to run its own tokens. A failure here is not an error: the answer then runs the full path."""
if not clip or not Path(clip["dir"]).is_dir() or (model_choice != ALL and model_choice not in MODELS):
return gr.update()
try:
start = time.perf_counter()
frames = load_frames(clip["dir"])
for size in sizes_of(model_choice):
key = (clip["id"], size)
if key not in PREFIXES:
PREFIXES[key] = build_prefix(MODELS[size], frames)
PREFIXES.move_to_end(key)
while len(PREFIXES) > MAX_PREFIXES:
PREFIXES.popitem(last=False)
torch.cuda.synchronize()
seconds = time.perf_counter() - start
print("prepared", clip["id"][:8], model_choice, f"{len(frames)} frames", f"{seconds:.1f}s", flush=True)
return f"Video ready ({len(frames)} frames, prepared in {seconds:.1f} s)."
except Exception as e:
print(f"prepare failed: {type(e).__name__}: {e}", flush=True)
return f"Video ready (not prepared ahead: {type(e).__name__})."
# ---- answer ----
def answers_table(rows, n_frames):
"""Markdown: the answer alone for one model, a table for several. rows: (size, answer, seconds, how it ran)."""
if len(rows) == 1:
size, text, seconds, how = rows[0]
return f"## {text}\n\nSpaceTimeVLM-{size}, {n_frames} frames, {seconds:.1f} s ({how})"
lines = ["| Model | Answer | Seconds | |", "|---|---|---:|---|"]
for size, text, seconds, how in rows:
cell = text.replace("|", "\\|").replace("\n", " ")
lines.append(f"| SpaceTimeVLM-{size} | **{cell}** | {seconds:.1f} | {how} |")
return "\n".join(lines) + f"\n\n{n_frames} frames, the same for every model."
def answer_seconds(video=None, question=None, model_choice=None, *args, **kwargs):
"""GPU time to reserve for one answer: 12 s per model. The full path took at most 7.4 s per model at 32 frames
(measured on 2026-11-29: 2B 7.4 s, 4B 6.7 s, 9B 7.4 s). A visitor's quota is checked against this number."""
return 12 * (len(SIZES) if model_choice == ALL else 1)
@spaces.GPU(duration=answer_seconds, size="xlarge")
def answer(video: str, question: str, model_choice: str = SIZES[0], num_frames: int = 32, short_answer: bool = False,
clip: dict | None = None):
"""Answer a spatial question about a video of a scene with SpaceTimeVLM.
Args:
video: Path or URL of a video file, for example a walkthrough of a room.
question: The question, for example "How many chairs are in this room?".
model_choice: The model size ("2B", "4B" or "9B"), or "All of them" to compare the three answers.
num_frames: Number of frames sampled uniformly from the video (8, 16 or 32).
short_answer: Use the VSI-Bench prompt, which asks for a single word or phrase.
Returns:
The answer (a table of answers for "All of them") and the frames the model saw.
"""
if not video:
raise gr.Error("Add a video first.")
if not question or not question.strip():
raise gr.Error("Write a question first.")
if model_choice != ALL and model_choice not in MODELS:
raise gr.Error(f"Unknown model: {model_choice}")
num_frames = clamp_frames(num_frames)
if clip_matches(clip, video, num_frames): # the frames sampled when the video was added
frames, clip_id = load_frames(clip["dir"]), clip["id"]
else: # an API call, or the video changed since
with tempfile.TemporaryDirectory() as d:
save_frames(video, num_frames, d)
frames, clip_id = load_frames(d), None
question = question.strip()
prompt = SHORT_ANSWER_PROMPT.format(question) if short_answer else question
rows = []
for size in sizes_of(model_choice):
model, prefix = MODELS[size], PREFIXES.get((clip_id, size))
start = time.perf_counter()
text, how = None, "full run"
if PREPARE_AHEAD: # say why the prepared path was not taken, to tell the cases apart on the Space
if clip_id is None:
how = "full run: the frames were sampled again"
elif prefix is None:
how = "full run: this GPU worker has no prepared video"
else:
try:
text = answer_from_prefix(model, prefix, prompt)
how = "from the prepared video" if text is not None else "full run: the prompt has another prefix"
except Exception as e:
how = f"full run: the prepared path failed with {type(e).__name__}"
print(f"answer from prefix failed: {type(e).__name__}: {e}", flush=True)
if text is None:
(text,) = model.answer(model.prepare(frames, [prompt]), max_new_tokens=MAX_NEW_TOKENS)
torch.cuda.synchronize()
rows.append((size, text, time.perf_counter() - start, how))
print("answered", [(size, round(seconds, 1), how) for size, _, seconds, how in rows],
f"{len(frames)} frames", flush=True)
return answers_table(rows, len(frames)), thumbnails(frames)
# ---- page ----
MODEL_LINKS = "".join(f'<a href="https://huggingface.co/{REPO.format(s)}" target="_blank">{s}</a>'
for s in ("2B", "4B", "9B"))
HEADER = f"""<header id="head">
<h1>SpaceTimeVLM</h1>
<p class="lede">Ask a spatial question about a video of a scene: how many objects there are, how far apart two
objects are, how large a room is.</p>
<p class="about">SpaceTimeVLM is Qwen3.5 with the frozen geometry encoder of VGGT-1B, read through a 3D-aware
cross-attention, so every visual token has a position in the scene.</p>
<p class="models"><span>Models</span>{MODEL_LINKS}</p>
</header>"""
NO_ANSWER_YET = '<p class="empty">Add a video, write a question and press Ask. The answer appears here.</p>'
HOW_IT_WORKS = f"""- The video is decoded with ffmpeg, which applies the rotation flag of phone videos. Only the first
{MAX_VIDEO_SECONDS // 60} minutes are read.
- 8, 16 or 32 frames are sampled uniformly, as soon as the video is added. These are the frame counts the models
were trained with, and the frames are shown next to the answer.
- "Short answer" wraps the question in the VSI-Bench prompt used for the benchmark scores on the model cards."""
NOTES = """<footer id="notes">The models are released under CC BY-NC 4.0 (non-commercial use), because of the
VGGT-1B weights. The example video is an excerpt of
<a href="https://commons.wikimedia.org/wiki/File:UE4Arch.com_-_Viennese_apartment.webm" target="_blank">UE4Arch.com
- Viennese apartment</a> by UE4Arch.com (CC BY-SA 4.0).</footer>"""
# Plain look: white page, Open Sans, one dark-teal accent, thin borders, no shadows.
TEAL = gr.themes.Color(c50="#eef4f6", c100="#dbe8ee", c200="#b9d1db", c300="#9cc4d4", c400="#5f8fa1", c500="#3a6f83",
c600="#27586b", c700="#1b4756", c800="#133844", c900="#0d2a33", c950="#081c22")
THEME = gr.themes.Base(
primary_hue=TEAL, neutral_hue="slate", radius_size="sm",
font=[gr.themes.GoogleFont("Open Sans"), "Helvetica Neue", "Arial", "sans-serif"],
font_mono=[gr.themes.GoogleFont("JetBrains Mono"), "ui-monospace", "monospace"],
).set(
body_background_fill="white", block_shadow="none", block_shadow_dark="none",
block_label_background_fill="transparent", block_label_border_width="0px", block_label_text_weight="600",
block_title_text_weight="600",
button_primary_background_fill="*primary_800", button_primary_background_fill_hover="*primary_700",
button_primary_text_color="white", button_primary_shadow="none",
button_primary_background_fill_dark="*primary_500", button_primary_background_fill_hover_dark="*primary_400",
checkbox_label_background_fill_selected="*primary_100", checkbox_label_background_fill_selected_dark="*primary_700",
button_large_text_weight="600",
)
CSS = """
:root { --st-accent: #133844; }
.dark { --st-accent: #9cc4d4; }
.gradio-container { max-width: 1120px !important; margin: 0 auto !important; }
#head { padding: 20px 0 14px; border-bottom: 3px solid var(--st-accent); margin-bottom: 6px; }
#head h1 { font-size: 2rem; font-weight: 700; line-height: 1.2; color: var(--st-accent); margin: 0 0 8px; }
#head p { max-width: 74ch; margin: 0; }
#head .lede { font-size: 1.05rem; }
#head .about { color: var(--body-text-color-subdued); font-size: 0.9rem; margin-top: 6px; }
#head .models { display: flex; flex-wrap: wrap; align-items: center; gap: 8px; margin-top: 12px; }
#head .models span { font-size: 0.72rem; font-weight: 700; letter-spacing: 0.07em; text-transform: uppercase;
color: var(--body-text-color-subdued); }
#head .models a { font-size: 0.8rem; font-weight: 600; color: var(--st-accent); text-decoration: none;
border: 1.5px solid currentColor; border-radius: 999px; padding: 1px 12px; }
#head .models a:hover { background: var(--st-accent); color: var(--body-background-fill); }
.flush, .flush .html-container { padding: 0 !important; }
#status { min-height: 0; }
#status:not(:has(p)) { display: none; }
#status p { font-size: 0.85rem; color: var(--body-text-color-subdued); }
#answer { border-top: 3px solid var(--st-accent); padding: 14px 2px 8px; min-height: 124px; }
#answer h2 { font-size: 1.9rem; font-weight: 700; line-height: 1.25; color: var(--st-accent); margin: 0 0 8px; }
#answer p { font-size: 0.85rem; color: var(--body-text-color-subdued); margin: 0; }
#answer p.empty { font-size: 0.95rem; padding-top: 6px; }
#answer table { border-collapse: collapse; width: 100%; margin: 0 0 10px; font-variant-numeric: tabular-nums; }
#answer table, #answer tr, #answer th, #answer td { border: 0 !important; background: transparent !important; }
#answer th, #answer td { padding: 7px 12px 7px 0; text-align: left; }
#answer thead th { border-top: 1.5px solid var(--body-text-color) !important;
border-bottom: 1px solid var(--body-text-color) !important;
font-weight: 600; font-size: 0.85rem; }
#answer tbody tr:last-child td { border-bottom: 1.5px solid var(--body-text-color) !important; }
#answer td strong { color: var(--st-accent); font-size: 1.05rem; }
#answer td:last-child { color: var(--body-text-color-subdued); font-size: 0.85rem; }
/* placeholder of the empty gallery: a line of text under its icon */
#seen .empty { display: flex; flex-direction: column; align-items: center; justify-content: center; gap: 10px;
min-height: 200px; }
#seen .empty::after { content: "The frames sampled from your video appear here."; font-size: 0.9rem;
color: var(--body-text-color-subdued); text-align: center; padding: 0 16px; }
#notes { font-size: 0.8rem; color: var(--body-text-color-subdued); border-top: 1px solid var(--border-color-primary);
padding-top: 12px; margin-top: 8px; max-width: 96ch; }
#notes a { color: var(--st-accent); padding: 0; }
"""
with gr.Blocks(title="SpaceTimeVLM") as demo:
gr.HTML(HEADER, elem_classes="flush")
clip = gr.State(None)
with gr.Row(equal_height=False):
with gr.Column(scale=5):
video = gr.Video(label="Video", sources=["upload"], height=300)
status = gr.Markdown(elem_id="status")
question = gr.Textbox(label="Question", placeholder="How many chairs are in this room?", lines=2)
with gr.Row():
model_choice = gr.Radio(list(SIZES) + ([ALL] if len(SIZES) > 1 else []), value=SIZES[0], label="Model")
num_frames = gr.Radio(FRAME_CHOICES, value=32, label="Frames")
short_answer = gr.Checkbox(label="Short answer (VSI-Bench prompt)", value=False)
ask = gr.Button("Ask", variant="primary", size="lg")
gr.Examples(
examples=[[example_video(), "How many chairs are in this room?"],
[example_video(), "What is the size of this room in square meters?"]],
example_labels=["How many chairs are in this room?", "What is the size of this room in square meters?"],
inputs=[video, question], cache_examples=False, label="Or try the example video with a question")
with gr.Column(scale=6):
result = gr.Markdown(NO_ANSWER_YET, label="Answer", elem_id="answer")
seen = gr.Gallery(label="Frames the model saw", columns=4, height="auto", object_fit="cover", elem_id="seen")
with gr.Accordion("How it works", open=False):
gr.Markdown(HOW_IT_WORKS)
gr.HTML(NOTES, elem_classes="flush")
# The GPU steps share one queue, so a question sent while its video is still being prepared waits for it.
gpu = dict(concurrency_id="gpu", concurrency_limit=1)
in_background = dict(fn=prepare, inputs=[clip, model_choice], outputs=status, show_progress="hidden",
api_visibility="private", **gpu)
sample = dict(fn=decode, inputs=[video, num_frames], outputs=[clip, seen, status], api_visibility="private")
if PREPARE_AHEAD:
video.change(**sample).then(**in_background)
num_frames.change(**sample).then(**in_background)
model_choice.change(**in_background)
else: # the frames are still sampled ahead; ZeroGPU needs prepare bound to an event, so it stays hidden
video.change(**sample)
num_frames.change(**sample)
gr.Button(visible=False).click(**in_background)
inputs = [video, question, model_choice, num_frames, short_answer, clip]
ask.click(answer, inputs, [result, seen], api_name="answer", **gpu)
question.submit(answer, inputs, [result, seen], api_visibility="private", **gpu)
if __name__ == "__main__":
demo.launch(mcp_server=True, theme=THEME, css=CSS) # in Gradio 6 the theme and the CSS are given to launch()