Spaces:
Paused
Paused
Update the demo from the repository
Browse filesFiles changed (5)
14 unmodified lines151617181920128 unmodified lines14915015115215315414 unmodified lines16917017117217317417517614 unmodified lines- COCO (`detection-datasets/coco`, Parquet): every image with at least one annotatedobject in the listed training shards, in shard order, named by its COCO image id, soa teacher's labels can be set against COCO's own on the same images."""import argparse128 unmodified linesyield linedef prepare(config, out):out = Path(out)out.mkdir(parents=True, exist_ok=True)14 unmodified linesquota = settings["images"] - counts.get(source, 0)if quota <= 0:continuewith manifest.open("a") as handle:for line in makers[source](settings, quota):handle.write(json.dumps(line) + "\n")handle.flush()return manifest14 unmodified lines15161718192021222324128 unmodified lines15315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025114 unmodified lines26626726826927027127227327427527627727827914 unmodified lines- COCO (`detection-datasets/coco`, Parquet): every image with at least one annotatedobject in the listed training shards, in shard order, named by its COCO image id, soa teacher's labels can be set against COCO's own on the same images.- Generated (a source with a "model", a text-to-image model on fal.ai): one image perprompt, which names a few COCO categories and fills the config's template from its listsof media, places and so on (`scene`); the manifest line keeps the prompt and thecategories it names."""import argparse128 unmodified linesyield lineFAL = "https://fal.run/"PLURALS = {"person": "people", "knife": "knives", "mouse": "mice", "sheep": "sheep"}def plural(name):"""A COCO category name in the plural ("skis" and "scissors" already are)."""if name in PLURALS or name.endswith(("skis", "scissors")):return PLURALS.get(name, name)return name + ("es" if name.endswith(("s", "x", "ch", "sh")) else "s")def scene(settings, rng):"""One prompt of a generated source and the categories it names.The prompt is `settings["template"]` with `{things}` and one drawn phrase per list in`settings["choices"]` (a phrase list may hold "" for nothing). The things are one to`max_categories` COCO categories, each with a count from `counts` and, withprobability `attribute_share`, a modifier from `attributes`. With probability`group_share` the categories come from one of `groups` (categories that occurtogether), otherwise from all 80."""from crescent_moon.tasks import COCO_NAMESmany = rng.randint(1, settings["max_categories"])groups = settings.get("groups")if groups and rng.random() < settings["group_share"]:pool = rng.choice(groups)asked = rng.sample(pool, min(many, len(pool)))else:asked = rng.sample(COCO_NAMES, many)things = []for name in asked:count = rng.choice(settings["counts"])modifier = ""if settings.get("attributes") and rng.random() < settings["attribute_share"]:modifier = rng.choice(settings["attributes"]) + " "# "a" is the only count that takes a singular noun, and its article agrees.if count == "a":count = "an" if (modifier + name)[0] in "aeiou" else "a"things.append(f"{count} {modifier}{name}")else:things.append(f"{count} {modifier}{plural(name)}")listed = things[0] if len(things) == 1 else ", ".join(things[:-1]) + " and " + things[-1]drawn = {key: rng.choice(phrases) for key, phrases in settings["choices"].items()}prompt = " ".join(settings["template"].format(things=listed, **drawn).split())return prompt.replace(" ,", ","), askeddef generated(source, settings, out, quota, max_side, rng, existing):"""Images from a text-to-image model on fal.ai (`settings["model"]`), one per `scene`,in a size drawn from `sizes`; the manifest line keeps the prompt and the categoriesit names. The key is read from the FAL_KEY environment variable."""import osfrom concurrent.futures import ThreadPoolExecutorkey = os.environ["FAL_KEY"]scenes = [(*scene(settings, rng), rng.choice(settings["sizes"])) for _ in range(settings["images"])]wanted = [(i, s) for i, s in enumerate(scenes) if f"{source}/{i:05d}" not in existing]def one(job):index, (prompt, _, size) = jobbody = {"prompt": prompt,"seed": index,"num_images": 1,"image_size": size,**settings["request"],}request = urllib.request.Request(FAL + settings["model"],data=json.dumps(body).encode(),headers={"Authorization": f"Key {key}", "Content-Type": "application/json"},)try:with urllib.request.urlopen(request, timeout=180) as response:url = json.load(response)["images"][0]["url"]with urllib.request.urlopen(url, timeout=180) as response:return response.read()except (OSError, KeyError, IndexError, ValueError):return Nonewith ThreadPoolExecutor(settings.get("workers", 8)) as pool:for (index, (prompt, asked, _)), data in zip(wanted[:quota], pool.map(one, wanted[:quota]), strict=True):line = data and save(data, out, source, f"{index:05d}", max_side, existing)if line:yield line | {"prompt": prompt, "asked": asked}def prepare(config, out):out = Path(out)out.mkdir(parents=True, exist_ok=True)14 unmodified linesquota = settings["images"] - counts.get(source, 0)if quota <= 0:continue# A source with a "model" is generated under its own name; the others are fixed.make = makers.get(source) or (lambda s, q, source=source: generated(source, s, out, q, config["max_side"], rng, existing))with manifest.open("a") as handle:for line in make(settings, quota):handle.write(json.dumps(line) + "\n")handle.flush()return manifest
17 unmodified lines181920212223243 unmodified lines282930313233343545 unmodified lines8182838485864 unmodified lines91929394959655 unmodified lines15215315415515615779 unmodified lines23723823924024124217 unmodified linesfrom crescent_moon.metrics import summarizefrom crescent_moon.tasks import (coco_samples,lvis_samples,mot_samples,refcoco_m_samples,3 unmodified linesdef hub_files(dataset):from huggingface_hub import hf_hub_downloadreturn [hf_hub_download(dataset["repo"], name, repo_type=dataset["repo_type"], revision=dataset["revision"]45 unmodified linesdataset["images"],config["seed"],exclude_images=dataset.get("exclude_images", 0),)extract_images(paths, built, image_folder)elif dataset["kind"] == "refcoco_m":4 unmodified linesbuilt = mot_dataset_samples(dataset, image_folder)elif dataset["kind"] == "voc":built = voc_tar_samples(paths[0], dataset, config["seed"], image_folder)else:raise ValueError(f"Unknown dataset kind {dataset['kind']!r}")samples += [sample | {"dataset": dataset["name"]} for sample in built]55 unmodified linesreturn builtdef fetch_image(reference, folder):"""Open an image from the folder, downloading a URL into it first.79 unmodified linesfrom crescent_moon.train_slots import SlotDetectorreturn SlotDetector(**model, device=device)raise ValueError(f"Unknown adapter {adapter!r}")17 unmodified lines1819202122232425263 unmodified lines30313233343536373839404145 unmodified lines878889909192934 unmodified lines989910010110210310410510610710810911055 unmodified lines16616716816917017117217317417517617717817918018118218318418518618718879 unmodified lines26826927027127227327427527627717 unmodified linesfrom crescent_moon.metrics import summarizefrom crescent_moon.tasks import (coco_json_samples,coco_samples,labelled_samples,lvis_samples,mot_samples,refcoco_m_samples,3 unmodified linesdef hub_files(dataset):"""Local paths of a dataset's files: from its Hub repository, or as given when it hasnone (paths on the volume)."""from huggingface_hub import hf_hub_downloadif "repo" not in dataset:return dataset["files"]return [hf_hub_download(dataset["repo"], name, repo_type=dataset["repo_type"], revision=dataset["revision"]45 unmodified linesdataset["images"],config["seed"],exclude_images=dataset.get("exclude_images", 0),categories=dataset.get("categories"),)extract_images(paths, built, image_folder)elif dataset["kind"] == "refcoco_m":4 unmodified linesbuilt = mot_dataset_samples(dataset, image_folder)elif dataset["kind"] == "voc":built = voc_tar_samples(paths[0], dataset, config["seed"], image_folder)elif dataset["kind"] == "labelled":replies = [json.loads(line) for line in Path(paths[0]).read_text().splitlines()]built = labelled_samples(replies, dataset["images"], config["seed"], dataset["image_folder"])elif dataset["kind"] == "coco_json":built = coco_zip_samples(paths[0], dataset, config["seed"], image_folder)else:raise ValueError(f"Unknown dataset kind {dataset['kind']!r}")samples += [sample | {"dataset": dataset["name"]} for sample in built]55 unmodified linesreturn builtdef coco_zip_samples(path, dataset, seed, image_folder):"""Samples from a zip that holds a COCO-format annotation file (`annotations`, a pathinside the zip) and its images (under `image_root`), with the sampled images writtento the image folder."""import zipfilewith zipfile.ZipFile(path) as archive:annotations = json.loads(archive.read(dataset["annotations"]))built = coco_json_samples(annotations, dataset["images"], seed, dataset["name"])for sample in built:target = Path(image_folder) / sample["image"]if not target.exists():target.parent.mkdir(parents=True, exist_ok=True)target.write_bytes(archive.read(f"{dataset['image_root']}/{target.name}"))return builtdef fetch_image(reference, folder):"""Open an image from the folder, downloading a URL into it first.79 unmodified linesfrom crescent_moon.train_slots import SlotDetectorreturn SlotDetector(**model, device=device)if adapter == "yolo":from crescent_moon.yolo import YoloDetectorreturn YoloDetector(**model, device=device)raise ValueError(f"Unknown adapter {adapter!r}")
156 unmodified lines1571581591601611621631641651661671681695 unmodified lines1751761771781791803 unmodified lines184185186187188189190191192193194195156 unmodified linesreturn samplesdef coco_samples(rows, images, seed, names=COCO_NAMES, exclude_images=0):"""Prompt each COCO image with the categories annotated in it.`rows` follow detection-datasets/coco: `objects` holds parallel `category`indices into `names` and `bbox` as [x0, y0, x1, y1]. `exclude_images` leaves outthe images that a sample of that size with the same seed would take, so a tuningsplit never overlaps the evaluation split."""rows = [row for row in sorted(rows, key=lambda row: row["image_id"]) if row["objects"]["bbox"]]if exclude_images:5 unmodified linesby_category = defaultdict(list)for category, box in zip(row["objects"]["category"], row["objects"]["bbox"], strict=True):by_category[category].append(list(box))samples.append({"image_id": row["image_id"],3 unmodified lines"queries": [{"phrase": names[category],"kind": "present","boxes": boxes,"exhaustive": True,"group": "",}for category, boxes in sorted(by_category.items())],})156 unmodified lines1571581591601611621631641651661671681691701715 unmodified lines1771781791801811821831841851861873 unmodified lines191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262156 unmodified linesreturn samplesdef coco_samples(rows, images, seed, names=COCO_NAMES, exclude_images=0, categories=None):"""Prompt each COCO image with the categories annotated in it.`rows` follow detection-datasets/coco: `objects` holds parallel `category`indices into `names` and `bbox` as [x0, y0, x1, y1]. `exclude_images` leaves outthe images that a sample of that size with the same seed would take, so a tuningsplit never overlaps the evaluation split. `categories` prompts each image withexactly that many: its annotated ones first (the lowest indices when it has more),then absent ones drawn with the seed, to measure time against the number asked."""rows = [row for row in sorted(rows, key=lambda row: row["image_id"]) if row["objects"]["bbox"]]if exclude_images:5 unmodified linesby_category = defaultdict(list)for category, box in zip(row["objects"]["category"], row["objects"]["bbox"], strict=True):by_category[category].append(list(box))asked = sorted(by_category.items())if categories is not None:absent = [c for c in range(len(names)) if c not in by_category]more = rng.sample(absent, max(0, categories - len(asked)))asked = asked[:categories] + [(category, []) for category in sorted(more)]samples.append({"image_id": row["image_id"],3 unmodified lines"queries": [{"phrase": names[category],"kind": "present" if boxes else "absent","boxes": boxes,"exhaustive": True,"group": "",}for category, boxes in asked],})return samplesdef coco_json_samples(annotations, images, seed, folder):"""Prompt each sampled image of a COCO-format annotation file with the categoriesannotated in it. `folder` is where the images lie under the image folder."""names = {c["id"]: c["name"] for c in annotations["categories"]}by_image = defaultdict(lambda: defaultdict(list))for a in annotations["annotations"]:x, y, w, h = a["bbox"]by_image[a["image_id"]][names[a["category_id"]]].append([x, y, x + w, y + h])rows = sorted((i for i in annotations["images"] if i["id"] in by_image), key=lambda i: i["id"])return [{"image_id": row["id"],"image": f"{folder}/{row['file_name']}","width": row["width"],"height": row["height"],"queries": [{"phrase": name, "kind": "present", "boxes": boxes, "exhaustive": True, "group": ""}for name, boxes in sorted(by_image[row["id"]].items())],}for row in random.Random(seed).sample(rows, min(images, len(rows)))]def labelled_samples(replies, images, seed, folder):"""Prompt each sampled image with the categories a teacher labelled in it.`replies` are the records `crescent_moon.teacher` writes ({"image_id", "width","height", "objects": [{"label", "box"}]}, boxes in pixels); `folder` holds`<image_id>.jpg`. The teacher's boxes are the truth, so the scores measure agreementwith it."""rows = sorted((r for r in replies if "error" not in r and r["objects"]), key=lambda r: r["image_id"])samples = []for row in random.Random(seed).sample(rows, min(images, len(rows))):by_label = defaultdict(list)for obj in row["objects"]:by_label[obj["label"]].append(obj["box"])samples.append({"image_id": row["image_id"],"image": f"{folder}/{row['image_id']}.jpg","width": row["width"],"height": row["height"],"queries": [{"phrase": name,"kind": "present","boxes": boxes,"exhaustive": True,"group": "",}for name, boxes in sorted(by_label.items())],})
1234567891011121314151617181920212223242526272829303132333435363738394041"""A closed-set detector through Ultralytics, as a reference for speed and size.
YOLO models trained on COCO return all 80 categories in one pass, with a confidence perbox; their class indices follow COCO's order, as `tasks.COCO_NAMES` does."""
import time
from crescent_moon.tasks import COCO_NAMES
class YoloDetector: def __init__(self, name, device, confidence=0.001): from ultralytics import YOLO
self.model = YOLO(name) self.device, self.confidence = device, confidence
def detect(self, image, phrases): """Return {"boxes", "scores": per-phrase lists, "shared_seconds", "phrase_seconds"}: one pass over the image, its boxes handed to the phrases that name their category.""" start = time.perf_counter() (result,) = self.model.predict( image, conf=self.confidence, device=self.device, verbose=False ) found = result.boxes corners, scores, classes = found.xyxy.tolist(), found.conf.tolist(), found.cls.tolist() shared = time.perf_counter() - start boxes = [[] for _ in phrases] kept = [[] for _ in phrases] for box, score, index in zip(corners, scores, classes, strict=True): for position, phrase in enumerate(phrases): if phrase == COCO_NAMES[int(index)]: boxes[position].append(box) kept[position].append(score) return { "boxes": boxes, "scores": kept, "shared_seconds": shared, "phrase_seconds": [0.0] * len(phrases), }381 unmodified lines38238338438538638738838939039177 unmodified lines469470471472473474475476477381 unmodified linesconst qkv = storage(device, rows * 3 * T.dim * 4);const layer = tensors["text.blocks.0.mlp.fc1"];const now = () => performance.now() / 1000;const time = async (make, repeats) => {const start = now();device.queue.submit([encode(device, Array.from({ length: repeats }, make).flat())]);await device.queue.onSubmittedWorkDone();return (now() - start) / repeats;};const product = (tuning) => {77 unmodified linesif (kept) return kept;} catch { /* no storage, or nothing usable in it: measure */ }let tuning;try {tuning = await tune(device, manifest, tensors);} catch (error) {return { ...TUNING, seconds: {}, error: String(error) };}try { localStorage.setItem(key, JSON.stringify(tuning)); } catch { /* not kept */ }381 unmodified lines38238338438538638738838939039139239339439539677 unmodified lines474475476477478479480481482483484485486381 unmodified linesconst qkv = storage(device, rows * 3 * T.dim * 4);const layer = tensors["text.blocks.0.mlp.fc1"];const now = () => performance.now() / 1000;// A lost device answers at once and does no work, so its times mean nothing.let lost = null;device.lost.then((info) => { lost = info; });const time = async (make, repeats) => {const start = now();device.queue.submit([encode(device, Array.from({ length: repeats }, make).flat())]);await device.queue.onSubmittedWorkDone();await Promise.resolve();if (lost) throw new Error(`the GPU device was lost while timing kernels (${lost.message || lost.reason})`);return (now() - start) / repeats;};const product = (tuning) => {77 unmodified linesif (kept) return kept;} catch { /* no storage, or nothing usable in it: measure */ }let tuning;let lost = false;device.lost.then(() => { lost = true; });try {tuning = await tune(device, manifest, tensors);} catch (error) {await Promise.resolve();if (lost) throw error; // nothing runs on a lost devicereturn { ...TUNING, seconds: {}, error: String(error) };}try { localStorage.setItem(key, JSON.stringify(tuning)); } catch { /* not kept */ }
crescent_moon/images.py+104-1
crescent_moon/run.py+35
crescent_moon/tasks.py+70-3
crescent_moon/yolo.pyAdded+41
web/model.js+9