Sync from GitHub via hub-sync
Browse filesFiles changed (3)
- README.md+76-1
- falcon-perception-bucket.pyAdded+239
- falcon-perception.pyAdded+429
4 unmodified lines56789101117 unmodified lines293031323334207 unmodified lines2422432444 unmodified lines# Object Detection Dataset Scripts5 scripts to convert, validate, inspect, diff, and sample object detection datasets on the Hub. Supports 6 bbox formats — no setup required.This repository is inspired by [panlabel](https://github.com/strickvl/panlabel)## Quick Start17 unmodified lines| Script | Description ||--------|-------------|| `convert-hf-dataset.py` | Convert between 6 bbox formats and push to Hub || `validate-hf-dataset.py` | Check annotations for errors (invalid bboxes, duplicates, bounds) || `stats-hf-dataset.py` | Compute statistics (counts, label histogram, area, co-occurrence) |207 unmodified lines```Works with any Hugging Face dataset containing object detection annotations — COCO, YOLO, VOC, TFOD, or Label Studio format.4 unmodified lines567891011121317 unmodified lines3132333435363738207 unmodified lines2462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183194 unmodified lines# Object Detection Dataset Scripts7 scripts to **create**, convert, validate, inspect, diff, and sample object detection datasets on the Hub. Supports 6 bbox formats — no setup required.Start from nothing: `falcon-perception.py` generates a first-pass detection dataset for any class you can name, zero-shot, with no labelling and no training. The other six then convert, check, and measure it.This repository is inspired by [panlabel](https://github.com/strickvl/panlabel)## Quick Start17 unmodified lines| Script | Description ||--------|-------------|| `falcon-perception.py` | **Create** a detection dataset zero-shot from any image dataset — name a class, get boxes + masks (runs on Apple Silicon too) || `falcon-perception-bucket.py` | Same, reading images from an HF bucket, resumable across restarts || `convert-hf-dataset.py` | Convert between 6 bbox formats and push to Hub || `validate-hf-dataset.py` | Check annotations for errors (invalid bboxes, duplicates, bounds) || `stats-hf-dataset.py` | Compute statistics (counts, label histogram, area, co-occurrence) |207 unmodified lines```Works with any Hugging Face dataset containing object detection annotations — COCO, YOLO, VOC, TFOD, or Label Studio format.## Making a dataset from scratchThe other scripts assume you already have annotations. `falcon-perception.py` is where they can come from — [Falcon-Perception](https://huggingface.co/tiiuae/Falcon-Perception) finds every instance of a class you name, with no label set and no training:```bash# 1. does the model do the thing? (your laptop — no GPU needed)uv run falcon-perception.py --image page.jpg --query illustration --preview# 2. does it work on YOUR data? (first rows of the real corpus)uv run falcon-perception.py --dataset biglam/british-library-book-images \--config plates --limit 3 --preview# 3. the whole corpus, on a GPUhf jobs uv run --flavor a10g-large --secrets HF_TOKEN falcon-perception.py -- \--dataset biglam/british-library-book-images --config plates \--id-col fname --query illustration --out you/plates-illustrations# 4. it is already in `yolo` format — the rest of this directory just worksuv run validate-hf-dataset.py you/plates-illustrations --bbox-format yolouv run stats-hf-dataset.py you/plates-illustrations --bbox-format yolo```Falcon emits boxes as normalised centre x,y + w,h, which *is* the `yolo` format above, so no conversion step is needed.**The correction loop.** A zero-shot first pass is a starting point, not ground truth. Convert it for human review, correct it, then diff the two to find out how good the first pass actually was:```bashuv run convert-hf-dataset.py you/plates-illustrations you/for-review --from yolo --to label_studio# ... correct in Label Studio, push as you/corrected ...uv run diff-hf-datasets.py you/plates-illustrations you/corrected # IoU match = zero-shot accuracy```**Runs without a CUDA GPU.** Unlike most recipes in this repo, `falcon-perception.py` selects the MLX backend on Apple Silicon automatically. It is slower there (~6 s/img vs ~0.4 on an A10G), which is the right trade for step 1 and 2 above — checking your class name works before spending GPU hours.### Known limitsMeasured, not guessed — see the script docstrings for the failure each one came from.| Limit | What to do ||---|---|| `--query` is a **class name**, not an instruction | `illustration` works; `the illustration, excluding captions` returns nothing || **One class per run** | A combined query returned 6 instances where three single-class runs found 24. N classes = N runs, then concatenate || **No confidence scores** — the model has no score token | Sort review by the emitted `rectangularity` (mask area ÷ bbox area, measured 0.34–1.00) and apply an area floor || `a10g-small` gets OOMKilled | The engine's auto-config sizes from the GPU and ignores host RAM — use `a10g-large` |### Just want the numbers?`--out` takes a file path as readily as a repo id — no Hub push, nothing to clean up:```bashuv run falcon-perception.py --image page.jpg --query illustration --out results.jsonuv run falcon-perception.py --image "scans/*.jpg" --query illustration --out results.jsonluv run falcon-perception.py --image page.jpg --query illustration --json | jq '.[0].objects.bbox'```Anything ending `.json`, `.jsonl` or `.parquet` is written locally; anything else is treated as a Hub dataset repo id.### Bucket runs`falcon-perception-bucket.py` reads images from an HF bucket and writes resumable parquet parts back to a bucket — kill it and re-run the same command, done keys are skipped. Publish once at the end to use the rest of this directory:```pythonfrom datasets import load_datasetload_dataset("parquet", data_files=["hf://buckets/you/bl-masks/part-000000.parquet", ...],split="train").push_to_hub("you/bl-masks")```### Output columns`objects.bbox` (`yolo`), `objects.category`, `objects.area`, `objects.rectangularity`, plus `image`, `image_id`, `width`, `height`, `n_instances`, and `masks_rle` (COCO RLE — segmentation rides along; the bbox scripts ignore it).
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239#!/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.0.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 falcon-bucket.py -- \ --src biglam/bl-images --include 'full/embellishments/**/*.jpg' \ --out davanstrien/bl-masks --query illustration
Input : bucketbag batched_files — bounded scratch, files deleted as the loop advancesEngine : 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 therun 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 load_dataset load_dataset("parquet", data_files=[ "hf://buckets/you/bl-masks/part-000000.parquet", ... ], split="train").push_to_hub("you/bl-masks")
uv run validate-hf-dataset.py you/bl-masks --bbox-format yolo
Note the parts carry `width`/`height` but no `image` column (the images stay inthe source bucket), so pass --image-column accordingly if a downstream scriptwants to decode them.
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; on a10g-small it gets OOMKilled (exit 137) before processing anything. cudagraph is off by default here for the same reason. * xy in the output is the NORMALISED CENTRE, not a corner."""
import argparseimport ioimport jsonimport time
import pyarrow as paimport pyarrow.parquet as pqfrom bucketbag import batched_files, boost, completed_keys, iter_keys, put_filesfrom pycocotools import mask as mask_utils
# 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.string()), ("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, by design ("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): 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=2 * 2**30) 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") args = p.parse_args()
boost() # raise xet small-file concurrency — the whole point on many small objects
done = set() if args.no_resume else completed_keys(args.out) print(f"{len(done)} keys already done", flush=True)
# 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: return
import torch # noqa: F401 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 if max(img.size) > args.max_dim * 2: img.thumbnail((args.max_dim * 2, args.max_dim * 2)) pairs.append((str(it.key), img)) except Exception as e: pairs.append((str(it.key), e))
good = [(k, im) for k, im 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), 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() W, H = im.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()} r = min(float(mask_utils.area(m)) / max(a * W * H, 1.0), 1.0) except Exception: r = 0.0 rect.append(r) rows.append({ "__source_key": key, "image_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, }) for key, err in [(k, v) for k, v in pairs if isinstance(v, Exception)]: # a durable error row, never a gap — and it counts as done so it is # not retried forever on every re-run rows.append({k: None for k in SCHEMA.names} | { "__source_key": key, "image_id": key, "query": args.query, "error": f"{type(err).__name__}: {err}", })
ext = "jsonl" if args.format == "jsonl" else "parquet" put_files([(f"part-{batch_i:06d}.{ext}", serialise(rows, args.format))], 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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429#!/usr/bin/env -S uv run --script# /// script# requires-python = ">=3.10"# dependencies = [# "falcon-perception>=1.0.0",# "datasets>=4.5.0",# "huggingface-hub>=1.12.0",# "pillow",# ]# ///"""Zero-shot object detection + instance segmentation -> a YOLO detection dataset.
Falcon-Perception finds every instance of a class you name, with no training andno label set. Output is a detection dataset in `yolo` format, so it feeds theother recipes in this directory directly:
validate-hf-dataset.py you/first-pass --bbox-format yolo stats-hf-dataset.py you/first-pass --bbox-format yolo convert-hf-dataset.py you/first-pass you/for-review --from yolo --to label_studio # ... a human corrects the first pass in Label Studio ... diff-hf-datasets.py you/first-pass you/corrected # IoU -> zero-shot accuracy
RUNS ON YOUR LAPTOP TOO. Unusually for this repo no CUDA GPU is required: onApple Silicon it selects the MLX backend automatically. Slower (~6 s/img vs~0.4 on an A10G), which is fine for the step that matters locally -- checkingyour class name works on your images before spending GPU hours on the corpus.
# 1. does the model do the thing? uv run falcon-perception.py --image page.jpg --query illustration --preview
# 2. does it work on MY data? (first rows of the real corpus) uv run falcon-perception.py --dataset biglam/british-library-book-images \ --config plates --limit 3 --preview
# 3. the whole corpus, on a GPU hf jobs uv run --flavor a10g-large --secrets HF_TOKEN falcon-perception.py -- \ --dataset biglam/british-library-book-images --config plates \ --id-col fname --query illustration --out you/plates-illustrations
Output goes wherever --out points:
--out you/plates-illustrations a Hub dataset (yolo format, feeds the scripts above) --out results.json a local JSON file -- no Hub push --out results.jsonl a local JSONL file -- one record per line --out results.parquet a local parquet file --json also print the records on stdout, for piping (omit --out) print a summary and, with --preview, annotated JPEGs
For images in a bucket rather than a dataset, see falcon-perception-bucket.py.
MEASURED LIMITS -- not guesses; each one cost a failed run:
* --query takes a CLASS NAME, never an instruction. "illustration" works; "the illustration, excluding captions" returns nothing at all. * ONE class per run. A combined query ("illustration, map, portrait") returned 6 instances where three single-class passes found 24, and emitted <|absence|> on the richest image. The output vocabulary has no class token either, so instances could not be attributed even if the counts held. N classes = N runs. * NO confidence scores -- the model has no score token. Two triage proxies are emitted instead: `rectangularity` (mask area / bbox area; measured 0.34-1.00, low = irregular, 1.00 = clean rectangular plate) and `area`. Sort review by rectangularity ascending and apply an area floor; the smallest box seen was 941 px^2 and was spurious. * torch.compile is OFF. Per-image dynamic shapes break Inductor ("ValueError: Exponent must be non-negative" after symbolic-shape recursion). * CUDA graphs are OFF by default. engine_config_for_gpu() sizes itself from the GPU and ignores host RAM; on a10g-small the container is OOMKilled (exit 137) before one image is processed. Use a10g-large, or pass --cudagraph knowingly."""
import argparseimport glob as globlibimport ioimport itertoolsimport jsonimport osimport pathlibimport platformimport sysimport time
# ── backend / engine selection ──────────────────────────────────────────────# The MLX and torch APIs match parameter-for-parameter, but are NOT drop-in:# torch also needs setup_torch_config(), a compile= kwarg, and every batch tensor# moved with .to(device). Omitting the last fails deep inside# flex_attention.create_block_mask, nowhere near the actual cause.
def pick_backend(requested): if requested != "auto": return requested return "mlx" if (sys.platform == "darwin" and platform.machine() == "arm64") else "torch"
def guard_mlx_memory(frac=0.55): """MLX allocates from unified memory with NO default cap.
An oversized image through the AnyUp upsampler exhausts system RAM and hangs the whole machine -- the process is never OOM-killed, because there is no separate GPU pool for the kernel to reclaim. Measured: 0.22 MP ran fine; 5.4 MP took down a 32 GiB Mac whose MLX default ceiling was 30.4 GiB. """ try: import mlx.core as mx
total = os.sysconf("SC_PAGE_SIZE") * os.sysconf("SC_PHYS_PAGES") mx.set_memory_limit(int(total * frac)) print(f"mlx memory capped at {total * frac / 2**30:.1f} GiB", flush=True) except Exception as e: print(f"WARNING: could not cap MLX memory ({e}) -- a large image may hang this machine", flush=True)
# ── sources: every source yields (key, PIL image) ───────────────────────────
def src_images(spec): from falcon_perception.data import load_image from PIL import Image
if spec.startswith(("http://", "https://")): from urllib.parse import unquote
yield unquote(spec.rsplit("/", 1)[-1])[:120], load_image(spec).convert("RGB") return paths = sorted(globlib.glob(spec)) if any(c in spec for c in "*?[") else [spec] if not paths: raise SystemExit(f"no files matched {spec!r}") for p in paths: yield os.path.basename(p), Image.open(p).convert("RGB")
def src_dataset(repo, config, split, image_col, id_col): from datasets import load_dataset from PIL import Image
ds = load_dataset(repo, config, split=split, streaming=True) for idx, row in enumerate(ds): im = row[image_col] if isinstance(im, dict) and "bytes" in im: im = Image.open(io.BytesIO(im["bytes"])) yield (str(row.get(id_col)) if id_col else str(idx)), im.convert("RGB")
# ── helpers ─────────────────────────────────────────────────────────────────
def pair_bboxes(raw): """[{x,y}, {h,w}, ...] -> [{x,y,h,w}, ...]. xy is the normalised CENTRE.
Centre-not-corner is why the output is natively `yolo` -- and why a corner reading would put every box out of bounds. """ 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 fit(im, max_dim, backend): """Downscale BEFORE the preprocessor sees it -- on MLX the full-size intermediate is what exhausts memory.""" budget = max_dim if backend == "mlx" else max_dim * 2 if max(im.size) > budget: im = im.copy() im.thumbnail((budget, budget)) return im
def save_preview(key, im, boxes, rles, out_dir): import numpy as np from PIL import Image, ImageDraw from pycocotools import mask as mask_utils
os.makedirs(out_dir, exist_ok=True) W, H = im.size canvas = np.array(im.convert("RGB"), dtype=np.float32) for i, rle in enumerate(rles): m = rle if isinstance(rle.get("counts"), bytes) else {**rle, "counts": str(rle["counts"]).encode()} try: dec = mask_utils.decode(m).astype("uint8") except Exception: continue if dec.shape != (H, W): # mask is at model resolution -- NEAREST only dec = np.array(Image.fromarray(dec).resize((W, H), Image.NEAREST)) col = np.array([(255, 60, 60), (60, 160, 255), (80, 200, 120)][i % 3], dtype=np.float32) sel = dec > 0 canvas[sel] = canvas[sel] * 0.65 + col * 0.35 out = Image.fromarray(canvas.clip(0, 255).astype("uint8")) pen = ImageDraw.Draw(out) for b in boxes: cx, cy, bw, bh = b["x"] * W, b["y"] * H, b["w"] * W, b["h"] * H pen.rectangle([cx - bw / 2, cy - bh / 2, cx + bw / 2, cy + bh / 2], outline=(255, 220, 0), width=3) safe = "".join(c if c.isalnum() or c in "._-" else "_" for c in key)[:80] path = os.path.join(out_dir, f"{safe}.jpg") out.save(path) return path
def batched(it, n): buf = [] for x in it: buf.append(x) if len(buf) == n: yield buf buf = [] if buf: yield buf
# ── the two generation paths ────────────────────────────────────────────────
def run_paged(model, tokenizer, items, prompt, args): """CUDA: TII's continuous-batching engine. ~0.4 s/img on an A10G.""" from falcon_perception.data import ImageProcessor from falcon_perception.paged_inference import ( PagedInferenceEngine, SamplingParams, Sequence, engine_config_for_gpu, )
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, ) for chunk in batched(items, args.chunk): chunk = [(k, fit(im, args.max_dim, "torch")) for k, im in chunk] 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(chunk) ] t0 = time.perf_counter() engine.generate(seqs, sampling_params=sp) dt = (time.perf_counter() - t0) / len(seqs) for (k, im), s in zip(chunk, seqs): yield k, im, s.output_aux, dt
def run_batch(model, tokenizer, items, prompt, args, backend, max_seq_len): """MLX (and a torch fallback): the readable reference engine. ~6 s/img on an M1 Pro.""" if backend == "mlx": from falcon_perception.mlx.batch_inference import BatchInferenceEngine, process_batch_and_generate else: from falcon_perception.batch_inference import BatchInferenceEngine, process_batch_and_generate
engine = BatchInferenceEngine(model, tokenizer) for chunk in batched(items, 1 if backend == "mlx" else args.chunk): chunk = [(k, fit(im, args.max_dim, backend)) for k, im in chunk] b = process_batch_and_generate( tokenizer, [(im, prompt) for _, im in chunk], max_length=max_seq_len, min_dimension=256, max_dimension=args.max_dim, ) if backend != "mlx": # torch needs every tensor on the model's device import torch
b = {k2: (v.to(model.device) if torch.is_tensor(v) else v) for k2, v in b.items()} t0 = time.perf_counter() _, auxes = engine.generate( tokens=b["tokens"], pos_t=b["pos_t"], pos_hw=b["pos_hw"], pixel_values=b["pixel_values"], pixel_mask=b["pixel_mask"], max_new_tokens=args.max_new_tokens, temperature=0.0, task=args.task, ) dt = (time.perf_counter() - t0) / len(chunk) for (k, im), aux in zip(chunk, auxes): yield k, im, aux, dt
# ── main ────────────────────────────────────────────────────────────────────
def main(): p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) s = p.add_mutually_exclusive_group(required=True) s.add_argument("--image", help="path, URL, or glob ('scans/*.jpg')") s.add_argument("--dataset", help="Hub dataset repo id (streamed)") p.add_argument("--config") p.add_argument("--split", default="train") p.add_argument("--image-col", default="image") p.add_argument("--id-col", default=None, help="stable id column; falls back to row index") p.add_argument("--query", required=True, help="a CLASS NAME, not an instruction") p.add_argument("--task", default="segmentation", choices=["segmentation", "detection"]) p.add_argument("--out", default=None, help="where results go. A path ending .json/.jsonl/.parquet writes that file " "locally; anything else is treated as a Hub dataset repo id. Omit for " "stdout + previews only.") p.add_argument("--json", action="store_true", help="also print the records as JSON on stdout (for piping / agents)") p.add_argument("--private", action="store_true") p.add_argument("--limit", type=int, default=None, help="3 for a sense check") p.add_argument("--preview", action="store_true", help="save annotated JPEGs") p.add_argument("--preview-dir", default="./falcon-preview") p.add_argument("--max-dim", type=int, default=1024) p.add_argument("--max-new-tokens", type=int, default=200) p.add_argument("--chunk", type=int, default=16) p.add_argument("--backend", default="auto", choices=["auto", "mlx", "torch"]) p.add_argument("--engine", default="auto", choices=["auto", "batch", "paged"]) p.add_argument("--cudagraph", action="store_true", help="opt IN -- can OOM the host on small flavors") p.add_argument("--mlx-mem-fraction", type=float, default=0.55) args = p.parse_args()
backend = pick_backend(args.backend) if backend == "mlx": guard_mlx_memory(args.mlx_mem_fraction) use_paged = args.engine == "paged" or (args.engine == "auto" and backend == "torch") if use_paged and backend == "mlx": print("paged engine is CUDA-only -- using batch", flush=True) use_paged = False print(f"backend={backend} engine={'paged' if use_paged else 'batch'} query={args.query!r}", flush=True)
from falcon_perception import PERCEPTION_MODEL_ID, build_prompt_for_task, load_and_prepare_model from pycocotools import mask as mask_utils
kw = {} if backend == "torch": from falcon_perception import setup_torch_config
setup_torch_config() kw = {"compile": False} # dynamic image shapes break Inductor t = time.perf_counter() model, tokenizer, model_args = load_and_prepare_model( hf_model_id=PERCEPTION_MODEL_ID, dtype="float16" if backend == "mlx" else "bfloat16", backend=backend, **kw, ) print(f"model loaded in {time.perf_counter() - t:.1f}s", flush=True) prompt = build_prompt_for_task(args.query, args.task)
items = src_images(args.image) if args.image else src_dataset( args.dataset, args.config, args.split, args.image_col, args.id_col) if args.limit: # islice STOPS the iterator; a filter would keep streaming the whole corpus. items = itertools.islice(items, args.limit)
gen = (run_paged(model, tokenizer, items, prompt, args) if use_paged else run_batch(model, tokenizer, items, prompt, args, backend, model_args.max_seq_len))
records, n, t0 = [], 0, time.perf_counter() for key, im, aux, dt in gen: W, H = im.size boxes = pair_bboxes(aux.bboxes_raw) rles = list(aux.masks_rle) 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(rles): # rectangularity -- the only triage signal available try: m = rles[i] if isinstance(m.get("counts"), str): m = {**m, "counts": m["counts"].encode()} r = min(float(mask_utils.area(m)) / max(a * W * H, 1.0), 1.0) except Exception: r = 0.0 rect.append(r) n += 1 print(f"[{n}] {key[:55]:55s} {len(bbox):2d} inst {dt:.2f}s", flush=True) if args.preview: print(f" -> {save_preview(key, im, boxes, rles, args.preview_dir)}", flush=True) if args.out or args.json: records.append({ "image": im, "image_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([ {**m, "counts": m["counts"].decode() if isinstance(m.get("counts"), bytes) else m.get("counts")} for m in rles ]), })
wall = time.perf_counter() - t0 print(f"\n{n} images in {wall:.1f}s ({n / max(wall, 1e-9):.2f} img/s)", flush=True)
# --- local file output: everything except the PIL image, which is not serialisable def plain(recs): return [{k: v for k, v in r.items() if k != "image"} for r in recs]
if args.json: print(json.dumps(plain(records), indent=2), flush=True)
if args.out and args.out.endswith((".json", ".jsonl", ".parquet")): rows = plain(records) if args.out.endswith(".json"): pathlib.Path(args.out).write_text(json.dumps(rows, indent=2)) elif args.out.endswith(".jsonl"): pathlib.Path(args.out).write_text("".join(json.dumps(r) + "\n" for r in rows)) else: import pyarrow as pa import pyarrow.parquet as pq
pq.write_table(pa.Table.from_pylist(rows), args.out, compression="zstd") total = sum(r["n_instances"] for r in rows) print(f"{total} instances -> {args.out}", flush=True) return
if args.out: from datasets import Dataset, Features, Image as ImageFeat, Sequence as SeqFeat, Value
feats = Features({ "image": ImageFeat(), "image_id": Value("string"), "width": Value("int32"), "height": Value("int32"), "objects": {"bbox": SeqFeat(SeqFeat(Value("float32"))), "category": SeqFeat(Value("int64")), "area": SeqFeat(Value("float32")), "rectangularity": SeqFeat(Value("float32"))}, "n_instances": Value("int32"), "masks_rle": Value("string"), }) Dataset.from_list(records, features=feats).push_to_hub(args.out, private=args.private) print(f"{sum(r['n_instances'] for r in records)} instances -> {args.out}", flush=True) print(f"\nNEXT: validate-hf-dataset.py {args.out} --bbox-format yolo", flush=True)
main()README.md+76-1
falcon-perception-bucket.pyAdded+239
falcon-perception.pyAdded+429