File size: 24,379 Bytes
3d5feb7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
"""Recaption BLIP3o-Recap webdataset shards with Qwen2.5-VL-3B-Instruct (vLLM, one process per GPU).

Each image keeps its original caption and gets two new ones; one jsonl per shard with
``{key, source_shard, orig_caption, recap_1, recap_2}``. Rejected samples (see ``violations``) are resampled.
Resumable: keys already in a shard's jsonl are skipped and finished shards have a ``.done`` marker.

    python recaption.py run --shards data/*.tar --out out/ [--limit 1000] [--focus]
    python recaption.py stats out/*.jsonl [--sim 500]
    python recaption.py export --src out/ --out hf/recaptions --manifest subset_manifest.json   # needs pyarrow
"""

import argparse
import io
import json
import os
import random
import re
import tarfile
import time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

MODEL = "Qwen/Qwen2.5-VL-3B-Instruct"
MAX_PIXELS = 640 * 28 * 28
SYSTEM = "You are an image captioner. Describe only what is visible."
USER = """Describe this image in ONE paragraph of 70–90 words.
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.).
Rules:
- Start directly with the main subject. Never begin with "The image", "This picture", "In this photo", or similar.
- 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.
- Quote visible text only if it is legible.
- No lists, no line breaks, no concluding summary sentence."""
# --focus: appended to the second caption's prompt only, so the two captions differ in emphasis
FOCUS = "\nPut extra emphasis on colors, materials, and attributes of each object rather than on the layout."

# Decode-time ban of the filtered phrases (the prompt is kept verbatim): without it, Qwen2.5-VL-3B starts ~60% of
# captions with "The image ..." and uses one of the banned words in ~80%, so resampling alone cannot fix them.
# Openers go through vLLM bad_words (multi-token, works); words through logit_bias (see ban_bias).
_SPEC = ("likely", "possibly", "appears", "suggesting", "serene", "vibrant", "charming", "picturesque")
# beyond the spec list: inflections and the substitutes the model switches to once the spec words are banned
_EXTRA = ("appear", "appeared", "appearing", "suggest", "suggests", "suggested", "seem", "seems", "seemed", "seemingly",
          "indicating", "indicates", "indicate", "indicated", "indicative", "perhaps", "probably", "might", "possible",
          "tranquil", "peaceful", "idyllic", "cozy", "inviting", "stunning", "breathtaking", "bustling",
          "overall", "atmosphere", "ambiance", "ambience",  # summary sentences ("The overall ...") and mood
          # second round, from word counts on the first 177k full-run captions
          "calm", "lively", "festive", "scenic", "striking", "dramatic", "majestic", "grand", "dynamic", "typical",
          "emphasizing", "emphasizes", "emphasize", "emphasized", "enjoy", "enjoys", "enjoying", "welcoming",
          "relaxed", "relaxing", "pleasant", "playful", "harmonious", "elegant", "whimsical", "energetic", "cheerful",
          "celebratory", "celebrating", "intimate", "aesthetic", "iconic", "mood", "moody",
          # third round (fixed after the full run with `fix`): guesses that still leaked
          "potentially", "presumably", "apparently", "supposedly", "hinting", "hints", "implies", "implying",
          "impression")
# interpretive phrases ("creating a sense of calm"), banned through bad_words like the openers
_PHRASES = ["creating a", "sense of", "giving a", "giving it", "giving the scene", "giving the image", "adding a",
            "natural beauty", "looks like", "look like", "what looks", "could be", "may be"]
_WORDS = _SPEC + _EXTRA
_OPENERS = [f"{a} {b}" for a in ("The", "This", "These") for b in
            ("image", "picture", "photo", "photograph", "scene", "illustration", "snapshot")] + ["In this", "In the image",
            "In the picture", "In the photo"]
# caption-initial "The"/"This"/"These" (no leading space: a different token from mid-sentence " The"); the model
# otherwise dodges every banned opener with "The main object in the image is ...", "The mainsubject ...", etc.
_FIRST = ("The", "This", "These")



def ban_bias(tokenizer) -> dict[int, float]:
    """logit_bias -100 on every single-token form of _WORDS (" vibrant", "Appear", ...).

    vLLM's ``bad_words`` cannot ban them: it keeps the space-prefixed form only when it tokenizes to as many tokens
    as the bare word, and e.g. "vibrant" is v|ibr|ant while " vibrant" is one token, so mid-sentence uses pass.
    Rare multi-token forms (sentence-initial "Vibrant") are left to the filter.
    """
    forms = [p + c for x in _WORDS for c in (x, x.capitalize()) for p in ("", " ")]
    ids = [tokenizer.encode(f, add_special_tokens=False) for f in forms]
    ids += [tokenizer.encode(f, add_special_tokens=False) for f in _FIRST]
    return {i[0]: -100.0 for i in ids if len(i) == 1}


_OPENER = re.compile(
    r"^\W*(?:(?:the|this|these)\s+(?:image|picture|photo|photograph|scene|illustration|snapshot)s?\b"
    r"|in\s+(?:this|the)\s+(?:image|picture|photo|photograph|scene|illustration)\b)",
    re.I,
)
_OPENER_X = re.compile(r"^\W*the\s+main", re.I)
_BANNED = re.compile(rf"\b(?:{'|'.join(_SPEC)})\b", re.I)
_BANNED_X = re.compile(rf"\b(?:{'|'.join(_EXTRA + tuple(_PHRASES))})\b", re.I)
_LIST = re.compile(r"(?:^|\n)\s*(?:[-*•]|\d+[.)])\s")
# CJK / kana / Hangul outside quotes: the model drifting into Chinese ("piles of salt结晶"); quoted signage is kept
_CJK = re.compile(r"[぀-ヿ㐀-䶿一-鿿가-힯]")
_QUOTED = re.compile(r"\"[^\"]*\"|“[^”]*”|「[^」]*」|'[^']*'")


def cap(text: str, finished: bool = True, max_words: int | None = None) -> str:
    """Drop a cut-off last sentence; with ``max_words``, also keep only the whole sentences that fit."""
    sents = re.split(r"(?<=[.!?])\s+", text.strip())
    if not finished or not sents[-1].endswith((".", "!", "?", '"')):
        sents = sents[:-1]
    out, n = [], 0
    for x in sents:
        n += len(x.split())
        if max_words and n > max_words:
            break
        out.append(x)
    return " ".join(out)


def violations(text: str, finished: bool = True, strict: bool = True) -> list[str]:
    """Reasons a caption is rejected (empty list = accepted); ``strict=False``: the spec rules only."""
    out = []
    if _OPENER.search(text) or strict and _OPENER_X.search(text):
        out.append("opener")
    bare = _QUOTED.sub("", text)  # quoted visible text ("Enjoy the simple things") is kept verbatim
    if _BANNED.search(bare) or strict and _BANNED_X.search(bare):
        out.append("banned_word")
    if "\n" in text.strip() or _LIST.search(text):
        out.append("newline_list")
    if _CJK.search(bare):
        out.append("lang_drift")
    if len(text.split()) < 60:  # no upper bound: max_tokens=160 keeps it far below BERT's 512 tokens
        out.append("length")
    if not finished:
        out.append("truncated")
    return out


def prompt(focus: bool) -> str:
    return (
        f"<|im_start|>system\n{SYSTEM}<|im_end|>\n<|im_start|>user\n<|vision_start|><|image_pad|><|vision_end|>"
        f"{USER}{FOCUS if focus else ''}<|im_end|>\n<|im_start|>assistant\n"
    )


def read_shard(path: Path):
    """Yield ``(key, jpg bytes, caption)`` from a webdataset tar (members of a key are adjacent)."""
    cur, parts = None, {}
    with tarfile.open(path, "r|*") as tar:
        for m in tar:
            if not m.isfile():
                continue
            key, ext = m.name.rsplit(".", 1)
            if key != cur:
                if cur is not None and "jpg" in parts:
                    yield cur, parts["jpg"], parts.get("txt", b"").decode("utf-8", "replace").strip()
                cur, parts = key, {}
            parts[ext] = tar.extractfile(m).read()
    if cur is not None and "jpg" in parts:
        yield cur, parts["jpg"], parts.get("txt", b"").decode("utf-8", "replace").strip()


def load_image(data: bytes):
    """Decode and shrink to at most MAX_PIXELS so the processor's own resize is cheap."""
    from PIL import Image

    im = Image.open(io.BytesIO(data))
    if im.width * im.height > 4 * MAX_PIXELS:  # JPEG DCT-domain downscale, much faster than a full decode
        im.draft("RGB", (im.width // 2, im.height // 2))
    im = im.convert("RGB")
    s = (MAX_PIXELS / (im.width * im.height)) ** 0.5
    if s < 1:
        im = im.resize((max(28, round(im.width * s)), max(28, round(im.height * s))), Image.BICUBIC)
    return im


def claim(out: Path, shard: Path) -> bool:
    if (out / f"{shard.stem}.done").exists():
        return False
    try:
        os.close(os.open(out / f"{shard.stem}.lock", os.O_CREAT | os.O_EXCL))
        return True
    except FileExistsError:
        return False


def _patch_bad_words() -> None:
    """Ban both the bare and the space-prefixed token sequence of every bad word.

    vLLM keeps the space-prefixed variant only when it has as many tokens as the bare word, so mid-sentence
    " giving a" (bare g|iving| a) or " whimsical" (bare wh|ims|ical) were never banned. The bad_words kernel itself
    handles any token sequence; only this expansion (run in the frontend process) is replaced.
    """
    from vllm import SamplingParams

    def update_from_tokenizer(self, tokenizer) -> None:
        if not self.bad_words:
            return
        ids = []
        for w in self.bad_words:
            for prefix in ("", " "):
                t = tokenizer.encode(prefix + w.lstrip(), add_special_tokens=False)
                if t and t not in ids:
                    ids.append(t)
        self._bad_words_token_ids = ids

    SamplingParams.update_from_tokenizer = update_from_tokenizer


def engine(args):
    os.environ.setdefault("VLLM_MAX_NUM_BAD_WORDS", "1024")  # ~400 sequences with every word form
    os.environ.setdefault("VLLM_MAX_BAD_WORDS_TOTAL_TOKENS", "4096")
    from vllm import LLM, SamplingParams

    _patch_bad_words()

    llm = LLM(
        model=args.model,
        max_model_len=2048,
        gpu_memory_utilization=args.gpu_mem,
        enable_prefix_caching=True,
        limit_mm_per_prompt={"image": 1},
        mm_processor_kwargs={"max_pixels": MAX_PIXELS},
        seed=args.seed,
    )
    words = [c for x in _WORDS for c in (x, x.capitalize())]  # multi-token forms; logit_bias covers single tokens
    ban = {"bad_words": _OPENERS + _PHRASES + words, "logit_bias": ban_bias(llm.get_tokenizer())}
    ban = {} if args.no_ban else ban
    sp = lambda n: SamplingParams(n=n, temperature=0.8, top_p=0.9, max_tokens=160, **ban)  # noqa: E731
    return llm, sp


def run(args):
    out = Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    llm, sp = engine(args)
    pool = ThreadPoolExecutor(args.workers)
    rank = os.environ.get("CUDA_VISIBLE_DEVICES", "0")

    for shard in map(Path, args.shards):
        if not claim(out, shard):
            continue
        dst = out / f"{shard.stem}.jsonl"
        seen = {json.loads(l)["key"] for l in open(dst)} if dst.exists() else set()
        stats = {"images": 0, "samples": 0, "rejected": 0, "reasons": {}, "fallback": [], "gen_s": 0.0}
        sp_path = out / f"{shard.stem}.stats.json"
        if sp_path.exists() and seen:
            stats = json.load(open(sp_path))
        t0, done = time.time(), len(seen)
        items = ((k, j, c) for k, j, c in read_shard(shard) if k not in seen)
        with open(dst, "a") as f:
            while True:
                chunk = [x for _, x in zip(range(args.chunk), items)]
                if args.limit:
                    chunk = chunk[: max(0, args.limit - done)]
                if not chunk:
                    break
                imgs = list(pool.map(lambda x: load_image(x[1]), chunk))
                tg = time.time()
                rows = recaption(llm, sp, imgs, args.focus, args.retries, stats)
                stats["gen_s"] += time.time() - tg
                for (key, _, cap), (r1, r2, ok) in zip(chunk, rows):
                    f.write(json.dumps({"key": key, "source_shard": shard.name, "orig_caption": cap,
                                        "recap_1": r1, "recap_2": r2}) + "\n")
                    if not ok:
                        stats["fallback"].append(key)
                f.flush()
                done += len(chunk)
                stats["images"] = done
                json.dump(stats, open(sp_path, "w"))
                print(f"[gpu{rank}] {shard.name} {done} imgs {len(chunk) / (time.time() - tg + 1e-9):.1f} img/s "
                      f"(chunk) rej {stats['rejected'] / max(1, stats['samples']):.3f}", flush=True)
                if args.limit and done >= args.limit:
                    break
        stats["wall_s"] = stats.get("wall_s", 0) + time.time() - t0
        json.dump(stats, open(sp_path, "w"))
        if not args.limit:
            (out / f"{shard.stem}.done").touch()
        (out / f"{shard.stem}.lock").unlink(missing_ok=True)


def recaption(llm, sp, imgs, focus, retries, stats, todo=None):
    """Two accepted captions per image; resample rejected ones up to ``retries`` times, then keep the best.

    ``todo``: the ``(image, slot)`` pairs to generate (default: both slots of every image); others come back None.
    """
    good = [[[], []] for _ in imgs]  # per image, per slot (recap_1 / recap_2): accepted texts
    best = [[None, None] for _ in imgs]  # fallback: (n violations, text) with fewest violations
    # slot 0 and slot 1 share the same prompt unless --focus, in which case slot 1 gets the FOCUS sentence
    todo = todo or [(i, s) for i in range(len(imgs)) for s in (0, 1)]
    asked = set(todo)
    for attempt in range(retries + 1):
        if not todo:
            break
        reqs, owners = [], []
        if focus:
            for i, s in todo:
                reqs.append(({"prompt": prompt(s == 1), "multi_modal_data": {"image": imgs[i]}}, 1))
                owners.append([(i, s)])
        else:  # one request per image with n = number of missing slots, so both samples share the prefill
            by_img = {}
            for i, s in todo:
                by_img.setdefault(i, []).append(s)
            for i, slots in by_img.items():
                reqs.append(({"prompt": prompt(False), "multi_modal_data": {"image": imgs[i]}}, len(slots)))
                owners.append([(i, s) for s in slots])
        by_n = {}
        for k, (_, n) in enumerate(reqs):
            by_n.setdefault(n, []).append(k)
        outs = [None] * len(reqs)
        for n, ks in by_n.items():
            for k, o in zip(ks, llm.generate([reqs[k][0] for k in ks], sp(n), use_tqdm=False)):
                outs[k] = o
        todo = []
        for o, own in zip(outs, owners):
            for c, (i, s) in zip(o.outputs, own):
                raw = c.text.strip()
                text = cap(raw, c.finish_reason == "stop")  # cut off at max_tokens: drop the partial sentence
                stats["capped"] = stats.get("capped", 0) + (text != raw)
                v = violations(text)
                stats["samples"] += 1
                if v:
                    stats["rejected"] += 1
                    for r in v:
                        stats["reasons"][r] = stats["reasons"].get(r, 0) + 1
                    if best[i][s] is None or len(v) < best[i][s][0]:
                        best[i][s] = (len(v), text)
                    todo.append((i, s))
                else:
                    good[i][s].append(text)
    rows = []
    for i in range(len(imgs)):
        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)]
        rows.append((r[0], r[1], all(good[i][s] for s in (0, 1) if (i, s) in asked)))
    return rows


def fix(args):
    """Regenerate, in finished shards, only the captions that violate the current rules (one slot at a time).

    Each shard's jsonl is rewritten atomically and marked ``.fixed``; workers claim shards like ``run``.
    """
    out = Path(args.out)
    llm, sp = engine(args)
    pool = ThreadPoolExecutor(args.workers)
    rank = os.environ.get("CUDA_VISIBLE_DEVICES", "0")
    for shard in map(Path, args.shards):
        stem = shard.stem
        if not (out / f"{stem}.done").exists() or (out / f"{stem}.fixed").exists():
            continue
        try:  # own lock name: ``claim`` skips shards that are already .done
            os.close(os.open(out / f"{stem}.fixlock", os.O_CREAT | os.O_EXCL))
        except FileExistsError:
            continue
        if (out / f"{stem}.fixed").exists():  # finished by another worker between the check and the claim
            (out / f"{stem}.fixlock").unlink(missing_ok=True)
            continue
        rows = [json.loads(l) for l in open(out / f"{stem}.jsonl")]
        bad = {r["key"]: [s for s in (0, 1) if violations(r[f"recap_{s + 1}"])] for r in rows}
        bad = {k: v for k, v in bad.items() if v}
        st = {"images": len(bad), "slots": sum(map(len, bad.values())), "samples": 0, "rejected": 0, "reasons": {},
              "fallback": []}
        items = [(k, j) for k, j, _ in read_shard(shard) if k in bad]
        new, t0 = {}, time.time()
        for c in range(0, len(items), args.chunk):
            chunk = items[c : c + args.chunk]
            imgs = list(pool.map(lambda x: load_image(x[1]), chunk))
            todo = [(i, s) for i, (k, _) in enumerate(chunk) for s in bad[k]]
            for (k, _), (r1, r2, ok) in zip(chunk, recaption(llm, sp, imgs, False, args.retries, st, todo)):
                new[k] = (r1, r2)
                if not ok:
                    st["fallback"].append(k)
        tmp = out / f"{stem}.jsonl.tmp"
        with open(tmp, "w") as f:
            for r in rows:
                for s, t in enumerate(new.get(r["key"], (None, None))):
                    if t is not None:
                        r[f"recap_{s + 1}"] = t
                f.write(json.dumps(r) + "\n")
        os.replace(tmp, out / f"{stem}.jsonl")
        sj = out / f"{stem}.stats.json"
        allst = json.load(open(sj))
        allst["fix"] = st
        json.dump(allst, open(sj, "w"))
        (out / f"{stem}.fixed").touch()
        (out / f"{stem}.fixlock").unlink(missing_ok=True)
        print(f"[gpu{rank}] fixed {stem}: {st['slots']} captions of {st['images']} images in "
              f"{time.time() - t0:.0f}s, still violating {len(st['fallback'])}", flush=True)


def _ngrams(t: str, n: int = 2) -> set:
    w = re.findall(r"\w+", t.lower())
    return {tuple(w[i : i + n]) for i in range(len(w) - n + 1)}


def _lcs(a: list, b: list) -> int:
    prev = [0] * (len(b) + 1)
    for x in a:
        cur = [0]
        for j, y in enumerate(b):
            cur.append(prev[j] + 1 if x == y else max(prev[j + 1], cur[j]))
        prev = cur
    return prev[-1]


def similarity(a: str, b: str) -> dict:
    """Bigram Jaccard and ROUGE-L F1 between two captions."""
    ga, gb = _ngrams(a), _ngrams(b)
    wa, wb = re.findall(r"\w+", a.lower()), re.findall(r"\w+", b.lower())
    l = _lcs(wa, wb)
    return {"jaccard2": len(ga & gb) / max(1, len(ga | gb)), "rougeL": 2 * l / max(1, len(wa) + len(wb))}


def stats(args):
    rows = [json.loads(l) for p in args.files for l in open(p)]
    agg = {"images": 0, "samples": 0, "rejected": 0, "reasons": {}, "fallback": 0, "gen_s": 0.0, "wall_s": 0.0}
    for p in args.files:
        s = json.load(open(Path(p).with_suffix(".stats.json")))
        for k in ("images", "samples", "rejected", "gen_s", "wall_s"):
            agg[k] += s.get(k, 0)
        agg["fallback"] += len(s["fallback"])
        for r, c in s["reasons"].items():
            agg["reasons"][r] = agg["reasons"].get(r, 0) + c
    first = 2 * agg["images"]  # first-pass samples
    print(json.dumps(agg, indent=1))
    print(f"img/s (generation only) {agg['images'] / agg['gen_s']:.2f}, (wall) {agg['images'] / agg['wall_s']:.2f}")
    print(f"rejected / all samples {agg['rejected'] / agg['samples']:.3f}; resample overhead "
          f"{agg['samples'] / first - 1:.3f}; images with a fallback caption {agg['fallback'] / agg['images']:.4f}")
    for strict in (False, True):
        final = [violations(r[k], strict=strict) for r in rows for k in ("recap_1", "recap_2")]
        print(f"final captions still violating ({'extended' if strict else 'spec'} rules) "
              f"{sum(map(bool, final)) / len(final):.4f}")
    wc = sorted(len(r[k].split()) for r in rows for k in ("recap_1", "recap_2"))
    print(f"words: p5 {wc[len(wc) // 20]} median {wc[len(wc) // 2]} p95 {wc[19 * len(wc) // 20]}")
    rng = random.Random(0)
    sub = rng.sample(rows, min(args.sim, len(rows)))
    pair = [similarity(r["recap_1"], r["recap_2"]) for r in sub]
    other = [similarity(r["recap_1"], rng.choice(rows)["recap_2"]) for r in sub]  # different images: floor
    orig = [similarity(r["recap_1"], r["orig_caption"]) for r in sub]
    for name, s in (("recap_1 vs recap_2 (same image)", pair), ("recap_1 vs orig (same image)", orig),
                    ("recap_1 vs recap_2 (random image)", other)):
        print(f"{name}: " + ", ".join(f"{k} {sum(x[k] for x in s) / len(s):.3f}" for k in s[0]))


def export(args):
    """One parquet per shard (tar order, keys unique), row counts checked against the subset manifest."""
    import pyarrow as pa
    import pyarrow.parquet as pq

    src, out = Path(args.src), Path(args.out)
    out.mkdir(parents=True, exist_ok=True)
    cols = ("key", "source_shard", "orig_caption", "recap_1", "recap_2")
    total = 0
    for sh in json.load(open(args.manifest))["shards"]:
        stem = Path(sh["file"]).stem
        assert (src / f"{stem}.done").exists(), f"{stem} not finished"
        rows, seen = [], set()
        for line in open(src / f"{stem}.jsonl"):
            try:
                r = json.loads(line)
            except json.JSONDecodeError:  # a line cut by a killed worker
                continue
            if r["key"] not in seen:
                seen.add(r["key"])
                rows.append(r)
        assert len(rows) == sh["pairs"], f"{stem}: {len(rows)} rows, manifest {sh['pairs']}"
        pq.write_table(pa.table({c: [r[c] for r in rows] for c in cols}), out / f"{stem}.parquet", compression="zstd")
        total += len(rows)
    print(f"{total} rows -> {out}")


if __name__ == "__main__":
    ap = argparse.ArgumentParser()
    sub = ap.add_subparsers(dest="cmd", required=True)
    r = sub.add_parser("run")
    r.add_argument("--shards", nargs="+", required=True)
    r.add_argument("--out", required=True)
    r.add_argument("--model", default=MODEL)
    r.add_argument("--limit", type=int, default=0, help="images per shard (test runs; no .done marker)")
    r.add_argument("--chunk", type=int, default=1024)
    r.add_argument("--no-ban", action="store_true", help="no decode-time bans (filter + resample only)")
    r.add_argument("--retries", type=int, default=3)
    r.add_argument("--focus", action="store_true", help="add the FOCUS sentence to the second caption's prompt")
    r.add_argument("--gpu-mem", type=float, default=0.85)
    r.add_argument("--workers", type=int, default=16)
    r.add_argument("--seed", type=int, default=0)
    x = sub.add_parser("fix", help="regenerate only the captions that violate the current rules")
    x.add_argument("--shards", nargs="+", required=True)
    x.add_argument("--out", required=True)
    x.add_argument("--model", default=MODEL)
    x.add_argument("--chunk", type=int, default=1024)
    x.add_argument("--retries", type=int, default=3)
    x.add_argument("--gpu-mem", type=float, default=0.85)
    x.add_argument("--workers", type=int, default=16)
    x.add_argument("--seed", type=int, default=0)
    x.add_argument("--no-ban", action="store_true")
    s = sub.add_parser("stats")
    s.add_argument("files", nargs="+")
    s.add_argument("--sim", type=int, default=500)
    e = sub.add_parser("export")
    e.add_argument("--src", required=True)
    e.add_argument("--out", required=True)
    e.add_argument("--manifest", required=True)
    a = ap.parse_args()
    {"run": run, "fix": fix, "stats": stats, "export": export}[a.cmd](a)