File size: 11,526 Bytes
38ba49a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ab9f34
38ba49a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ab9f34
38ba49a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1ab9f34
 
 
38ba49a
1ab9f34
38ba49a
1ab9f34
38ba49a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import spaces  # ZeroGPU: must precede any torch / CUDA-touching import

import os
import re
import time
from typing import Tuple

import torch
from transformers import AutoModelForImageTextToText, AutoProcessor, LogitsProcessorList

from qwen_vl_utils import process_vision_info

MODEL_ID = "jsun39/Future-OPSD-Qwen3-VL-8B-Future-L1"

# OPSD protocol: this exact system prompt (from the model card / eval code) makes the
# model reason inside <reason> </reason> and answer inside <answer> </answer>.
SYSTEM_PROMPT = (
    "You are a helpful assistant that predicts what happens next in videos. "
    "First reason step by step inside <reason> </reason>, "
    "then give your final answer inside <answer> </answer>."
)

# Reference inference settings from the paper's eval harness
# (future-opsd/eval/lmms-eval/lmms_eval/models/qwen3_vl.py):
MIN_PIXELS = 256 * 28 * 28
MAX_PIXELS = 1605632
MAX_NUM_FRAMES = 32
REASONING_BUDGET = 512  # tokens of <reason> before budget forcing kicks in

device = "cuda" if torch.cuda.is_available() else "cpu"

processor = AutoProcessor.from_pretrained(
    MODEL_ID, min_pixels=MIN_PIXELS, max_pixels=MAX_PIXELS
)
tokenizer = processor.tokenizer
model = AutoModelForImageTextToText.from_pretrained(
    MODEL_ID,
    dtype=torch.bfloat16,
    attn_implementation="sdpa",
).eval().to(device)


class BudgetForcing:
    """Ported from the Future-OPSD eval harness (qwen3_vl.py).

    A row with no <answer> after `budget` generated tokens is forced to
    continue from "...</reason>\\n<answer>" and gets at most `answer_tokens`
    more tokens (then <|im_end|>).
    """

    def __init__(self, tok, prompt_len, budget, eos_id, answer_tokens=16):
        self.tok, self.prompt_len, self.budget, self.eos = tok, prompt_len, budget, eos_id
        self.answer_tokens = answer_tokens
        self.queue, self.deadline = {}, {}

    def __call__(self, input_ids, scores):
        t = input_ids.shape[1] - self.prompt_len
        if t == self.budget:
            for b in range(input_ids.shape[0]):
                gen = input_ids[b, self.prompt_len:].tolist()
                if self.eos in gen or self.tok.pad_token_id in gen:
                    continue  # finished
                text = self.tok.decode(gen, skip_special_tokens=True)
                if "<answer>" in text:
                    continue
                tail = ("\n</reason>\n" if "<reason>" in text and "</reason>" not in text else "\n") + "<answer>"
                self.queue[b] = self.tok(tail, add_special_tokens=False)["input_ids"]
                self.deadline[b] = t + len(self.queue[b]) + self.answer_tokens
        force = {}
        for b, q in list(self.queue.items()):
            if q:
                force[b] = q.pop(0)
        for b, dl in self.deadline.items():
            if b not in force and t >= dl:
                force[b] = self.eos
        for b, tid in force.items():
            scores[b] = float("-inf")
            scores[b, tid] = 0.0
        return scores


def _floor_to_frame_factor(nframes: int, factor: int = 2) -> int:
    return max(factor, (int(nframes) // factor) * factor)


def _cap_nframes(video_path: str, requested: int) -> int:
    """Cap requested frames to what the file actually has (floored to a factor of 2),
    matching the reference implementation."""
    try:
        from decord import VideoReader

        total = len(VideoReader(video_path))
        return _floor_to_frame_factor(min(requested, total))
    except Exception:
        return _floor_to_frame_factor(requested)


@spaces.GPU(duration=60)
def predict(video: str, question: str, nframes: int = 32, max_new_tokens: int = 1024,
            reasoning_budget: int = REASONING_BUDGET) -> Tuple[str, str, str, float]:
    """Predict what happens next in a video.

    Given an observed video clip and a question, the model reasons step by
    step inside <reason> </reason> and gives its final prediction inside
    <answer> </answer>.

    Args:
        video: Path to the input video clip (mp4/avi/mov/mkv/webm).
        question: The question to ask about what happens next, e.g.
            "What will the person most likely do next?"
        nframes: Number of frames sampled from the video (capped to the
            video's actual frame count; default 32 as in the paper).
        max_new_tokens: Maximum generated tokens.
        reasoning_budget: Token budget for the <reason> section; when
            exceeded without an <answer>, budget forcing appends
            "</reason>\\n<answer>" and allows only ~16 more tokens.

    Returns:
        Tuple of (final answer text, reasoning text, raw generation, elapsed seconds).
    """
    t0 = time.perf_counter()
    if not video:
        raise ValueError("Please provide a video clip first.")
    if isinstance(video, (tuple, list)):  # defensive: some gr.Video configs return (path, meta)
        video = video[0]
    question = (question or "").strip() or "What will the person most likely do next?"

    video = video[7:] if video.startswith("file://") else video
    nframes = max(2, int(nframes))
    capped = _cap_nframes(video, nframes)

    video_kwargs = {
        "min_pixels": MIN_PIXELS,
        "max_pixels": MAX_PIXELS,
        "nframes": capped,
    }
    messages = [
        {"role": "system", "content": [{"type": "text", "text": SYSTEM_PROMPT}]},
        {
            "role": "user",
            "content": [
                {"type": "video", "video": video, **video_kwargs},
                {"type": "text", "text": question},
            ],
        },
    ]

    texts = processor.apply_chat_template(
        messages, tokenize=False, add_generation_prompt=True
    )
    image_inputs, video_inputs, processed_video_kwargs = process_vision_info(
        messages,
        return_video_kwargs=True,
        image_patch_size=16,
        return_video_metadata=True,
    )
    video_list, video_metadata_list = (
        map(list, zip(*video_inputs)) if video_inputs is not None else (None, None)
    )
    inputs = processor(
        text=texts,
        images=image_inputs,
        videos=video_list,
        video_metadata=video_metadata_list,
        **processed_video_kwargs,
        do_resize=False,
        return_tensors="pt",
    ).to(model.device)

    prompt_len = inputs["input_ids"].shape[1]
    gen_kwargs = {
        "max_new_tokens": min(int(max_new_tokens), int(reasoning_budget) + 40),
        "do_sample": False,
        "temperature": None,
        "top_p": None,
        "num_beams": 1,
        "pad_token_id": tokenizer.pad_token_id,
    }
    if reasoning_budget and reasoning_budget > 0:
        gen_kwargs["logits_processor"] = LogitsProcessorList([
            BudgetForcing(tokenizer, prompt_len, int(reasoning_budget),
                         tokenizer.convert_tokens_to_ids("<|im_end|>"))
        ])

    with torch.inference_mode():
        out = model.generate(**inputs, **gen_kwargs)
    generated = processor.batch_decode(
        out[:, prompt_len:], skip_special_tokens=True
    )[0].strip()

    elapsed = time.perf_counter() - t0
    print(f"[future-opsd] frames={capped} prompt={prompt_len} out_len={out.shape[1] - prompt_len} "
          f"time={elapsed:.1f}s", flush=True)

    # The model often hits EOS right after the answer text without writing </answer>,
    # so accept an unclosed tag (matches the reference's closed-tag behavior when present).
    m = re.search(r"<answer>(.*?)(?:</answer>|$)", generated, re.S)
    answer = m.group(1).strip() if m else generated.strip()
    m = re.search(r"<reason>(.*?)(?:</reason>|$)", generated, re.S)
    reason = m.group(1).strip() if m else ""
    return answer, reason, generated, round(elapsed, 1)


import gradio as gr  # noqa: E402  (after spaces/torch by design)

CSS = """
#col-container { max-width: 1100px; margin: 0 auto; }
.dark .gradio-container { color: var(--body-text-color); }
"""

DESCRIPTION = """
# Future-OPSD · Video foresight reasoning 🔮

Upload a short **video clip** and ask what happens next. [Future-OPSD](https://arxiv.org/abs/2611.26954)
trains a video VLM on unlabeled past–future pairs via on-policy self-distillation: the student sees only
the observed video, while a frozen teacher copy of the same model sees the real future frames. The model
first reasons inside `<reason> </reason>`, then answers inside `<answer> </answer>`.

- 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)
- Code: [Jingchensun/future-opsd](https://github.com/Jingchensun/future-opsd) · Project page: [jingchensun.github.io/future-opsd](https://jingchensun.github.io/future-opsd/)
- Protocol: 32 frames, greedy decoding, 512-token reasoning budget with budget forcing (per the paper's eval harness)
"""

with gr.Blocks() as demo:
    with gr.Column(elem_id="col-container"):
        gr.Markdown(DESCRIPTION)
        with gr.Row():
            with gr.Column():
                video_in = gr.Video(label="Observed video clip", sources=["upload"])
                question = gr.Textbox(
                    label="Question",
                    placeholder="What will the person most likely do next?",
                    value="What will the person most likely do next?",
                )
                run_btn = gr.Button("Predict", variant="primary")
            with gr.Column():
                answer_out = gr.Textbox(label="Predicted answer", lines=3, buttons=["copy"])
                reason_out = gr.Textbox(label="Reasoning", lines=8, buttons=["copy"])
                raw_out = gr.Textbox(label="Raw output", lines=2, visible=False)
                elapsed_out = gr.Textbox(label="Elapsed (s)", visible=False)
        with gr.Accordion("Advanced settings", open=False):
            nframes_in = gr.Slider(minimum=4, maximum=32, value=32, step=2,
                                   label="Sampled frames",
                                   info="Capped to the video's actual frame count")
            max_new_tokens_in = gr.Slider(minimum=64, maximum=1024, value=1024, step=64,
                                          label="Max new tokens")
            reasoning_budget_in = gr.Slider(minimum=64, maximum=1024, value=512, step=64,
                                            label="Reasoning budget (tokens)",
                                            info="After this many tokens without <answer>, the answer is forced")
        gr.Examples(
            examples=[
                ["sprint_start.mp4", "What will the person most likely do next?"],
                ["tennis_serve.mp4", "What will the person most likely do next?"],
                ["slicing_veggie.mp4", "What will the person most likely do next?"],
            ],
            inputs=[video_in, question],
            outputs=[answer_out, reason_out, raw_out, elapsed_out],
            fn=predict,
            cache_examples=True,
            cache_mode="lazy",
            label="Examples",
        )
        gr.Markdown(
            "Example videos are from the [repo-to-space-example-videos](https://huggingface.co/datasets/linoyts/repo-to-space-example-videos) "
            "dataset (free-to-use, CC0-style license)."
        )

    run_btn.click(
        fn=predict,
        inputs=[video_in, question, nframes_in, max_new_tokens_in, reasoning_budget_in],
        outputs=[answer_out, reason_out, raw_out, elapsed_out],
        api_name="predict",
    )


if __name__ == "__main__":
    demo.launch(theme=gr.themes.Citrus(), css=CSS, mcp_server=True)