File size: 16,247 Bytes
149c236
 
 
 
 
 
3688d57
149c236
 
 
 
 
 
853d8c9
 
 
149c236
 
 
 
 
 
 
 
 
 
 
 
3688d57
7bd0abb
 
 
 
3688d57
 
7bd0abb
149c236
7bd0abb
149c236
3688d57
 
 
 
 
149c236
 
 
 
 
7bd0abb
 
 
149c236
 
 
 
 
853d8c9
149c236
 
 
 
3688d57
149c236
 
 
 
 
853d8c9
 
 
 
 
 
149c236
 
 
 
 
853d8c9
149c236
 
 
 
7bd0abb
 
 
149c236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3688d57
149c236
 
 
3688d57
149c236
 
 
 
 
 
 
 
 
 
 
 
 
 
3688d57
 
 
149c236
 
 
3688d57
 
149c236
3688d57
 
 
 
 
 
 
149c236
853d8c9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
149c236
 
853d8c9
 
 
 
 
 
149c236
 
3688d57
 
 
 
 
 
 
 
 
 
 
 
 
 
149c236
 
 
 
 
 
 
 
 
 
 
 
3688d57
 
 
 
 
149c236
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
853d8c9
149c236
 
3688d57
 
149c236
3688d57
149c236
3688d57
149c236
 
 
3688d57
149c236
 
 
 
 
 
 
 
3688d57
149c236
 
 
 
 
 
853d8c9
 
 
149c236
 
 
 
 
 
 
 
 
 
 
853d8c9
 
 
 
149c236
 
 
3688d57
853d8c9
149c236
 
 
 
3688d57
 
 
 
 
149c236
853d8c9
 
149c236
853d8c9
 
 
149c236
 
 
853d8c9
 
 
 
3688d57
 
149c236
853d8c9
3688d57
149c236
 
 
 
 
 
 
 
 
 
 
 
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
#!/usr/bin/env -S uv run --script
# /// script
# requires-python = ">=3.10"
# dependencies = [
#   "falcon-perception>=1.0.0",
#   # tarball not git+: some GPU images have no `git` for uv to shell out to
#   "bucketbag @ https://github.com/davanstrien/bucketbag/archive/refs/tags/v0.3.1.tar.gz",
#   "pyarrow>=18",
#   "pycocotools>=2.0.11",
# ]
# ///
"""Falcon-Perception over a whole HF bucket, resumable.

    hf jobs uv run --flavor a10g-large --secrets HF_TOKEN \
        https://huggingface.co/datasets/uv-scripts/object-detection/raw/main/falcon-perception-bucket.py \
        --src biglam/bl-images --prefix full/embellishments \
        --out davanstrien/bl-masks --query illustration

Input  : bucketbag batched_files — bounded scratch, files deleted as the loop advances
Engine : PagedInferenceEngine (CUDA, continuous batching)
Output : one parquet per batch -> out bucket; resume via completed_keys(__source_key)

Kill it at any point and re-run the same command. Done keys are skipped.

Output is parquet parts in a BUCKET, not a dataset repo — that is what makes the
run resumable (`completed_keys` reads the done-set back from `__source_key`).
To hand the result to the rest of this directory, publish it once at the end:

    from datasets import ClassLabel, Image, Sequence, load_dataset
    ds = load_dataset("parquet", data_files="hf://buckets/<namespace>/<bucket>/part-*.parquet",
                      split="train")
    feats = ds.features.copy()  # parquet stores category as bare ints; name the class
    feats["objects"]["category"] = Sequence(ClassLabel(names=[ds[0]["query"]]))
    if "image" in feats:  # --embed-images parts: make the bytes a decodable Image column
        feats["image"] = Image()
    ds.cast(feats).push_to_hub("<namespace>/<dataset>")  # a dataset repo, distinct from the bucket

    uv run validate-hf-dataset.py <namespace>/<dataset> --bbox-format yolo

By default the parts carry `width`/`height` but no `image` column: the images stay in
the source bucket, the parts stay small and resumable, and `embed-bucket-images.py`
joins the bytes back in. Pass --embed-images to write the source bytes into each part
instead (an `image` column datasets decodes directly) -- storage is cheap and it saves
the join's re-fetch of every image; the cost is a copy of the corpus in the output bucket.

GOTCHAS (all measured, none in the model card):
  * --query is a CLASS NAME. "illustration" works; "the illustration, excluding
    captions" returns nothing.
  * torch.compile breaks on per-image dynamic shapes -> compile is OFF here.
  * engine_config_for_gpu() sizes from the GPU and ignores host RAM; the 15 GB
    flavors (t4-small, a10g-small) get OOMKilled (exit 137) before processing
    anything -- pick >15 GB `ram` from `hf jobs hardware --json`.
    cudagraph is off by default here for the same reason.
  * xy in the output is the NORMALISED CENTRE, not a corner.
"""

import argparse
import hashlib
import io
import json
import time

import fsspec
import pyarrow as pa
import pyarrow.parquet as pq
from bucketbag import batched_files, boost, completed_keys, iter_keys, put_files
from pycocotools import mask as mask_utils


def stable_id(key):
    """Deterministic int64 image_id from the source key (COCO consumers need an int;
    a hash, not a running index, keeps ids identical across resumed runs)."""
    return int.from_bytes(hashlib.blake2b(str(key).encode(), digest_size=8).digest(), "big") >> 1

# Same YOLO column layout as falcon-perception.py, so both outputs validate with
# `validate-hf-dataset.py --bbox-format yolo` and can be concatenated.
# `__source_key` is bucketbag's resume column — the name is load-bearing.
SCHEMA = pa.schema([
    ("__source_key", pa.string()),
    ("image_id", pa.int64()),  # int, not str: COCO-style trainers tensorise it
    ("width", pa.int32()),
    ("height", pa.int32()),
    ("objects", pa.struct([
        ("bbox", pa.list_(pa.list_(pa.float32()))),   # yolo: cx, cy, w, h normalised
        ("category", pa.list_(pa.int64())),           # single class per run; the class NAME
                                                      # is the `query` column — cast to
                                                      # ClassLabel at publish (see docstring)
        ("area", pa.list_(pa.float32())),
        ("rectangularity", pa.list_(pa.float32())),   # triage proxy — no confidence score exists
    ])),
    ("n_instances", pa.int32()),
    ("masks_rle", pa.string()),
    ("query", pa.string()),
    ("gen_seconds", pa.float32()),
    ("error", pa.string()),
])


def pair_bboxes(raw):
    boxes, cur = [], {}
    for e in raw:
        if not isinstance(e, dict):
            continue
        cur.update(e)
        if all(k in cur for k in ("x", "y", "h", "w")):
            boxes.append(dict(cur)); cur = {}
    return boxes


def serialise(rows, fmt, schema=SCHEMA):
    if fmt == "jsonl":
        return "\n".join(json.dumps(r) for r in rows) + "\n"
    buf = io.BytesIO()
    pq.write_table(pa.Table.from_pylist(rows, schema=schema), buf, compression="zstd")
    return buf.getvalue()


def main():
    p = argparse.ArgumentParser()
    p.add_argument("--src", required=True, help="source bucket, e.g. biglam/bl-images")
    p.add_argument("--prefix", default=None, help="bucket prefix, e.g. full/embellishments")
    p.add_argument("--out", required=True, help="output bucket")
    p.add_argument("--query", default="illustration", help="a CLASS NAME, not an instruction")
    p.add_argument("--task", default="segmentation", choices=["segmentation", "detection"])
    p.add_argument("--limit", type=int, default=None)
    p.add_argument("--max-dim", type=int, default=1024)
    p.add_argument("--max-new-tokens", type=int, default=200)
    p.add_argument("--batch-n", type=int, default=32, help="files per bucketbag batch")
    p.add_argument("--max-bytes", type=int, default=None,
                   help="scratch bytes per batch (RAM tmpfs). Default 2 GiB; 256 MiB with --embed-images, "
                        "whose bytes are also held ~4x in host RAM while a part is serialised")
    p.add_argument("--cudagraph", action="store_true", help="opt IN; off by default (host OOM)")
    p.add_argument("--format", default="parquet", choices=["parquet", "jsonl"])
    p.add_argument("--no-resume", action="store_true")
    p.add_argument("--embed-images", action="store_true",
                   help="also write the source image bytes into each part (see docstring)")
    args = p.parse_args()
    if args.embed_images and args.format == "jsonl":
        raise SystemExit("--embed-images writes raw image bytes, which jsonl cannot carry; use --format parquet.")
    if args.max_bytes is None:
        args.max_bytes = 256 * 2**20 if args.embed_images else 2 * 2**30
    schema = SCHEMA
    if args.embed_images:
        schema = SCHEMA.append(pa.field("image", pa.struct([("bytes", pa.binary()), ("path", pa.string())])))

    if args.format == "jsonl" and not args.no_resume:
        # completed_keys only reads the done-set back from .parquet parts, so jsonl
        # output silently reprocesses EVERYTHING on every re-run.
        raise SystemExit("--format jsonl is not resumable; pass --no-resume to run it anyway.")

    try:
        import torch

        has_cuda = torch.cuda.is_available()
    except ImportError:  # falcon-perception pins torch off-darwin, so it may be absent
        has_cuda = False
    if not has_cuda:
        raise SystemExit(
            "This script needs a CUDA GPU (PagedInferenceEngine). "
            "For MLX/CPU-capable runs use falcon-perception.py instead."
        )

    boost()  # raise xet small-file concurrency — the whole point on many small objects

    from huggingface_hub import HfApi

    # first run: the out bucket may not exist yet — completed_keys 404s on a
    # missing bucket, killing the job before anything happens
    HfApi().create_bucket(args.out, private=True, exist_ok=True)

    done = set() if args.no_resume else completed_keys(args.out)
    print(f"{len(done)} keys already done", flush=True)
    if done and args.format == "parquet":
        # a resume must not mix part schemas: half the parts with an image column and half
        # without loads as nulls downstream, and the null rows crash the trainer's tree build
        first_part = next((f for f in iter_keys(args.out, prefix="part-", objects=True)
                           if f.path.endswith(".parquet")), None)
        if first_part is not None:
            with fsspec.open(f"hf://buckets/{args.out}/{first_part.path}", "rb") as fh:
                existing = pq.read_schema(fh)
            if ("image" in existing.names) != args.embed_images:
                raise SystemExit(
                    f"existing parts in {args.out} were written "
                    f"{'with' if 'image' in existing.names else 'without'} --embed-images; "
                    "resume with the same flag, or write to a fresh --out bucket."
                )

    # objects=True yields BucketFile (with .size), so max_bytes is honoured.
    # Needs bucketbag >= 0.3.0: before that, string keys made batched_files drop
    # max_bytes silently and run unbounded against RAM-tmpfs scratch.
    keys = [
        f for f in iter_keys(args.src, prefix=args.prefix, objects=True)
        if f.path.lower().endswith((".jpg", ".jpeg", ".png")) and f.path not in done
    ]
    if args.limit:
        keys = keys[: args.limit]
    print(f"{len(keys)} keys to process", flush=True)
    if not keys:
        raise SystemExit(
            f"0 keys matched under {args.src}/{args.prefix or ''} — this script reads only "
            ".jpg/.jpeg/.png (convert JPEG 2000 / TIFF first), and already-done keys are skipped "
            "(pass --no-resume to redo)."
        )

    from falcon_perception import PERCEPTION_MODEL_ID, build_prompt_for_task, load_and_prepare_model, setup_torch_config
    from falcon_perception.data import ImageProcessor
    from falcon_perception.paged_inference import (
        PagedInferenceEngine, SamplingParams, Sequence, engine_config_for_gpu,
    )

    setup_torch_config()
    t = time.perf_counter()
    model, tokenizer, _ = load_and_prepare_model(
        hf_model_id=PERCEPTION_MODEL_ID, dtype="bfloat16", compile=False,  # compile breaks on dynamic shapes
    )
    print(f"model loaded in {time.perf_counter() - t:.1f}s", flush=True)

    cfg = engine_config_for_gpu(max_image_size=args.max_dim, dtype=model.dtype)
    print(f"paged config: {cfg}", flush=True)
    engine = PagedInferenceEngine(
        model, tokenizer, ImageProcessor(patch_size=16, merge_size=1),
        max_seq_length=8192, capture_cudagraph=args.cudagraph, **cfg,
    )
    sp = SamplingParams(
        args.max_new_tokens,
        stop_token_ids=[tokenizer.eos_token_id, tokenizer.end_of_query_token_id],
        coord_dedup_threshold=0.01,
    )
    prompt = build_prompt_for_task(args.query, args.task)

    n, gen_total, t_all, batch_i = 0, 0.0, time.perf_counter(), 0
    for batch in batched_files(args.src, keys=keys, n=args.batch_n, max_bytes=args.max_bytes):
        # NOTE: never hold a LoadedItem past its batch — convert eagerly.
        pairs = []
        for it in batch:
            try:
                img = it.image.convert("RGB")  # convert() forces the load off disk
                orig_size = img.size  # SOURCE dims -- the images downstream tools decode
                if max(img.size) > args.max_dim * 2:
                    img.thumbnail((args.max_dim * 2, args.max_dim * 2))
                raw = it.bytes if args.embed_images else None  # read before the batch is deleted
                pairs.append((str(it.key), img, orig_size, raw))
            except Exception as e:
                pairs.append((str(it.key), e, None, None))

        good = [(k, im, sz, raw) for k, im, sz, raw in pairs if not isinstance(im, Exception)]
        seqs = [
            Sequence(text=prompt, image=im, min_image_size=256,
                     max_image_size=args.max_dim, request_idx=i, task=args.task)
            for i, (_, im, _, _) in enumerate(good)
        ]
        t0 = time.perf_counter()
        if seqs:
            engine.generate(seqs, sampling_params=sp)
        dt = time.perf_counter() - t0
        gen_total += dt

        rows = []
        for (key, im, orig_size, raw), seq in zip(good, seqs):
            aux = seq.output_aux
            boxes = pair_bboxes(aux.bboxes_raw)
            masks = list(aux.masks_rle)
            for m in masks:
                if isinstance(m.get("counts"), bytes):
                    m["counts"] = m["counts"].decode()
            # width/height are the SOURCE image's dims: boxes are normalised (frame-free),
            # and downstream pixel conversions run against the untouched bucket images.
            W, H = orig_size
            bbox, area, rect = [], [], []
            for i, b in enumerate(boxes):
                bbox.append([b["x"], b["y"], b["w"], b["h"]])  # yolo: cx, cy, w, h normalised
                a = b["w"] * b["h"]
                area.append(a)
                r = 0.0
                if i < len(masks):  # rectangularity — the only triage signal; no score exists
                    try:
                        m = masks[i]
                        if isinstance(m.get("counts"), str):
                            m = {**m, "counts": m["counts"].encode()}
                        # box area measured in the MASK's own frame (rle size) — mixing
                        # frames skews r
                        mh, mw = (m.get("size") or [H, W])[:2]
                        r = min(float(mask_utils.area(m)) / max(a * mw * mh, 1.0), 1.0)
                    except Exception:
                        r = 0.0
                rect.append(r)
            row = {
                "__source_key": key, "image_id": stable_id(key), "width": W, "height": H,
                "objects": {"bbox": bbox, "category": [0] * len(bbox),
                            "area": area, "rectangularity": rect},
                "n_instances": len(bbox), "masks_rle": json.dumps(masks),
                "query": args.query, "gen_seconds": dt / max(len(seqs), 1), "error": None,
            }
            if args.embed_images:
                row["image"] = {"bytes": raw, "path": None}
            rows.append(row)
        for key, err, _, _ in [t for t in pairs if isinstance(t[1], Exception)]:
            # a durable error row, never a gap — and it counts as done so it is
            # not retried forever on every re-run. objects is EMPTY, not null:
            # a null struct crashes validate-hf-dataset.py after publish.
            rows.append({k: None for k in SCHEMA.names} | {
                "__source_key": key, "image_id": stable_id(key), "query": args.query,
                "objects": {"bbox": [], "category": [], "area": [], "rectangularity": []},
                "n_instances": 0, "masks_rle": "[]",
                "error": f"{type(err).__name__}: {err}",
            })

        # part name derives from batch CONTENT, not a run-local counter: a resumed run's
        # counter restarts at 0 and put_files overwrites, silently destroying the first
        # run's parts. A content-derived name is stable per batch and collision-free
        # across resumes (a re-run of the same batch overwrites its own part, idempotent).
        if not rows:  # bucketbag drops files that vanished between listing and download
            continue
        ext = "jsonl" if args.format == "jsonl" else "parquet"
        part = hashlib.blake2b(rows[0]["__source_key"].encode(), digest_size=6).hexdigest()
        put_files([(f"part-{part}.{ext}", serialise(rows, args.format, schema))], args.out)
        n += len(rows); batch_i += 1
        rate = n / (time.perf_counter() - t_all)
        print(f"batch {batch_i}: {len(rows)} rows ({dt / max(len(seqs), 1):.2f}s/img)  "
              f"total {n}  {rate:.2f} img/s", flush=True)

    wall = time.perf_counter() - t_all
    print(f"\n{n} images in {wall:.1f}s ({gen_total:.1f}s generation) | {n / wall:.2f} img/s", flush=True)
    if n:
        print(f"extrapolation: 100k images ≈ {wall / n * 100_000 / 3600:.1f} GPU-hours end-to-end", flush=True)


main()