Hongyang-Du commited on
Commit
3d5feb7
·
verified ·
1 Parent(s): 77effa4

Add the recaptioning code (github.com/Hongyang-Du/prh-vlm@0b7b0b7)

Browse files
Files changed (3) hide show
  1. README.md +1 -0
  2. code/launch.sh +17 -0
  3. code/recaption.py +492 -0
README.md CHANGED
@@ -83,6 +83,7 @@ recaps = load_dataset(
83
  ### Generation
84
 
85
  - Model: `Qwen/Qwen2.5-VL-3B-Instruct`, vLLM 0.31.0, bf16, images capped at 640×28×28 pixels.
 
86
  - Both captions are two samples (`n=2`) of the same prompt: temperature 0.8, top-p 0.9, at most 160 new tokens.
87
  - Prompt (verbatim):
88
 
 
83
  ### Generation
84
 
85
  - Model: `Qwen/Qwen2.5-VL-3B-Instruct`, vLLM 0.31.0, bf16, images capped at 640×28×28 pixels.
86
+ - Code: [`code/recaption.py`](code/recaption.py) (`run`, `fix`, `stats`, `export`) and [`code/launch.sh`](code/launch.sh) (one worker per GPU).
87
  - Both captions are two samples (`n=2`) of the same prompt: temperature 0.8, top-p 0.9, at most 160 new tokens.
88
  - Prompt (verbatim):
89
 
code/launch.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # One recaption.py worker per GPU inside the recap-vllm container; workers claim shards through lock files,
3
+ # finished shards have .done (run) / .fixed (fix) markers, so rerunning this script resumes.
4
+ # docker exec recap-vllm bash /workspace/prh-vlm/blip3o_recap/launch.sh 0,1,2,3,4,5,6 [out_dir] [run|fix]
5
+ set -e
6
+ GPUS=${1:-0,1,2,3,4,5,6,7}
7
+ OUT=${2:-/workspace/prh-vlm/data/blip3o_recap/recap}
8
+ MODE=${3:-run}
9
+ cd /workspace/prh-vlm/blip3o_recap
10
+ if pgrep -f "^python3 recaption.py" >/dev/null; then echo "workers already running" >&2; exit 1; fi
11
+ mkdir -p "$OUT/logs"
12
+ rm -f "$OUT"/*.lock "$OUT"/*.fixlock # no worker is alive, so every lock is stale
13
+ for g in ${GPUS//,/ }; do
14
+ CUDA_VISIBLE_DEVICES=$g nohup python3 recaption.py $MODE --shards ../data/blip3o_recap/shards/*.tar --out "$OUT" \
15
+ --gpu-mem 0.85 >> "$OUT/logs/${MODE}_gpu$g.log" 2>&1 &
16
+ done
17
+ sleep 2; pgrep -f "^python3 recaption.py" | wc -l
code/recaption.py ADDED
@@ -0,0 +1,492 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Recaption BLIP3o-Recap webdataset shards with Qwen2.5-VL-3B-Instruct (vLLM, one process per GPU).
2
+
3
+ Each image keeps its original caption and gets two new ones; one jsonl per shard with
4
+ ``{key, source_shard, orig_caption, recap_1, recap_2}``. Rejected samples (see ``violations``) are resampled.
5
+ Resumable: keys already in a shard's jsonl are skipped and finished shards have a ``.done`` marker.
6
+
7
+ python recaption.py run --shards data/*.tar --out out/ [--limit 1000] [--focus]
8
+ python recaption.py stats out/*.jsonl [--sim 500]
9
+ python recaption.py export --src out/ --out hf/recaptions --manifest subset_manifest.json # needs pyarrow
10
+ """
11
+
12
+ import argparse
13
+ import io
14
+ import json
15
+ import os
16
+ import random
17
+ import re
18
+ import tarfile
19
+ import time
20
+ from concurrent.futures import ThreadPoolExecutor
21
+ from pathlib import Path
22
+
23
+ MODEL = "Qwen/Qwen2.5-VL-3B-Instruct"
24
+ MAX_PIXELS = 640 * 28 * 28
25
+ SYSTEM = "You are an image captioner. Describe only what is visible."
26
+ USER = """Describe this image in ONE paragraph of 70–90 words.
27
+ Order: main subject(s) (count, category, color, size, pose/action) → spatial relations (left/right, front/behind, near/far) → background and setting → lighting, viewpoint, and medium (photo, illustration, 3D render, etc.).
28
+ Rules:
29
+ - Start directly with the main subject. Never begin with "The image", "This picture", "In this photo", or similar.
30
+ - State only what is clearly visible. No guesses ("likely", "possibly", "suggesting", "appears to be"), no mood words ("serene", "vibrant", "charming", "picturesque"), no interpretation of purpose or meaning.
31
+ - Quote visible text only if it is legible.
32
+ - No lists, no line breaks, no concluding summary sentence."""
33
+ # --focus: appended to the second caption's prompt only, so the two captions differ in emphasis
34
+ FOCUS = "\nPut extra emphasis on colors, materials, and attributes of each object rather than on the layout."
35
+
36
+ # Decode-time ban of the filtered phrases (the prompt is kept verbatim): without it, Qwen2.5-VL-3B starts ~60% of
37
+ # captions with "The image ..." and uses one of the banned words in ~80%, so resampling alone cannot fix them.
38
+ # Openers go through vLLM bad_words (multi-token, works); words through logit_bias (see ban_bias).
39
+ _SPEC = ("likely", "possibly", "appears", "suggesting", "serene", "vibrant", "charming", "picturesque")
40
+ # beyond the spec list: inflections and the substitutes the model switches to once the spec words are banned
41
+ _EXTRA = ("appear", "appeared", "appearing", "suggest", "suggests", "suggested", "seem", "seems", "seemed", "seemingly",
42
+ "indicating", "indicates", "indicate", "indicated", "indicative", "perhaps", "probably", "might", "possible",
43
+ "tranquil", "peaceful", "idyllic", "cozy", "inviting", "stunning", "breathtaking", "bustling",
44
+ "overall", "atmosphere", "ambiance", "ambience", # summary sentences ("The overall ...") and mood
45
+ # second round, from word counts on the first 177k full-run captions
46
+ "calm", "lively", "festive", "scenic", "striking", "dramatic", "majestic", "grand", "dynamic", "typical",
47
+ "emphasizing", "emphasizes", "emphasize", "emphasized", "enjoy", "enjoys", "enjoying", "welcoming",
48
+ "relaxed", "relaxing", "pleasant", "playful", "harmonious", "elegant", "whimsical", "energetic", "cheerful",
49
+ "celebratory", "celebrating", "intimate", "aesthetic", "iconic", "mood", "moody",
50
+ # third round (fixed after the full run with `fix`): guesses that still leaked
51
+ "potentially", "presumably", "apparently", "supposedly", "hinting", "hints", "implies", "implying",
52
+ "impression")
53
+ # interpretive phrases ("creating a sense of calm"), banned through bad_words like the openers
54
+ _PHRASES = ["creating a", "sense of", "giving a", "giving it", "giving the scene", "giving the image", "adding a",
55
+ "natural beauty", "looks like", "look like", "what looks", "could be", "may be"]
56
+ _WORDS = _SPEC + _EXTRA
57
+ _OPENERS = [f"{a} {b}" for a in ("The", "This", "These") for b in
58
+ ("image", "picture", "photo", "photograph", "scene", "illustration", "snapshot")] + ["In this", "In the image",
59
+ "In the picture", "In the photo"]
60
+ # caption-initial "The"/"This"/"These" (no leading space: a different token from mid-sentence " The"); the model
61
+ # otherwise dodges every banned opener with "The main object in the image is ...", "The mainsubject ...", etc.
62
+ _FIRST = ("The", "This", "These")
63
+
64
+
65
+
66
+ def ban_bias(tokenizer) -> dict[int, float]:
67
+ """logit_bias -100 on every single-token form of _WORDS (" vibrant", "Appear", ...).
68
+
69
+ vLLM's ``bad_words`` cannot ban them: it keeps the space-prefixed form only when it tokenizes to as many tokens
70
+ as the bare word, and e.g. "vibrant" is v|ibr|ant while " vibrant" is one token, so mid-sentence uses pass.
71
+ Rare multi-token forms (sentence-initial "Vibrant") are left to the filter.
72
+ """
73
+ forms = [p + c for x in _WORDS for c in (x, x.capitalize()) for p in ("", " ")]
74
+ ids = [tokenizer.encode(f, add_special_tokens=False) for f in forms]
75
+ ids += [tokenizer.encode(f, add_special_tokens=False) for f in _FIRST]
76
+ return {i[0]: -100.0 for i in ids if len(i) == 1}
77
+
78
+
79
+ _OPENER = re.compile(
80
+ r"^\W*(?:(?:the|this|these)\s+(?:image|picture|photo|photograph|scene|illustration|snapshot)s?\b"
81
+ r"|in\s+(?:this|the)\s+(?:image|picture|photo|photograph|scene|illustration)\b)",
82
+ re.I,
83
+ )
84
+ _OPENER_X = re.compile(r"^\W*the\s+main", re.I)
85
+ _BANNED = re.compile(rf"\b(?:{'|'.join(_SPEC)})\b", re.I)
86
+ _BANNED_X = re.compile(rf"\b(?:{'|'.join(_EXTRA + tuple(_PHRASES))})\b", re.I)
87
+ _LIST = re.compile(r"(?:^|\n)\s*(?:[-*•]|\d+[.)])\s")
88
+ # CJK / kana / Hangul outside quotes: the model drifting into Chinese ("piles of salt结晶"); quoted signage is kept
89
+ _CJK = re.compile(r"[぀-ヿ㐀-䶿一-鿿가-힯]")
90
+ _QUOTED = re.compile(r"\"[^\"]*\"|“[^”]*”|「[^」]*」|'[^']*'")
91
+
92
+
93
+ def cap(text: str, finished: bool = True, max_words: int | None = None) -> str:
94
+ """Drop a cut-off last sentence; with ``max_words``, also keep only the whole sentences that fit."""
95
+ sents = re.split(r"(?<=[.!?])\s+", text.strip())
96
+ if not finished or not sents[-1].endswith((".", "!", "?", '"')):
97
+ sents = sents[:-1]
98
+ out, n = [], 0
99
+ for x in sents:
100
+ n += len(x.split())
101
+ if max_words and n > max_words:
102
+ break
103
+ out.append(x)
104
+ return " ".join(out)
105
+
106
+
107
+ def violations(text: str, finished: bool = True, strict: bool = True) -> list[str]:
108
+ """Reasons a caption is rejected (empty list = accepted); ``strict=False``: the spec rules only."""
109
+ out = []
110
+ if _OPENER.search(text) or strict and _OPENER_X.search(text):
111
+ out.append("opener")
112
+ bare = _QUOTED.sub("", text) # quoted visible text ("Enjoy the simple things") is kept verbatim
113
+ if _BANNED.search(bare) or strict and _BANNED_X.search(bare):
114
+ out.append("banned_word")
115
+ if "\n" in text.strip() or _LIST.search(text):
116
+ out.append("newline_list")
117
+ if _CJK.search(bare):
118
+ out.append("lang_drift")
119
+ if len(text.split()) < 60: # no upper bound: max_tokens=160 keeps it far below BERT's 512 tokens
120
+ out.append("length")
121
+ if not finished:
122
+ out.append("truncated")
123
+ return out
124
+
125
+
126
+ def prompt(focus: bool) -> str:
127
+ return (
128
+ f"<|im_start|>system\n{SYSTEM}<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>"
129
+ f"{USER}{FOCUS if focus else ''}<|im_end|>\n<|im_start|>assistant\n"
130
+ )
131
+
132
+
133
+ def read_shard(path: Path):
134
+ """Yield ``(key, jpg bytes, caption)`` from a webdataset tar (members of a key are adjacent)."""
135
+ cur, parts = None, {}
136
+ with tarfile.open(path, "r|*") as tar:
137
+ for m in tar:
138
+ if not m.isfile():
139
+ continue
140
+ key, ext = m.name.rsplit(".", 1)
141
+ if key != cur:
142
+ if cur is not None and "jpg" in parts:
143
+ yield cur, parts["jpg"], parts.get("txt", b"").decode("utf-8", "replace").strip()
144
+ cur, parts = key, {}
145
+ parts[ext] = tar.extractfile(m).read()
146
+ if cur is not None and "jpg" in parts:
147
+ yield cur, parts["jpg"], parts.get("txt", b"").decode("utf-8", "replace").strip()
148
+
149
+
150
+ def load_image(data: bytes):
151
+ """Decode and shrink to at most MAX_PIXELS so the processor's own resize is cheap."""
152
+ from PIL import Image
153
+
154
+ im = Image.open(io.BytesIO(data))
155
+ if im.width * im.height > 4 * MAX_PIXELS: # JPEG DCT-domain downscale, much faster than a full decode
156
+ im.draft("RGB", (im.width // 2, im.height // 2))
157
+ im = im.convert("RGB")
158
+ s = (MAX_PIXELS / (im.width * im.height)) ** 0.5
159
+ if s < 1:
160
+ im = im.resize((max(28, round(im.width * s)), max(28, round(im.height * s))), Image.BICUBIC)
161
+ return im
162
+
163
+
164
+ def claim(out: Path, shard: Path) -> bool:
165
+ if (out / f"{shard.stem}.done").exists():
166
+ return False
167
+ try:
168
+ os.close(os.open(out / f"{shard.stem}.lock", os.O_CREAT | os.O_EXCL))
169
+ return True
170
+ except FileExistsError:
171
+ return False
172
+
173
+
174
+ def _patch_bad_words() -> None:
175
+ """Ban both the bare and the space-prefixed token sequence of every bad word.
176
+
177
+ vLLM keeps the space-prefixed variant only when it has as many tokens as the bare word, so mid-sentence
178
+ " giving a" (bare g|iving| a) or " whimsical" (bare wh|ims|ical) were never banned. The bad_words kernel itself
179
+ handles any token sequence; only this expansion (run in the frontend process) is replaced.
180
+ """
181
+ from vllm import SamplingParams
182
+
183
+ def update_from_tokenizer(self, tokenizer) -> None:
184
+ if not self.bad_words:
185
+ return
186
+ ids = []
187
+ for w in self.bad_words:
188
+ for prefix in ("", " "):
189
+ t = tokenizer.encode(prefix + w.lstrip(), add_special_tokens=False)
190
+ if t and t not in ids:
191
+ ids.append(t)
192
+ self._bad_words_token_ids = ids
193
+
194
+ SamplingParams.update_from_tokenizer = update_from_tokenizer
195
+
196
+
197
+ def engine(args):
198
+ os.environ.setdefault("VLLM_MAX_NUM_BAD_WORDS", "1024") # ~400 sequences with every word form
199
+ os.environ.setdefault("VLLM_MAX_BAD_WORDS_TOTAL_TOKENS", "4096")
200
+ from vllm import LLM, SamplingParams
201
+
202
+ _patch_bad_words()
203
+
204
+ llm = LLM(
205
+ model=args.model,
206
+ max_model_len=2048,
207
+ gpu_memory_utilization=args.gpu_mem,
208
+ enable_prefix_caching=True,
209
+ limit_mm_per_prompt={"image": 1},
210
+ mm_processor_kwargs={"max_pixels": MAX_PIXELS},
211
+ seed=args.seed,
212
+ )
213
+ words = [c for x in _WORDS for c in (x, x.capitalize())] # multi-token forms; logit_bias covers single tokens
214
+ ban = {"bad_words": _OPENERS + _PHRASES + words, "logit_bias": ban_bias(llm.get_tokenizer())}
215
+ ban = {} if args.no_ban else ban
216
+ sp = lambda n: SamplingParams(n=n, temperature=0.8, top_p=0.9, max_tokens=160, **ban) # noqa: E731
217
+ return llm, sp
218
+
219
+
220
+ def run(args):
221
+ out = Path(args.out)
222
+ out.mkdir(parents=True, exist_ok=True)
223
+ llm, sp = engine(args)
224
+ pool = ThreadPoolExecutor(args.workers)
225
+ rank = os.environ.get("CUDA_VISIBLE_DEVICES", "0")
226
+
227
+ for shard in map(Path, args.shards):
228
+ if not claim(out, shard):
229
+ continue
230
+ dst = out / f"{shard.stem}.jsonl"
231
+ seen = {json.loads(l)["key"] for l in open(dst)} if dst.exists() else set()
232
+ stats = {"images": 0, "samples": 0, "rejected": 0, "reasons": {}, "fallback": [], "gen_s": 0.0}
233
+ sp_path = out / f"{shard.stem}.stats.json"
234
+ if sp_path.exists() and seen:
235
+ stats = json.load(open(sp_path))
236
+ t0, done = time.time(), len(seen)
237
+ items = ((k, j, c) for k, j, c in read_shard(shard) if k not in seen)
238
+ with open(dst, "a") as f:
239
+ while True:
240
+ chunk = [x for _, x in zip(range(args.chunk), items)]
241
+ if args.limit:
242
+ chunk = chunk[: max(0, args.limit - done)]
243
+ if not chunk:
244
+ break
245
+ imgs = list(pool.map(lambda x: load_image(x[1]), chunk))
246
+ tg = time.time()
247
+ rows = recaption(llm, sp, imgs, args.focus, args.retries, stats)
248
+ stats["gen_s"] += time.time() - tg
249
+ for (key, _, cap), (r1, r2, ok) in zip(chunk, rows):
250
+ f.write(json.dumps({"key": key, "source_shard": shard.name, "orig_caption": cap,
251
+ "recap_1": r1, "recap_2": r2}) + "\n")
252
+ if not ok:
253
+ stats["fallback"].append(key)
254
+ f.flush()
255
+ done += len(chunk)
256
+ stats["images"] = done
257
+ json.dump(stats, open(sp_path, "w"))
258
+ print(f"[gpu{rank}] {shard.name} {done} imgs {len(chunk) / (time.time() - tg + 1e-9):.1f} img/s "
259
+ f"(chunk) rej {stats['rejected'] / max(1, stats['samples']):.3f}", flush=True)
260
+ if args.limit and done >= args.limit:
261
+ break
262
+ stats["wall_s"] = stats.get("wall_s", 0) + time.time() - t0
263
+ json.dump(stats, open(sp_path, "w"))
264
+ if not args.limit:
265
+ (out / f"{shard.stem}.done").touch()
266
+ (out / f"{shard.stem}.lock").unlink(missing_ok=True)
267
+
268
+
269
+ def recaption(llm, sp, imgs, focus, retries, stats, todo=None):
270
+ """Two accepted captions per image; resample rejected ones up to ``retries`` times, then keep the best.
271
+
272
+ ``todo``: the ``(image, slot)`` pairs to generate (default: both slots of every image); others come back None.
273
+ """
274
+ good = [[[], []] for _ in imgs] # per image, per slot (recap_1 / recap_2): accepted texts
275
+ best = [[None, None] for _ in imgs] # fallback: (n violations, text) with fewest violations
276
+ # slot 0 and slot 1 share the same prompt unless --focus, in which case slot 1 gets the FOCUS sentence
277
+ todo = todo or [(i, s) for i in range(len(imgs)) for s in (0, 1)]
278
+ asked = set(todo)
279
+ for attempt in range(retries + 1):
280
+ if not todo:
281
+ break
282
+ reqs, owners = [], []
283
+ if focus:
284
+ for i, s in todo:
285
+ reqs.append(({"prompt": prompt(s == 1), "multi_modal_data": {"image": imgs[i]}}, 1))
286
+ owners.append([(i, s)])
287
+ else: # one request per image with n = number of missing slots, so both samples share the prefill
288
+ by_img = {}
289
+ for i, s in todo:
290
+ by_img.setdefault(i, []).append(s)
291
+ for i, slots in by_img.items():
292
+ reqs.append(({"prompt": prompt(False), "multi_modal_data": {"image": imgs[i]}}, len(slots)))
293
+ owners.append([(i, s) for s in slots])
294
+ by_n = {}
295
+ for k, (_, n) in enumerate(reqs):
296
+ by_n.setdefault(n, []).append(k)
297
+ outs = [None] * len(reqs)
298
+ for n, ks in by_n.items():
299
+ for k, o in zip(ks, llm.generate([reqs[k][0] for k in ks], sp(n), use_tqdm=False)):
300
+ outs[k] = o
301
+ todo = []
302
+ for o, own in zip(outs, owners):
303
+ for c, (i, s) in zip(o.outputs, own):
304
+ raw = c.text.strip()
305
+ text = cap(raw, c.finish_reason == "stop") # cut off at max_tokens: drop the partial sentence
306
+ stats["capped"] = stats.get("capped", 0) + (text != raw)
307
+ v = violations(text)
308
+ stats["samples"] += 1
309
+ if v:
310
+ stats["rejected"] += 1
311
+ for r in v:
312
+ stats["reasons"][r] = stats["reasons"].get(r, 0) + 1
313
+ if best[i][s] is None or len(v) < best[i][s][0]:
314
+ best[i][s] = (len(v), text)
315
+ todo.append((i, s))
316
+ else:
317
+ good[i][s].append(text)
318
+ rows = []
319
+ for i in range(len(imgs)):
320
+ r = [None if (i, s) not in asked else good[i][s][0] if good[i][s] else best[i][s][1] for s in (0, 1)]
321
+ rows.append((r[0], r[1], all(good[i][s] for s in (0, 1) if (i, s) in asked)))
322
+ return rows
323
+
324
+
325
+ def fix(args):
326
+ """Regenerate, in finished shards, only the captions that violate the current rules (one slot at a time).
327
+
328
+ Each shard's jsonl is rewritten atomically and marked ``.fixed``; workers claim shards like ``run``.
329
+ """
330
+ out = Path(args.out)
331
+ llm, sp = engine(args)
332
+ pool = ThreadPoolExecutor(args.workers)
333
+ rank = os.environ.get("CUDA_VISIBLE_DEVICES", "0")
334
+ for shard in map(Path, args.shards):
335
+ stem = shard.stem
336
+ if not (out / f"{stem}.done").exists() or (out / f"{stem}.fixed").exists():
337
+ continue
338
+ try: # own lock name: ``claim`` skips shards that are already .done
339
+ os.close(os.open(out / f"{stem}.fixlock", os.O_CREAT | os.O_EXCL))
340
+ except FileExistsError:
341
+ continue
342
+ if (out / f"{stem}.fixed").exists(): # finished by another worker between the check and the claim
343
+ (out / f"{stem}.fixlock").unlink(missing_ok=True)
344
+ continue
345
+ rows = [json.loads(l) for l in open(out / f"{stem}.jsonl")]
346
+ bad = {r["key"]: [s for s in (0, 1) if violations(r[f"recap_{s + 1}"])] for r in rows}
347
+ bad = {k: v for k, v in bad.items() if v}
348
+ st = {"images": len(bad), "slots": sum(map(len, bad.values())), "samples": 0, "rejected": 0, "reasons": {},
349
+ "fallback": []}
350
+ items = [(k, j) for k, j, _ in read_shard(shard) if k in bad]
351
+ new, t0 = {}, time.time()
352
+ for c in range(0, len(items), args.chunk):
353
+ chunk = items[c : c + args.chunk]
354
+ imgs = list(pool.map(lambda x: load_image(x[1]), chunk))
355
+ todo = [(i, s) for i, (k, _) in enumerate(chunk) for s in bad[k]]
356
+ for (k, _), (r1, r2, ok) in zip(chunk, recaption(llm, sp, imgs, False, args.retries, st, todo)):
357
+ new[k] = (r1, r2)
358
+ if not ok:
359
+ st["fallback"].append(k)
360
+ tmp = out / f"{stem}.jsonl.tmp"
361
+ with open(tmp, "w") as f:
362
+ for r in rows:
363
+ for s, t in enumerate(new.get(r["key"], (None, None))):
364
+ if t is not None:
365
+ r[f"recap_{s + 1}"] = t
366
+ f.write(json.dumps(r) + "\n")
367
+ os.replace(tmp, out / f"{stem}.jsonl")
368
+ sj = out / f"{stem}.stats.json"
369
+ allst = json.load(open(sj))
370
+ allst["fix"] = st
371
+ json.dump(allst, open(sj, "w"))
372
+ (out / f"{stem}.fixed").touch()
373
+ (out / f"{stem}.fixlock").unlink(missing_ok=True)
374
+ print(f"[gpu{rank}] fixed {stem}: {st['slots']} captions of {st['images']} images in "
375
+ f"{time.time() - t0:.0f}s, still violating {len(st['fallback'])}", flush=True)
376
+
377
+
378
+ def _ngrams(t: str, n: int = 2) -> set:
379
+ w = re.findall(r"\w+", t.lower())
380
+ return {tuple(w[i : i + n]) for i in range(len(w) - n + 1)}
381
+
382
+
383
+ def _lcs(a: list, b: list) -> int:
384
+ prev = [0] * (len(b) + 1)
385
+ for x in a:
386
+ cur = [0]
387
+ for j, y in enumerate(b):
388
+ cur.append(prev[j] + 1 if x == y else max(prev[j + 1], cur[j]))
389
+ prev = cur
390
+ return prev[-1]
391
+
392
+
393
+ def similarity(a: str, b: str) -> dict:
394
+ """Bigram Jaccard and ROUGE-L F1 between two captions."""
395
+ ga, gb = _ngrams(a), _ngrams(b)
396
+ wa, wb = re.findall(r"\w+", a.lower()), re.findall(r"\w+", b.lower())
397
+ l = _lcs(wa, wb)
398
+ return {"jaccard2": len(ga & gb) / max(1, len(ga | gb)), "rougeL": 2 * l / max(1, len(wa) + len(wb))}
399
+
400
+
401
+ def stats(args):
402
+ rows = [json.loads(l) for p in args.files for l in open(p)]
403
+ agg = {"images": 0, "samples": 0, "rejected": 0, "reasons": {}, "fallback": 0, "gen_s": 0.0, "wall_s": 0.0}
404
+ for p in args.files:
405
+ s = json.load(open(Path(p).with_suffix(".stats.json")))
406
+ for k in ("images", "samples", "rejected", "gen_s", "wall_s"):
407
+ agg[k] += s.get(k, 0)
408
+ agg["fallback"] += len(s["fallback"])
409
+ for r, c in s["reasons"].items():
410
+ agg["reasons"][r] = agg["reasons"].get(r, 0) + c
411
+ first = 2 * agg["images"] # first-pass samples
412
+ print(json.dumps(agg, indent=1))
413
+ print(f"img/s (generation only) {agg['images'] / agg['gen_s']:.2f}, (wall) {agg['images'] / agg['wall_s']:.2f}")
414
+ print(f"rejected / all samples {agg['rejected'] / agg['samples']:.3f}; resample overhead "
415
+ f"{agg['samples'] / first - 1:.3f}; images with a fallback caption {agg['fallback'] / agg['images']:.4f}")
416
+ for strict in (False, True):
417
+ final = [violations(r[k], strict=strict) for r in rows for k in ("recap_1", "recap_2")]
418
+ print(f"final captions still violating ({'extended' if strict else 'spec'} rules) "
419
+ f"{sum(map(bool, final)) / len(final):.4f}")
420
+ wc = sorted(len(r[k].split()) for r in rows for k in ("recap_1", "recap_2"))
421
+ print(f"words: p5 {wc[len(wc) // 20]} median {wc[len(wc) // 2]} p95 {wc[19 * len(wc) // 20]}")
422
+ rng = random.Random(0)
423
+ sub = rng.sample(rows, min(args.sim, len(rows)))
424
+ pair = [similarity(r["recap_1"], r["recap_2"]) for r in sub]
425
+ other = [similarity(r["recap_1"], rng.choice(rows)["recap_2"]) for r in sub] # different images: floor
426
+ orig = [similarity(r["recap_1"], r["orig_caption"]) for r in sub]
427
+ for name, s in (("recap_1 vs recap_2 (same image)", pair), ("recap_1 vs orig (same image)", orig),
428
+ ("recap_1 vs recap_2 (random image)", other)):
429
+ print(f"{name}: " + ", ".join(f"{k} {sum(x[k] for x in s) / len(s):.3f}" for k in s[0]))
430
+
431
+
432
+ def export(args):
433
+ """One parquet per shard (tar order, keys unique), row counts checked against the subset manifest."""
434
+ import pyarrow as pa
435
+ import pyarrow.parquet as pq
436
+
437
+ src, out = Path(args.src), Path(args.out)
438
+ out.mkdir(parents=True, exist_ok=True)
439
+ cols = ("key", "source_shard", "orig_caption", "recap_1", "recap_2")
440
+ total = 0
441
+ for sh in json.load(open(args.manifest))["shards"]:
442
+ stem = Path(sh["file"]).stem
443
+ assert (src / f"{stem}.done").exists(), f"{stem} not finished"
444
+ rows, seen = [], set()
445
+ for line in open(src / f"{stem}.jsonl"):
446
+ try:
447
+ r = json.loads(line)
448
+ except json.JSONDecodeError: # a line cut by a killed worker
449
+ continue
450
+ if r["key"] not in seen:
451
+ seen.add(r["key"])
452
+ rows.append(r)
453
+ assert len(rows) == sh["pairs"], f"{stem}: {len(rows)} rows, manifest {sh['pairs']}"
454
+ pq.write_table(pa.table({c: [r[c] for r in rows] for c in cols}), out / f"{stem}.parquet", compression="zstd")
455
+ total += len(rows)
456
+ print(f"{total} rows -> {out}")
457
+
458
+
459
+ if __name__ == "__main__":
460
+ ap = argparse.ArgumentParser()
461
+ sub = ap.add_subparsers(dest="cmd", required=True)
462
+ r = sub.add_parser("run")
463
+ r.add_argument("--shards", nargs="+", required=True)
464
+ r.add_argument("--out", required=True)
465
+ r.add_argument("--model", default=MODEL)
466
+ r.add_argument("--limit", type=int, default=0, help="images per shard (test runs; no .done marker)")
467
+ r.add_argument("--chunk", type=int, default=1024)
468
+ r.add_argument("--no-ban", action="store_true", help="no decode-time bans (filter + resample only)")
469
+ r.add_argument("--retries", type=int, default=3)
470
+ r.add_argument("--focus", action="store_true", help="add the FOCUS sentence to the second caption's prompt")
471
+ r.add_argument("--gpu-mem", type=float, default=0.85)
472
+ r.add_argument("--workers", type=int, default=16)
473
+ r.add_argument("--seed", type=int, default=0)
474
+ x = sub.add_parser("fix", help="regenerate only the captions that violate the current rules")
475
+ x.add_argument("--shards", nargs="+", required=True)
476
+ x.add_argument("--out", required=True)
477
+ x.add_argument("--model", default=MODEL)
478
+ x.add_argument("--chunk", type=int, default=1024)
479
+ x.add_argument("--retries", type=int, default=3)
480
+ x.add_argument("--gpu-mem", type=float, default=0.85)
481
+ x.add_argument("--workers", type=int, default=16)
482
+ x.add_argument("--seed", type=int, default=0)
483
+ x.add_argument("--no-ban", action="store_true")
484
+ s = sub.add_parser("stats")
485
+ s.add_argument("files", nargs="+")
486
+ s.add_argument("--sim", type=int, default=500)
487
+ e = sub.add_parser("export")
488
+ e.add_argument("--src", required=True)
489
+ e.add_argument("--out", required=True)
490
+ e.add_argument("--manifest", required=True)
491
+ a = ap.parse_args()
492
+ {"run": run, "fix": fix, "stats": stats, "export": export}[a.cmd](a)