davanstrien HF Staff commited on
Commit
dac9128
·
verified ·
1 Parent(s): 57fca2f

Sync from GitHub via hub-sync

Browse files
Files changed (2) hide show
  1. README.md +36 -0
  2. qwen38-caption.py +266 -0
README.md CHANGED
@@ -38,6 +38,42 @@ hf jobs uv run --image vllm/vllm-openai:latest --flavor a10g-small \
38
 
39
  ## Scripts
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  ### marlin-caption.py
42
 
43
  Runs [NemoStation/Marlin-2B](https://huggingface.co/NemoStation/Marlin-2B) (2B video
 
38
 
39
  ## Scripts
40
 
41
+ ### qwen38-caption.py
42
+
43
+ Runs [Qwen/Qwen3.8-27B](https://huggingface.co/Qwen/Qwen3.8-27B) (27B dense VLM,
44
+ Apache 2.0, not gated) over a directory of videos via vLLM — **whole videos, no
45
+ chunking**. The model ingests video natively at hour scale: an 11-minute film is
46
+ one request. The default video processor caps each video at 768 frames and a
47
+ fixed pixel budget, so videos longer than ~6.4 min are seen at a lower frame rate
48
+ and resolution (an hour at ~1 frame per 4.7 s). Output is a resumable parquet dataset, one row per video with
49
+ `caption` (and, with `--timestamps`, an `events` column of `<start - end>`
50
+ descriptions in global seconds).
51
+
52
+ `--timestamps` asks for a full event timeline instead of a prose caption. The
53
+ model reads times off per-frame time tags rather than estimating. On one
54
+ 11-minute film (96 events), spot-checked event times matched extracted frames to
55
+ within ~2 s, and on-screen text was quoted verbatim; that is one measured
56
+ example, not a guarantee.
57
+
58
+ Thinking mode is on for `--timestamps` (without it, the model sometimes answered
59
+ a timeline request with a one-line summary) and off for captions.
60
+ `--thinking` / `--no-thinking` override this. A truncated, empty or
61
+ event-less answer is stored as an error row; `--retry-errors` tries it again.
62
+ Row ids include the prompt and mode, so changing them re-processes videos
63
+ instead of reusing old rows.
64
+
65
+ **Hardware**: bf16 weights are ~52 GB. The script's `[tool.hf-jobs]` header
66
+ sets `a100-large` and a pinned vLLM image, so `hf jobs uv run` needs no flavor
67
+ or image flags (hf CLI 1.32+). `--flavor h200` generated ~2.3x faster in our
68
+ test.
69
+
70
+ **vs marlin-caption.py**: Marlin is ~13x smaller and cheaper per minute of
71
+ footage, but must chunk at 60s (with per-chunk timestamp offsetting) and returns
72
+ grounding candidates rather than reliable timelines. Qwen3.8 handles the whole
73
+ film in one pass with verbatim on-screen-text reading. Rough guide: bulk
74
+ captioning of large collections → Marlin; rich timelines, text-heavy or
75
+ long-form material → Qwen3.8.
76
+
77
  ### marlin-caption.py
78
 
79
  Runs [NemoStation/Marlin-2B](https://huggingface.co/NemoStation/Marlin-2B) (2B video
qwen38-caption.py ADDED
@@ -0,0 +1,266 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "saturate[hf]==0.2.0",
5
+ # ]
6
+ #
7
+ # [tool.hf-jobs]
8
+ # image = "vllm/vllm-openai:v0.32.0"
9
+ # flavor = "a100-large"
10
+ # secrets = ["HF_TOKEN"]
11
+ # ///
12
+
13
+ """
14
+ Caption whole videos — no chunking — with Qwen3.8-27B, writing a resumable dataset.
15
+
16
+ Qwen3.8-27B (Apache 2.0, not gated) ingests videos natively at hour scale: an
17
+ 11-minute film is one request, and in --timestamps mode the model returns a
18
+ timeline of <start - end> events whose times are read off per-frame time tags
19
+ (verified accurate to the ~2s sampling interval, with on-screen text quoted
20
+ verbatim). This is the structural difference from marlin-caption.py, which must
21
+ split anything over ~60s into chunks.
22
+
23
+ Serves the model on vLLM inside the job and pumps every video in INPUT_DIR
24
+ through it with saturate: crash-safe parquet out, exact resume (re-running
25
+ skips completed videos), congestion-aware concurrency.
26
+
27
+ Input: Output (one parquet dataset):
28
+ /input/film.mp4 (11 min) -> 1 row per video — columns: video,
29
+ /input/clip.mp4 (45 s) -> duration_s, caption, events (JSON,
30
+ --timestamps mode), token counts
31
+
32
+ Examples:
33
+
34
+ # Caption a bucket of videos on HF Jobs (the [tool.hf-jobs] header sets the
35
+ # image, a100-large and HF_TOKEN; hf CLI >= 1.32)
36
+ hf jobs uv run --timeout 2h \\
37
+ -v hf://buckets/user/my-videos:/input:ro \\
38
+ https://huggingface.co/datasets/uv-scripts/video/raw/main/qwen38-caption.py \\
39
+ /input hf://buckets/user/my-videos/captions
40
+
41
+ # Timestamped event timeline per film instead of a prose caption
42
+ ... qwen38-caption.py /input hf://buckets/user/out --timestamps
43
+
44
+ # Local machine with a CUDA GPU (needs ~60 GB VRAM); vLLM comes from the
45
+ # Jobs image, so add it yourself
46
+ uv run --with vllm==0.32.0 qwen38-caption.py ./videos ./captions-out
47
+
48
+ Thinking mode defaults off for captions (little gain, big latency) but ON for
49
+ --timestamps: measured on the 11-min film, the non-thinking model may answer a
50
+ timeline request with a one-line summary, while thinking mode produced a
51
+ frame-verified 96-event timeline. --thinking / --no-thinking overrides.
52
+
53
+ Frame budget: the model's default video processor caps a video at 768 frames
54
+ and a fixed pixel budget (~12k video tokens). At the default 2 fps anything longer than
55
+ ~6.4 min is capped, so a long film is seen at lower frame rate and resolution:
56
+ an 11-min film at ~1 frame per 0.9 s, an hour at ~1 frame per 4.7 s. Small
57
+ on-screen text gets harder to read as videos get longer. The model card's
58
+ "Long Video Understanding" section explains how to raise the budget.
59
+
60
+ Model: Qwen/Qwen3.8-27B (27B dense, hybrid GDN linear attention, vision tower).
61
+ bf16 weights are ~52 GB — a100-large is the smallest sensible Jobs flavor;
62
+ h200 generates ~2.3x faster if latency matters.
63
+ """
64
+
65
+ import argparse
66
+ import hashlib
67
+ import json
68
+ import logging
69
+ import re
70
+ import shutil
71
+ import subprocess
72
+ import sys
73
+ from pathlib import Path
74
+
75
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
76
+ logger = logging.getLogger(__name__)
77
+
78
+ MODEL = "Qwen/Qwen3.8-27B"
79
+ VIDEO_EXTENSIONS = {".mp4", ".mkv", ".webm", ".mov", ".avi", ".m4v"}
80
+
81
+ CAPTION_PROMPT = (
82
+ "Describe this video: the setting, the people, what happens over its course, "
83
+ "and any text that appears on screen."
84
+ )
85
+ TIMESTAMPS_PROMPT = (
86
+ "Watch this video and produce a timeline of events covering the WHOLE video "
87
+ "from start to finish. Output ONLY the timeline, one event per line. For "
88
+ "each event give the time range as <start - end> in decimal seconds "
89
+ "(e.g. <95.0 - 112.5>) followed by a one-sentence description. "
90
+ "Include title cards, on-screen text (quoted), and scene changes. "
91
+ "Do not summarize; cover the full duration."
92
+ )
93
+
94
+ THINK = re.compile(r"<think>.*?</think>\s*|^.*?</think>\s*", re.DOTALL)
95
+ # accepts decimal seconds (<95.0 - 112.5>) and clock forms (<01:35 - 01:52>)
96
+ EVENT_LINE = re.compile(
97
+ r"<(\d+(?::\d{2}){0,2}(?:\.\d+)?)\s*-\s*(\d+(?::\d{2}){0,2}(?:\.\d+)?)>\s*[:–\-]?\s*(.+)")
98
+
99
+
100
+ def to_seconds(ts: str) -> float:
101
+ parts = [float(x) for x in ts.split(":")]
102
+ out = 0.0
103
+ for part in parts:
104
+ out = out * 60 + part
105
+ return round(out, 2)
106
+
107
+
108
+ def probe_duration(path: Path) -> float | None:
109
+ try:
110
+ out = subprocess.run(
111
+ ["ffprobe", "-v", "error", "-show_entries", "format=duration",
112
+ "-of", "csv=p=0", str(path)],
113
+ capture_output=True, text=True, timeout=120)
114
+ return round(float(out.stdout.strip()), 2)
115
+ except (ValueError, subprocess.SubprocessError):
116
+ return None
117
+
118
+
119
+ def config_tag(**config) -> str:
120
+ """Short hash of everything that changes the output, so resume never reuses
121
+ a row produced under a different prompt, mode or frame rate."""
122
+ return hashlib.sha256(json.dumps(config, sort_keys=True).encode()).hexdigest()[:12]
123
+
124
+
125
+ def parse_events(text: str) -> list[dict]:
126
+ return [{"start": to_seconds(a), "end": to_seconds(b), "text": d.strip()}
127
+ for a, b, d in EVENT_LINE.findall(text)]
128
+
129
+
130
+ def main():
131
+ parser = argparse.ArgumentParser(
132
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
133
+ parser.add_argument("input_dir", help="Directory of videos (e.g. a mounted bucket)")
134
+ parser.add_argument("output", help="Dataset output: hf://datasets/..., hf://buckets/..., or local path")
135
+ parser.add_argument("--timestamps", action="store_true",
136
+ help="Return a <start - end> event timeline per video instead of a prose caption")
137
+ parser.add_argument("--prompt", help="Override the built-in prompt")
138
+ parser.add_argument("--thinking", action=argparse.BooleanOptionalAction, default=None,
139
+ help="Thinking mode. Default: on for --timestamps (measured: without it the "
140
+ "model may summarize instead of covering the video), off otherwise")
141
+ parser.add_argument("--max-videos", type=int, help="Only process the first N videos (testing)")
142
+ parser.add_argument("--window-max", type=int, default=8,
143
+ help="Max in-flight requests (default 8 — whole-video requests are large)")
144
+ parser.add_argument("--max-model-len", type=int, default=131072)
145
+ parser.add_argument("--retry-errors", action="store_true",
146
+ help="Re-attempt rows that errored in a previous run")
147
+ args = parser.parse_args()
148
+ if args.window_max < 1:
149
+ sys.exit("--window-max must be at least 1")
150
+
151
+ if shutil.which("ffprobe") is None:
152
+ sys.exit("ffprobe not found — use the vllm/vllm-openai image (has it) or install ffmpeg")
153
+
154
+ input_root = Path(args.input_dir).resolve()
155
+ videos = sorted(p for p in input_root.rglob("*")
156
+ if p.suffix.lower() in VIDEO_EXTENSIONS)
157
+ if args.max_videos:
158
+ videos = videos[: args.max_videos]
159
+ if not videos:
160
+ sys.exit(f"no videos found under {input_root}")
161
+ logger.info("found %d videos", len(videos))
162
+
163
+ prompt = args.prompt or (TIMESTAMPS_PROMPT if args.timestamps else CAPTION_PROMPT)
164
+ thinking = args.timestamps if args.thinking is None else args.thinking
165
+ tag = config_tag(model=MODEL, prompt=prompt, timestamps=args.timestamps,
166
+ thinking=thinking)
167
+ logger.info("config tag %s (part of every row id; changing the prompt or mode "
168
+ "re-processes videos instead of reusing old rows)", tag)
169
+
170
+ # Row id = relative path + file size + config tag: a replaced video or a
171
+ # changed setting gets a new id, so resume cannot return a stale result.
172
+ rows = [(f"{p.relative_to(input_root)}|{p.stat().st_size}|{tag}",
173
+ {"video": str(p.relative_to(input_root)), "uri": p.as_uri(),
174
+ "duration_s": probe_duration(p)})
175
+ for p in videos]
176
+ # Timeline output scales with video length; measured 9.6K tokens for an
177
+ # 11-min film — leave generous headroom. Thinking needs its own budget on top.
178
+ max_tokens = 16384 if args.timestamps else 4096
179
+ if thinking:
180
+ max_tokens += 32768
181
+
182
+ def to_request(row: dict) -> dict:
183
+ req = {
184
+ "model": MODEL,
185
+ "messages": [{"role": "user", "content": [
186
+ {"type": "video_url", "video_url": {"url": row["uri"]}},
187
+ {"type": "text", "text": prompt},
188
+ ]}],
189
+ "max_tokens": max_tokens,
190
+ }
191
+ if thinking: # model-card sampling params per mode
192
+ req.update({"temperature": 1.0, "top_p": 0.95, "top_k": 20})
193
+ else:
194
+ req.update({"temperature": 0.7, "top_p": 0.8, "top_k": 20,
195
+ "presence_penalty": 1.5,
196
+ "chat_template_kwargs": {"enable_thinking": False}})
197
+ return req
198
+
199
+ def parse(row: dict, resp: dict) -> dict:
200
+ # Raising here makes saturate store an error row, which --retry-errors
201
+ # re-attempts; a truncated or empty answer must not count as done.
202
+ choice = resp["choices"][0]
203
+ raw = choice["message"]["content"] or ""
204
+ if choice.get("finish_reason") == "length":
205
+ raise ValueError(f"truncated at max_tokens={max_tokens} (finish_reason=length)")
206
+ if "<think>" in raw and "</think>" not in raw:
207
+ raise ValueError("reasoning never finished (no </think>)")
208
+ text = THINK.sub("", raw).strip()
209
+ if not text:
210
+ raise ValueError("empty response")
211
+ usage = resp.get("usage") or {}
212
+ out = {"video": row["video"], "duration_s": row["duration_s"],
213
+ "caption": text,
214
+ "prompt_tokens": usage.get("prompt_tokens"),
215
+ "completion_tokens": usage.get("completion_tokens")}
216
+ if args.timestamps:
217
+ events = parse_events(text)
218
+ if not events:
219
+ raise ValueError("no <start - end> events in the response")
220
+ duration = row["duration_s"]
221
+ if duration and any(e["end"] > duration + 2.0 for e in events):
222
+ raise ValueError(f"event ends past the video's {duration}s duration")
223
+ out["events"] = json.dumps(events)
224
+ return out
225
+
226
+ from saturate import Auto, Engine, pump
227
+
228
+ with Engine(
229
+ MODEL,
230
+ engine="vllm",
231
+ extra_args=[
232
+ "--allowed-local-media-path", str(input_root),
233
+ "--max-model-len", str(args.max_model_len),
234
+ # Model card's video flag. vLLM 0.32 then samples at the model's
235
+ # default 2 fps (a 60 s clip -> 119 frames). Do NOT also pass
236
+ # --mm-processor-kwargs '{"fps": ..., "do_sample_frames": true}':
237
+ # on 0.32 the frames are sampled twice and every request 400s.
238
+ "--media-io-kwargs", json.dumps({"video": {"num_frames": -1}}),
239
+ # Unbounded growth on distinct videos — OOM-kills the node if left on.
240
+ "--mm-processor-cache-gb", "0",
241
+ ],
242
+ ) as endpoint:
243
+ stats = pump(
244
+ rows,
245
+ to_request=to_request,
246
+ parse=parse,
247
+ endpoint=endpoint,
248
+ output=args.output,
249
+ window=Auto(initial=min(4, args.window_max), min_limit=1,
250
+ max_limit=args.window_max),
251
+ retry_errors=args.retry_errors,
252
+ # A thinking timeline can run to ~49k tokens; at 8 in flight one
253
+ # request can take longer than saturate's 1800 s default.
254
+ read_timeout=7200,
255
+ )
256
+
257
+ logger.info("done: %d ok, %d failed, %.1f tok/s (window settled at %d)",
258
+ stats.rows_processed, stats.rows_failed,
259
+ stats.tokens_per_sec, stats.final_limit)
260
+ if stats.rows_failed:
261
+ logger.warning("failed rows are recorded in the output; re-run with "
262
+ "--retry-errors to attempt them again")
263
+
264
+
265
+ if __name__ == "__main__":
266
+ main()