multimodalart HF Staff commited on
Commit
38ba49a
·
verified ·
1 Parent(s): 0872f33

Upload folder using huggingface_hub

Browse files
Files changed (7) hide show
  1. .gitattributes +3 -0
  2. README.md +27 -6
  3. app.py +275 -0
  4. requirements.txt +5 -0
  5. slicing_veggie.mp4 +3 -0
  6. sprint_start.mp4 +3 -0
  7. tennis_serve.mp4 +3 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ slicing_veggie.mp4 filter=lfs diff=lfs merge=lfs -text
37
+ sprint_start.mp4 filter=lfs diff=lfs merge=lfs -text
38
+ tennis_serve.mp4 filter=lfs diff=lfs merge=lfs -text
README.md CHANGED
@@ -1,13 +1,34 @@
1
  ---
2
- title: Future Opsd
3
- emoji: 📚
4
- colorFrom: pink
5
- colorTo: green
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: Future-OPSD Video Foresight Reasoning
3
+ emoji: 🔮
4
+ colorFrom: yellow
5
+ colorTo: purple
6
  sdk: gradio
7
  sdk_version: 6.32.0
 
8
  app_file: app.py
9
  pinned: false
10
+ license: apache-2.0
11
+ short_description: Predict what happens next in a video clip
12
+ python_version: "3.12"
13
+ startup_duration_timeout: 30m
14
  ---
15
 
16
+ # Future-OPSD · Video foresight reasoning
17
+
18
+ Demo of **Future-OPSD** (Qwen3-VL-8B fine-tune) from
19
+ [*Learning Video Foresight Reasoning from Unlabeled Videos via On-Policy Self-Distillation*](https://arxiv.org/abs/2611.26954).
20
+
21
+ Upload a short video clip and ask what happens next — the model first reasons step by step inside
22
+ `<reason> </reason>`, then gives its final prediction inside `<answer> </answer>`.
23
+
24
+ - Model: [jsun39/Future-OPSD-Qwen3-VL-8B-Future-L1](https://huggingface.co/jsun39/Future-OPSD-Qwen3-VL-8B-Future-L1)
25
+ - Code: [Jingchensun/future-opsd](https://github.com/Jingchensun/future-opsd)
26
+ - Project page: [jingchensun.github.io/future-opsd](https://jingchensun.github.io/future-opsd/)
27
+
28
+ Protocol (per the paper's evaluation harness): 32 sampled frames, greedy decoding, and a 512-token
29
+ reasoning budget with budget forcing — if no `<answer>` has been produced after the budget is spent,
30
+ the generation is forced into `</reason> <answer>` and truncated.
31
+
32
+ Example videos are from the
33
+ [repo-to-space-example-videos](https://huggingface.co/datasets/linoyts/repo-to-space-example-videos)
34
+ dataset (free-to-use, CC0-style license).
app.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import spaces # ZeroGPU: must precede any torch / CUDA-touching import
2
+
3
+ import os
4
+ import re
5
+ import time
6
+ from typing import Tuple
7
+
8
+ import torch
9
+ from transformers import AutoModelForImageTextToText, AutoProcessor, LogitsProcessorList
10
+
11
+ from qwen_vl_utils import process_vision_info
12
+
13
+ MODEL_ID = "jsun39/Future-OPSD-Qwen3-VL-8B-Future-L1"
14
+
15
+ # OPSD protocol: this exact system prompt (from the model card / eval code) makes the
16
+ # model reason inside <reason> </reason> and answer inside <answer> </answer>.
17
+ SYSTEM_PROMPT = (
18
+ "You are a helpful assistant that predicts what happens next in videos. "
19
+ "First reason step by step inside <reason> </reason>, "
20
+ "then give your final answer inside <answer> </answer>."
21
+ )
22
+
23
+ # Reference inference settings from the paper's eval harness
24
+ # (future-opsd/eval/lmms-eval/lmms_eval/models/qwen3_vl.py):
25
+ MIN_PIXELS = 256 * 28 * 28
26
+ MAX_PIXELS = 1605632
27
+ MAX_NUM_FRAMES = 32
28
+ REASONING_BUDGET = 512 # tokens of <reason> before budget forcing kicks in
29
+
30
+ device = "cuda" if torch.cuda.is_available() else "cpu"
31
+
32
+ processor = AutoProcessor.from_pretrained(
33
+ MODEL_ID, min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS
34
+ )
35
+ tokenizer = processor.tokenizer
36
+ model = AutoModelForImageTextToText.from_pretrained(
37
+ MODEL_ID,
38
+ dtype=torch.bfloat16,
39
+ attn_implementation="sdpa",
40
+ ).eval().to(device)
41
+
42
+
43
+ class BudgetForcing:
44
+ """Ported from the Future-OPSD eval harness (qwen3_vl.py).
45
+
46
+ A row with no <answer> after `budget` generated tokens is forced to
47
+ continue from "...</reason>\\n<answer>" and gets at most `answer_tokens`
48
+ more tokens (then <|im_end|>).
49
+ """
50
+
51
+ def __init__(self, tok, prompt_len, budget, eos_id, answer_tokens=16):
52
+ self.tok, self.prompt_len, self.budget, self.eos = tok, prompt_len, budget, eos_id
53
+ self.answer_tokens = answer_tokens
54
+ self.queue, self.deadline = {}, {}
55
+
56
+ def __call__(self, input_ids, scores):
57
+ t = input_ids.shape[1] - self.prompt_len
58
+ if t == self.budget:
59
+ for b in range(input_ids.shape[0]):
60
+ gen = input_ids[b, self.prompt_len:].tolist()
61
+ if self.eos in gen or self.tok.pad_token_id in gen:
62
+ continue # finished
63
+ text = self.tok.decode(gen, skip_special_tokens=True)
64
+ if "<answer>" in text:
65
+ continue
66
+ tail = ("\n</reason>\n" if "<reason>" in text and "</reason>" not in text else "\n") + "<answer>"
67
+ self.queue[b] = self.tok(tail, add_special_tokens=False)["input_ids"]
68
+ self.deadline[b] = t + len(self.queue[b]) + self.answer_tokens
69
+ force = {}
70
+ for b, q in list(self.queue.items()):
71
+ if q:
72
+ force[b] = q.pop(0)
73
+ for b, dl in self.deadline.items():
74
+ if b not in force and t >= dl:
75
+ force[b] = self.eos
76
+ for b, tid in force.items():
77
+ scores[b] = float("-inf")
78
+ scores[b, tid] = 0.0
79
+ return scores
80
+
81
+
82
+ def _floor_to_frame_factor(nframes: int, factor: int = 2) -> int:
83
+ return max(factor, (int(nframes) // factor) * factor)
84
+
85
+
86
+ def _cap_nframes(video_path: str, requested: int) -> int:
87
+ """Cap requested frames to what the file actually has (floored to a factor of 2),
88
+ matching the reference implementation."""
89
+ try:
90
+ from decord import VideoReader
91
+
92
+ total = len(VideoReader(video_path))
93
+ return _floor_to_frame_factor(min(requested, total))
94
+ except Exception:
95
+ return _floor_to_frame_factor(requested)
96
+
97
+
98
+ @spaces.GPU(duration=180)
99
+ def predict(video: str, question: str, nframes: int = 32, max_new_tokens: int = 1024,
100
+ reasoning_budget: int = REASONING_BUDGET) -> Tuple[str, str, str, float]:
101
+ """Predict what happens next in a video.
102
+
103
+ Given an observed video clip and a question, the model reasons step by
104
+ step inside <reason> </reason> and gives its final prediction inside
105
+ <answer> </answer>.
106
+
107
+ Args:
108
+ video: Path to the input video clip (mp4/avi/mov/mkv/webm).
109
+ question: The question to ask about what happens next, e.g.
110
+ "What will the person most likely do next?"
111
+ nframes: Number of frames sampled from the video (capped to the
112
+ video's actual frame count; default 32 as in the paper).
113
+ max_new_tokens: Maximum generated tokens.
114
+ reasoning_budget: Token budget for the <reason> section; when
115
+ exceeded without an <answer>, budget forcing appends
116
+ "</reason>\\n<answer>" and allows only ~16 more tokens.
117
+
118
+ Returns:
119
+ Tuple of (reasoning text, final answer text, raw generation, elapsed seconds).
120
+ """
121
+ t0 = time.perf_counter()
122
+ if not video:
123
+ raise ValueError("Please provide a video clip first.")
124
+ if isinstance(video, (tuple, list)): # defensive: some gr.Video configs return (path, meta)
125
+ video = video[0]
126
+ question = (question or "").strip() or "What will the person most likely do next?"
127
+
128
+ video = video[7:] if video.startswith("file://") else video
129
+ nframes = max(2, int(nframes))
130
+ capped = _cap_nframes(video, nframes)
131
+
132
+ video_kwargs = {
133
+ "min_pixels": MIN_PIXELS,
134
+ "max_pixels": MAX_PIXELS,
135
+ "nframes": capped,
136
+ }
137
+ messages = [
138
+ {"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]},
139
+ {
140
+ "role": "user",
141
+ "content": [
142
+ {"type": "video", "video": video, **video_kwargs},
143
+ {"type": "text", "text": question},
144
+ ],
145
+ },
146
+ ]
147
+
148
+ texts = processor.apply_chat_template(
149
+ messages, tokenize=False, add_generation_prompt=True
150
+ )
151
+ image_inputs, video_inputs, processed_video_kwargs = process_vision_info(
152
+ messages,
153
+ return_video_kwargs=True,
154
+ image_patch_size=16,
155
+ return_video_metadata=True,
156
+ )
157
+ video_list, video_metadata_list = (
158
+ map(list, zip(*video_inputs)) if video_inputs is not None else (None, None)
159
+ )
160
+ inputs = processor(
161
+ text=texts,
162
+ images=image_inputs,
163
+ videos=video_list,
164
+ video_metadata=video_metadata_list,
165
+ **processed_video_kwargs,
166
+ do_resize=False,
167
+ return_tensors="pt",
168
+ ).to(model.device)
169
+
170
+ prompt_len = inputs["input_ids"].shape[1]
171
+ gen_kwargs = {
172
+ "max_new_tokens": min(int(max_new_tokens), int(reasoning_budget) + 40),
173
+ "do_sample": False,
174
+ "temperature": None,
175
+ "top_p": None,
176
+ "num_beams": 1,
177
+ "pad_token_id": tokenizer.pad_token_id,
178
+ }
179
+ if reasoning_budget and reasoning_budget > 0:
180
+ gen_kwargs["logits_processor"] = LogitsProcessorList([
181
+ BudgetForcing(tokenizer, prompt_len, int(reasoning_budget),
182
+ tokenizer.convert_tokens_to_ids("<|im_end|>"))
183
+ ])
184
+
185
+ with torch.inference_mode():
186
+ out = model.generate(**inputs, **gen_kwargs)
187
+ generated = processor.batch_decode(
188
+ out[:, prompt_len:], skip_special_tokens=True
189
+ )[0].strip()
190
+
191
+ elapsed = time.perf_counter() - t0
192
+ print(f"[future-opsd] frames={capped} prompt={prompt_len} out_len={out.shape[1] - prompt_len} "
193
+ f"time={elapsed:.1f}s", flush=True)
194
+
195
+ m = re.search(r"<answer>(.*?)</answer>", generated, re.S)
196
+ answer = m.group(1).strip() if m else generated.strip()
197
+ m = re.search(r"<reason>(.*?)</reason>", generated, re.S)
198
+ reason = m.group(1).strip() if m else ""
199
+ return reason, answer, generated, round(elapsed, 1)
200
+
201
+
202
+ import gradio as gr # noqa: E402 (after spaces/torch by design)
203
+
204
+ CSS = """
205
+ #col-container { max-width: 1100px; margin: 0 auto; }
206
+ .dark .gradio-container { color: var(--body-text-color); }
207
+ """
208
+
209
+ DESCRIPTION = """
210
+ # Future-OPSD · Video foresight reasoning 🔮
211
+
212
+ Upload a short **video clip** and ask what happens next. [Future-OPSD](https://arxiv.org/abs/2611.26954)
213
+ trains a video VLM on unlabeled past–future pairs via on-policy self-distillation: the student sees only
214
+ the observed video, while a frozen teacher copy of the same model sees the real future frames. The model
215
+ first reasons inside `<reason> </reason>`, then answers inside `<answer> </answer>`.
216
+
217
+ - Model: [`jsun39/Future-OPSD-Qwen3-VL-8B-Future-L1`](https://huggingface.co/jsun39/Future-OPSD-Qwen3-VL-8B-Future-L1) (Qwen3-VL-8B fine-tune)
218
+ - Code: [Jingchensun/future-opsd](https://github.com/Jingchensun/future-opsd) · Project page: [jingchensun.github.io/future-opsd](https://jingchensun.github.io/future-opsd/)
219
+ - Protocol: 32 frames, greedy decoding, 512-token reasoning budget with budget forcing (per the paper's eval harness)
220
+ """
221
+
222
+ with gr.Blocks() as demo:
223
+ with gr.Column(elem_id="col-container"):
224
+ gr.Markdown(DESCRIPTION)
225
+ with gr.Row():
226
+ with gr.Column():
227
+ video_in = gr.Video(label="Observed video clip", sources=["upload"])
228
+ question = gr.Textbox(
229
+ label="Question",
230
+ placeholder="What will the person most likely do next?",
231
+ value="What will the person most likely do next?",
232
+ )
233
+ run_btn = gr.Button("Predict", variant="primary")
234
+ with gr.Column():
235
+ answer_out = gr.Textbox(label="Predicted answer", lines=3, buttons=["copy"])
236
+ reason_out = gr.Textbox(label="Reasoning", lines=8, buttons=["copy"])
237
+ raw_out = gr.Textbox(label="Raw output", lines=2, visible=False)
238
+ elapsed_out = gr.Textbox(label="Elapsed (s)", visible=False)
239
+ with gr.Accordion("Advanced settings", open=False):
240
+ nframes_in = gr.Slider(minimum=4, maximum=32, value=32, step=2,
241
+ label="Sampled frames",
242
+ info="Capped to the video's actual frame count")
243
+ max_new_tokens_in = gr.Slider(minimum=64, maximum=1024, value=1024, step=64,
244
+ label="Max new tokens")
245
+ reasoning_budget_in = gr.Slider(minimum=64, maximum=1024, value=512, step=64,
246
+ label="Reasoning budget (tokens)",
247
+ info="After this many tokens without <answer>, the answer is forced")
248
+ gr.Examples(
249
+ examples=[
250
+ ["sprint_start.mp4", "What will the person most likely do next?"],
251
+ ["tennis_serve.mp4", "What will the person most likely do next?"],
252
+ ["slicing_veggie.mp4", "What will the person most likely do next?"],
253
+ ],
254
+ inputs=[video_in, question],
255
+ outputs=[answer_out, reason_out, raw_out, elapsed_out],
256
+ fn=predict,
257
+ cache_examples=True,
258
+ cache_mode="lazy",
259
+ label="Examples",
260
+ )
261
+ gr.Markdown(
262
+ "Example videos are from the [repo-to-space-example-videos](https://huggingface.co/datasets/linoyts/repo-to-space-example-videos) "
263
+ "dataset (free-to-use, CC0-style license)."
264
+ )
265
+
266
+ run_btn.click(
267
+ fn=predict,
268
+ inputs=[video_in, question, nframes_in, max_new_tokens_in, reasoning_budget_in],
269
+ outputs=[answer_out, reason_out, raw_out, elapsed_out],
270
+ api_name="predict",
271
+ )
272
+
273
+
274
+ if __name__ == "__main__":
275
+ demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)
requirements.txt ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ transformers==5.14.1
2
+ accelerate
3
+ qwen-vl-utils==0.0.14
4
+ decord==0.6.0
5
+ pillow
slicing_veggie.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:dd50308ab3934280e9474b15c6dce541158dd07a0c5f16703210ef338a38b269
3
+ size 871629
sprint_start.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:82203071a3179d584688b81099d8708a35cc3c77ec70ed76f8f90fb59f60157b
3
+ size 1500628
tennis_serve.mp4 ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:b0573bb8c88de5a06d1528d9c8080d8a0d5ae91428624ab2fe8fa523867986fa
3
+ size 593435