davanstrien HF Staff commited on
Commit
1ee4ed7
·
verified ·
1 Parent(s): 95ed0db

Sync from GitHub via hub-sync

Browse files
Files changed (2) hide show
  1. README.md +63 -0
  2. marlin-caption.py +261 -0
README.md ADDED
@@ -0,0 +1,63 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ viewer: false
3
+ tags:
4
+ - uv-script
5
+ - video
6
+ - video-text-to-text
7
+ - video-captioning
8
+ - temporal-grounding
9
+ ---
10
+
11
+ # Video
12
+
13
+ Scripts for captioning and temporally grounding video files using HF Buckets and Jobs.
14
+
15
+ ## Quick Start
16
+
17
+ Scripts run directly from their Hub URL — no clone or local checkout needed:
18
+
19
+ ```bash
20
+ # Caption every video in a bucket: dense scene captions + timestamped events
21
+ hf jobs uv run --image vllm/vllm-openai:latest --flavor a10g-small \
22
+ -s HF_TOKEN \
23
+ -v hf://buckets/user/my-videos:/input:ro \
24
+ https://huggingface.co/datasets/uv-scripts/video/raw/main/marlin-caption.py \
25
+ /input hf://buckets/user/my-videos/captions
26
+
27
+ # Temporal grounding: when does an event happen?
28
+ hf jobs uv run --image vllm/vllm-openai:latest --flavor a10g-small \
29
+ -s HF_TOKEN \
30
+ -v hf://buckets/user/my-videos:/input:ro \
31
+ https://huggingface.co/datasets/uv-scripts/video/raw/main/marlin-caption.py \
32
+ /input hf://buckets/user/out --find "a person enters the room"
33
+ ```
34
+
35
+ ## Scripts
36
+
37
+ ### marlin-caption.py
38
+
39
+ Runs [NemoStation/Marlin-2B](https://huggingface.co/NemoStation/Marlin-2B) (2B video
40
+ VLM, gated — accept the license on the model page first) over a directory of videos
41
+ via vLLM. Output is a resumable parquet dataset: one row per ~60s chunk with `scene`,
42
+ `caption`, and an `events` column of `<start - end>` descriptions in seconds.
43
+ Re-running skips completed rows; failed rows are recorded, not dropped
44
+ (`--retry-errors` re-attempts them).
45
+
46
+ Videos longer than ~60s are split into chunks and event timestamps offset back to
47
+ global film time. This is required for correct timestamps, not an optimisation:
48
+ Marlin was trained on short clips and compresses any input onto a ~60s timeline.
49
+
50
+ `--find "event"` switches to grounding mode: each chunk returns a candidate
51
+ `(span_start, span_end)`. Spans are candidates, not detections — the model cannot
52
+ say "not present", so filter or verify downstream. When the event is real, spans
53
+ are precise to fractions of a second.
54
+
55
+ **Cost**: ~3s of GPU per minute of film on `a10g-small` at batch scale — about
56
+ $0.05 per hour of footage.
57
+
58
+ **Memory**: defaults encode a measured config (`--mm-processor-cache-gb 0`, in-flight
59
+ window capped at 24). vLLM's multimodal cache grows without bound on distinct videos
60
+ and will OOM a 15 GB node if re-enabled. On `a10g-large` and up, `--window-max 64`
61
+ is safe.
62
+
63
+ Run `--help` on the script for all options.
marlin-caption.py ADDED
@@ -0,0 +1,261 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # /// script
2
+ # requires-python = ">=3.11"
3
+ # dependencies = [
4
+ # "saturate[hf]",
5
+ # "vllm",
6
+ # "qwen-vl-utils",
7
+ # ]
8
+ # ///
9
+
10
+ """
11
+ Caption videos with timestamped events using Marlin-2B, writing a resumable dataset.
12
+
13
+ Marlin-2B (NemoStation/Marlin-2B, gated — accept the license on its model page first)
14
+ is a 2B video VLM producing dense scene captions with second-precise <start - end>
15
+ events, plus a temporal-grounding mode ("when does X happen?"). This recipe serves it
16
+ on vLLM and pumps every video in INPUT_DIR through it with saturate: crash-safe
17
+ parquet out, exact resume (re-running skips completed videos), congestion-aware
18
+ concurrency.
19
+
20
+ Videos longer than ~60s are split into chunks before captioning and event timestamps
21
+ are offset back to global film time. This is not an optimisation: Marlin compresses
22
+ any input onto a ~60s timeline (it was trained on short clips), so captioning a long
23
+ film in one request produces plausible-looking but wrong-scale timestamps.
24
+
25
+ Input: Output (one parquet dataset):
26
+ /input/film.mp4 (11 min) → 11 rows (one per 60s chunk), each with
27
+ /input/clip.mp4 (45 s) → 1 row — columns: video, chunk_start,
28
+ chunk_end, scene, events (JSON), caption,
29
+ prompt_tokens, completion_tokens
30
+
31
+ Examples:
32
+
33
+ # Caption a bucket of videos on HF Jobs (a10g-small handles ~24 concurrent 60s clips)
34
+ hf jobs uv run --image vllm/vllm-openai:latest --flavor a10g-small \\
35
+ -s HF_TOKEN \\
36
+ -v hf://buckets/user/my-videos:/input:ro \\
37
+ marlin-caption.py /input hf://buckets/user/my-videos/captions
38
+
39
+ # Temporal grounding instead of captioning
40
+ ... marlin-caption.py /input hf://buckets/user/out --find "a person enters the room"
41
+
42
+ Find mode returns CANDIDATES, not detections: Marlin always emits a span, even in
43
+ chunks where the event never occurs (the model has no "not present" answer). Treat
44
+ spans as a shortlist to rank or verify downstream — when the event is really there,
45
+ they are precise (matches caption-mode events to the half-second in testing).
46
+
47
+ # Local machine with a CUDA GPU
48
+ uv run marlin-caption.py ./videos ./captions-out
49
+
50
+ Memory safety (learned the hard way — defaults encode a measured config):
51
+ * --mm-processor-cache-gb 0 is passed to vLLM: its multimodal cache grows without
52
+ bound on distinct videos and OOM-kills 15 GB nodes. Do not re-enable for batch work.
53
+ * In-flight window is capped (default 24 ≈ the measured a10g-small ceiling for 60s
54
+ clips at 640px; each in-flight request holds ~290 MB of decoded frames). Use
55
+ --window-max 64 on RAM-rich flavors (a10g-large and up).
56
+
57
+ Model: NemoStation/Marlin-2B (Apache-2.0, Qwen3.5-2B fine-tune; served via vLLM's
58
+ native qwen3_5 implementation through an architecture override — no custom code).
59
+ """
60
+
61
+ import argparse
62
+ import json
63
+ import logging
64
+ import re
65
+ import shutil
66
+ import subprocess
67
+ import sys
68
+ from pathlib import Path
69
+
70
+ logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
71
+ logger = logging.getLogger(__name__)
72
+
73
+ MODEL = "NemoStation/Marlin-2B"
74
+ VIDEO_EXTENSIONS = {".mp4", ".mkv", ".webm", ".mov", ".avi", ".m4v"}
75
+ WORK_DIR = Path("/tmp/marlin_work")
76
+
77
+ # Canonical training-time prompts from the model's modeling_marlin.py — must match
78
+ # exactly; the model card warns that diverging silently degrades quality.
79
+ CAPTION_PROMPT = (
80
+ "Provide a spatial description of this clip followed by time-ranged events.\n"
81
+ "For each event, give the time range as <start - end> and a short description."
82
+ )
83
+ GROUNDING_PROMPT_TEMPLATE = (
84
+ 'Identify the timestamps during which "{event}" takes place. '
85
+ 'Output the time range as "From <start> to <end>." (numbers in seconds).'
86
+ )
87
+
88
+ THINK = re.compile(r"<think>.*?</think>\s*|^\s*<think>\s*\n*|</think>\s*", re.DOTALL)
89
+ EVENT_LINE = re.compile(r"<(\d+\.?\d*)\s*-\s*(\d+\.?\d*)>\s*(.*)")
90
+ SPAN = re.compile(r"From\s+(\d+\.?\d*)\s+to\s+(\d+\.?\d*)", re.IGNORECASE)
91
+
92
+
93
+ def probe_duration(path: Path) -> float | None:
94
+ """Video duration in seconds via ffprobe, or None if unreadable."""
95
+ try:
96
+ out = subprocess.run(
97
+ ["ffprobe", "-v", "error", "-show_entries", "format=duration",
98
+ "-of", "csv=p=0", str(path)],
99
+ capture_output=True, text=True, timeout=120)
100
+ return float(out.stdout.strip())
101
+ except (ValueError, subprocess.SubprocessError):
102
+ return None
103
+
104
+
105
+ def stage_chunks(videos: list[Path], input_root: Path, chunk_seconds: int) -> list[tuple[str, dict]]:
106
+ """Copy short videos / split long ones into WORK_DIR; return pump rows.
107
+
108
+ Chunk boundaries are re-encoded (libx264) rather than stream-copied: stream copy
109
+ snaps to keyframes and skews the timestamps we ground against — same choice
110
+ Marlin's own multi_find makes.
111
+ """
112
+ WORK_DIR.mkdir(parents=True, exist_ok=True)
113
+ rows = []
114
+ for n, video in enumerate(videos):
115
+ rel = video.relative_to(input_root).as_posix()
116
+ duration = probe_duration(video)
117
+ if duration is None:
118
+ logger.warning("skipping unreadable video: %s", rel)
119
+ continue
120
+ if duration <= chunk_seconds * 1.25: # tolerate slightly-long clips unsplit
121
+ staged = WORK_DIR / f"v{n:05d}.mp4"
122
+ if not staged.exists():
123
+ shutil.copyfile(video, staged)
124
+ rows.append((f"{rel}#0", {"video": rel, "path": str(staged),
125
+ "start": 0.0, "end": round(duration, 2)}))
126
+ continue
127
+ start = 0.0
128
+ c = 0
129
+ while start < duration - 5: # drop tails shorter than 5s
130
+ end = min(start + chunk_seconds, duration)
131
+ staged = WORK_DIR / f"v{n:05d}_c{c:04d}.mp4"
132
+ if not staged.exists():
133
+ subprocess.run(
134
+ ["ffmpeg", "-hide_banner", "-loglevel", "error",
135
+ "-ss", f"{start:.3f}", "-to", f"{end:.3f}", "-i", str(video),
136
+ "-c:v", "libx264", "-preset", "fast", "-an", "-y", str(staged)],
137
+ check=True, stdin=subprocess.DEVNULL)
138
+ rows.append((f"{rel}#{int(start)}", {"video": rel, "path": str(staged),
139
+ "start": round(start, 2), "end": round(end, 2)}))
140
+ start, c = end, c + 1
141
+ logger.info("split %s (%.0fs) into %d chunks", rel, duration, c)
142
+ return rows
143
+
144
+
145
+ def parse_caption_text(text: str, offset: float) -> tuple[str, list[dict]]:
146
+ """Split a Mode-1 caption into (scene, events); event times offset to global."""
147
+ scene, events = "", []
148
+ body = text.split("Events:", 1)
149
+ scene = body[0].replace("Scene:", "", 1).strip()
150
+ for line in (body[1] if len(body) > 1 else "").splitlines():
151
+ m = EVENT_LINE.match(line.strip())
152
+ if m:
153
+ events.append({"start": round(float(m.group(1)) + offset, 2),
154
+ "end": round(float(m.group(2)) + offset, 2),
155
+ "text": m.group(3).strip()})
156
+ return scene, events
157
+
158
+
159
+ def main():
160
+ parser = argparse.ArgumentParser(
161
+ description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
162
+ parser.add_argument("input_dir", help="Directory of videos (e.g. a mounted bucket)")
163
+ parser.add_argument("output", help="Dataset output: hf://datasets/..., hf://buckets/..., or local path")
164
+ parser.add_argument("--find", metavar="EVENT",
165
+ help="Temporal grounding mode: locate EVENT instead of captioning. "
166
+ "Every chunk returns a candidate span — filter downstream; "
167
+ "the model cannot say 'not present'.")
168
+ parser.add_argument("--chunk-seconds", type=int, default=60,
169
+ help="Chunk length for long videos (default 60 — Marlin's training scale)")
170
+ parser.add_argument("--max-videos", type=int, help="Only process the first N videos (testing)")
171
+ parser.add_argument("--window-max", type=int, default=24,
172
+ help="Max in-flight requests (default 24 for 15 GB nodes; 64 on a10g-large+)")
173
+ parser.add_argument("--max-model-len", type=int, default=65536)
174
+ parser.add_argument("--retry-errors", action="store_true",
175
+ help="Re-attempt rows that errored in a previous run")
176
+ args = parser.parse_args()
177
+
178
+ if shutil.which("ffmpeg") is None or shutil.which("ffprobe") is None:
179
+ sys.exit("ffmpeg/ffprobe not found — use the vllm/vllm-openai image (has both) "
180
+ "or install ffmpeg")
181
+
182
+ input_root = Path(args.input_dir)
183
+ videos = sorted(p for p in input_root.rglob("*")
184
+ if p.suffix.lower() in VIDEO_EXTENSIONS)
185
+ if args.max_videos:
186
+ videos = videos[: args.max_videos]
187
+ if not videos:
188
+ sys.exit(f"no videos found under {input_root}")
189
+ logger.info("found %d videos; staging chunks...", len(videos))
190
+ rows = stage_chunks(videos, input_root, args.chunk_seconds)
191
+ logger.info("%d chunk rows to process", len(rows))
192
+
193
+ prompt = (GROUNDING_PROMPT_TEMPLATE.format(event=args.find.strip())
194
+ if args.find else CAPTION_PROMPT)
195
+ max_tokens = 64 if args.find else 1024
196
+
197
+ def to_request(row: dict) -> dict:
198
+ return {
199
+ "messages": [{"role": "user", "content": [
200
+ {"type": "video_url", "video_url": {"url": f"file://{row['path']}"}},
201
+ {"type": "text", "text": prompt},
202
+ ]}],
203
+ "temperature": 0, # greedy, matching Marlin's own wrappers
204
+ "max_tokens": max_tokens,
205
+ }
206
+
207
+ def parse(row: dict, resp: dict) -> dict:
208
+ text = THINK.sub("", resp["choices"][0]["message"]["content"]).strip()
209
+ usage = resp.get("usage") or {}
210
+ out = {"video": row["video"], "chunk_start": row["start"], "chunk_end": row["end"],
211
+ "prompt_tokens": usage.get("prompt_tokens"),
212
+ "completion_tokens": usage.get("completion_tokens")}
213
+ if args.find:
214
+ m = SPAN.search(text)
215
+ out.update({
216
+ "span_start": round(float(m.group(1)) + row["start"], 2) if m else None,
217
+ "span_end": round(float(m.group(2)) + row["start"], 2) if m else None,
218
+ "format_ok": m is not None,
219
+ "raw": text,
220
+ })
221
+ else:
222
+ scene, events = parse_caption_text(text, offset=row["start"])
223
+ out.update({"scene": scene, "events": json.dumps(events), "caption": text})
224
+ return out
225
+
226
+ from saturate import Auto, Engine, pump
227
+
228
+ with Engine(
229
+ MODEL,
230
+ engine="vllm",
231
+ extra_args=[
232
+ # Marlin is a stock Qwen3.5-2B fine-tune; its custom code is only
233
+ # convenience wrappers, so route onto vLLM's native implementation.
234
+ "--hf-overrides", '{"architectures": ["Qwen3_5ForConditionalGeneration"]}',
235
+ "--allowed-local-media-path", str(WORK_DIR),
236
+ "--max-model-len", str(args.max_model_len),
237
+ # Unbounded growth on distinct videos — OOM-kills the node if left on.
238
+ "--mm-processor-cache-gb", "0",
239
+ "--enforce-eager",
240
+ ],
241
+ ) as endpoint:
242
+ stats = pump(
243
+ rows,
244
+ to_request=to_request,
245
+ parse=parse,
246
+ endpoint=endpoint,
247
+ output=args.output,
248
+ window=Auto(initial=8, max_limit=args.window_max),
249
+ retry_errors=args.retry_errors,
250
+ )
251
+
252
+ logger.info("done: %d ok, %d failed, %.1f tok/s (window settled at %d)",
253
+ stats.rows_processed, stats.rows_failed,
254
+ stats.tokens_per_sec, stats.final_limit)
255
+ if stats.rows_failed:
256
+ logger.warning("failed rows are recorded in the output; re-run with "
257
+ "--retry-errors to attempt them again")
258
+
259
+
260
+ if __name__ == "__main__":
261
+ main()