Datasets:

ArXiv:
License:
OpenEmbed-Data / tools /openembed_data /rebuild_edit.py
Yanqing0327's picture
OpenEmbed data
2f92e95
Raw History Blame Contribute Delete
24.5 kB
#!/usr/bin/env python3
"""Rebuild OpenEmbed's training shards of an image-editing corpus from its released records (approximately).
An editing set's folder (editing/<name>/) holds set.json, records.parquet and shards.parquet, and images/ours-*.tar
for the images we ship. Each record is one tf.train.Example of our training shards with byte features only: the two
images (jpg, the source image; cand_jpg, the edited image) and the texts (query_text, the edit instruction, and the
other stored strings), in the stored feature order. An image is either our bytes (a member of images/ours-*.tar, read
from the set's folder and checked against its sha256) or a pointer into the upstream dataset at a pinned revision: a
parquet cell, a member of a tar archive published in parts, or a file at a URL (Pico-Banana: Apple's CDN and the Open
Images mirror, with fallbacks). A record whose image the release can neither point to nor ship (pointer "unavailable",
Pico-Banana's licence forbids sharing our altered copies) is left out of the rebuilt shard and reported. Our training
images were re-encoded when we converted
the corpora, so upstream images are re-encoded the same way here (RGB, resized to our size with bicubic when the size
differs, JPEG quality 95 4:2:0 with Pillow): the result matches our training image approximately, not byte for byte,
and so do the rebuilt shards; each set's README.md and set.json give the pixel differences measured on its own
samples. Texts, feature order and record order are exact.
pip install pyarrow huggingface_hub Pillow crc32c
python tools/openembed_data/rebuild_edit.py --set-dir editing/magicbrush --out shards/ --cache hf_cache/
Tar-based sources (GPT-Image-Edit, SEED-Data-Edit, ImgEdit) are read as a stream once, part after part, before the
shards are built; the images the records need are re-encoded on the way and kept in --spill (about the size of our
images). --delete-parts removes each downloaded part once it has been read. Parquet sources are read per shard: each
upstream column chunk a shard needs is streamed once, up to its last needed row, and only the needed cells are kept, so
memory stays small even when a file is one row group of tens of GB (ScaleEdit).
"""
from __future__ import annotations
import argparse
import collections
import concurrent.futures as cf
import hashlib
import io
import json
import multiprocessing
import os
import sys
import tarfile
import time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import rebuild_shards as RS # noqa: E402 Sources (parquet cells, the set's tar members), TFRecord framing
RESAMPLE = {"bicubic": 3, "bilinear": 2, "lanczos": 1, "box": 4, "nearest": 0}
def transform(raw: bytes, tr: dict) -> bytes:
"""Our converter's re-encoding: decode, convert, resize to our size when it differs, JPEG."""
from PIL import Image
Image.MAX_IMAGE_PIXELS = None
with Image.open(io.BytesIO(raw)) as im:
im = im.convert(tr.get("mode", "RGB"))
if tr.get("rotate_cw"): # degrees clockwise (Open Images "Rotation"), before the resize
im = im.rotate(-int(tr["rotate_cw"]), expand=True)
size = tuple(int(x) for x in tr["resize"])
if im.size != size:
im = im.resize(size, RESAMPLE[tr.get("resample", "bicubic")])
out = io.BytesIO()
im.save(out, format="JPEG", **tr.get("save", {}))
return out.getvalue()
def _ld(field: int, payload: bytes) -> bytes:
return RS._varint(field << 3 | 2) + RS._varint(len(payload)) + payload
def encode_example(order: list, values: dict) -> bytes:
"""tf.train.Example with one bytes_list feature per key, in the stored key order."""
return _ld(1, b"".join(_ld(1, _ld(1, k.encode()) + _ld(2, _ld(1, b"".join(_ld(1, v) for v in values[k]))))
for k in order))
def spill_name(src: dict) -> str:
key = json.dumps([src["repo"], src["revision"], src["member"], src["transform"]], sort_keys=True)
return hashlib.sha1(key.encode()).hexdigest() + ".jpg"
class Parts(io.RawIOBase):
"""The concatenation of an archive's parts, downloaded one after another (and deleted after use if asked)."""
def __init__(self, repo, revision, parts, cache, delete):
self.repo, self.revision, self.parts, self.cache, self.delete = repo, revision, list(parts), cache, delete
self.i, self.fh, self.path = -1, None, None
self.downloaded = 0
def _next(self):
from huggingface_hub import hf_hub_download
if self.fh is not None:
self.fh.close()
if self.delete:
os.remove(self.path)
self.i += 1
if self.i >= len(self.parts):
self.fh = None
return False
local = os.path.join(self.cache, self.repo.replace("/", "__"), self.parts[self.i])
if os.path.isfile(local): # already in the cache folder (downloaded or copied)
self.path = local
else:
self.path = hf_hub_download(self.repo, self.parts[self.i], repo_type="dataset", revision=self.revision,
local_dir=os.path.join(self.cache, self.repo.replace("/", "__")))
self.downloaded += os.path.getsize(self.path)
self.fh = open(self.path, "rb")
return True
def readable(self):
return True
def readinto(self, b):
while True:
if self.fh is None and not self._next():
return 0
n = self.fh.readinto(b)
if n:
return n
if not self._next():
return 0
def prepass_tars(records, cache: str, spill: str, delete: bool) -> dict:
"""Read every tar archive the records point into once; re-encode the needed members into the spill folder."""
need = collections.defaultdict(lambda: collections.defaultdict(list)) # archive -> member -> [pointer]
for r in records:
for k in ("jpg_ptr", "cand_jpg_ptr"):
src = json.loads(r[k])
if src["type"] == "hf_split_tar_member" and not os.path.exists(os.path.join(spill, spill_name(src))):
need[(src["repo"], src["revision"], tuple(src["parts"]), src.get("compression", "none"))][src["member"]].append(src)
stats = {"archives": len(need), "members": 0, "downloaded": 0}
os.makedirs(spill, exist_ok=True)
for (repo, rev, parts, comp), members in need.items():
t0 = time.time()
raw = Parts(repo, rev, parts, cache, delete)
stream = io.BufferedReader(raw, buffer_size=16 << 20)
if comp == "gzip":
try:
from isal import igzip as gz # much faster when installed (pip install isal)
except ImportError:
import gzip as gz
stream = gz.GzipFile(fileobj=stream)
left = set(members)
with tarfile.open(fileobj=stream, mode="r|") as tf:
for m in tf:
if not left:
break
if not m.isfile() or m.name not in left:
continue
data = tf.extractfile(m).read()
for src in members[m.name]:
p = os.path.join(spill, spill_name(src))
if os.path.exists(p):
continue
if src.get("upstream_sha256") and hashlib.sha256(data).hexdigest() != src["upstream_sha256"]:
open(p + ".changed", "w").close() # reported per record when the shard is built
continue
with open(p + ".tmp", "wb") as fh:
fh.write(transform(data, src["transform"]))
os.replace(p + ".tmp", p)
left.discard(m.name)
stats["members"] += 1
if raw.fh is not None: # stopped early (every needed member read): close the open part
raw.fh.close()
if delete:
os.remove(raw.path)
raw.fh = None
stats["downloaded"] += raw.downloaded
for name in left: # members the archive no longer has: reported per record
for src in members[name]:
open(os.path.join(spill, spill_name(src)) + ".missing", "w").close()
stats["members_missing"] = stats.get("members_missing", 0) + len(left)
print(f"{parts[0]} ...: {len(members)} members in {time.time() - t0:.0f}s", flush=True)
return stats
def fetch_url(src: dict, cache: str) -> bytes:
"""An image published at a URL (no revision to pin): its first URL, else the fallbacks, kept in <cache>/url/."""
import urllib.request
urls = [src["url"]] + list(src.get("fallback_urls", []))
p = os.path.join(cache, "url", hashlib.sha1(src["url"].encode()).hexdigest())
if os.path.exists(p):
with open(p, "rb") as fh:
return fh.read()
last = None
for u in urls:
for attempt in range(4):
try:
req = urllib.request.Request(u, headers={"User-Agent": "openembed-rebuild/1.0"})
with urllib.request.urlopen(req, timeout=120) as r:
data = r.read()
os.makedirs(os.path.dirname(p), exist_ok=True)
with open(p + ".tmp", "wb") as fh:
fh.write(data)
os.replace(p + ".tmp", p)
return data
except Exception as e: # noqa: BLE001 (a 404 on the first URL moves to the fallback)
last = e
if getattr(e, "code", None) in (403, 404, 410):
break
time.sleep(2 * (attempt + 1))
raise FileNotFoundError(f"{src['url']}: not fetched ({last})")
def fill_instructions(rec: list, spec: dict, cache: str) -> collections.Counter:
"""Records released without the source's instructions (set.json "text_source"; Pico-Banana, whose terms do not let
us redistribute its content): each record's "query_text_source" names a line of the source's JSON-lines file
(0-based, as Python reads text lines) and one of its fields. The instruction is taken from there unchanged and
checked against the sha256 of our training text; a record whose line or text is not found is left out of the
rebuild and reported."""
st = collections.Counter()
data = fetch_url({"url": spec["url"]}, cache)
md5 = hashlib.md5(data).hexdigest()
if spec.get("md5") and md5 != spec["md5"]:
print(f"warning: {spec['url']} changed since our build (md5 {md5}, ours {spec['md5']}); every instruction is "
"still checked against its sha256", flush=True)
want = collections.defaultdict(list)
for i, r in enumerate(rec):
p = json.loads(r["query_text_source"])
want[p["line"]].append((i, p))
got = {}
for n, line in enumerate(io.TextIOWrapper(io.BytesIO(data), encoding="utf-8")):
if n in want:
d = json.loads(line)
for i, p in want[n]:
t = d.get(p["field"])
if isinstance(t, str) and hashlib.sha256(t.encode("utf-8")).hexdigest() == p["sha256"]:
got[i] = t
for i, r in enumerate(rec):
if i in got:
texts = json.loads(r["texts"])
texts["query_text"] = [got[i]]
r["texts"] = json.dumps(texts)
st["instructions_fetched"] += 1
else:
r["texts"] = None
st["instructions_missing"] += 1
return st
class Unavailable(Exception):
"""A record whose image the release can neither point to nor ship (see its pointer's reason)."""
class UpstreamChanged(Exception):
"""The upstream bytes at the pointer differ from those we matched (the pointer's upstream_sha256)."""
class ShippedDamaged(Exception):
"""Our shipped image does not have the sha256 of our training bytes (a damaged download)."""
_FILE_OK: dict = {}
def check_upstream_file(srcs, src: dict) -> None:
"""A parquet cell whose pointer carries upstream_file_sha256: the downloaded file must have that sha256 (checked
once per file and process)."""
want = src.get("upstream_file_sha256")
if not want:
return
p = srcs.path(src)
ok = _FILE_OK.get((p, want))
if ok is None:
h = hashlib.sha256()
with open(p, "rb") as fh:
for chunk in iter(lambda: fh.read(8 << 20), b""):
h.update(chunk)
ok = _FILE_OK[(p, want)] = h.hexdigest() == want
if not ok:
raise UpstreamChanged(f"{src['file']}: the upstream file differs from the one we matched (upstream_file_sha256)")
def check_upstream(raw: bytes, src: dict) -> bytes:
want = src.get("upstream_sha256")
if want and hashlib.sha256(raw).hexdigest() != want:
raise UpstreamChanged("the upstream image differs from the one we matched (upstream_sha256)")
return raw
def prefetch_cells(srcs, rows) -> dict:
"""The upstream parquet cells a shard's records need: {(file path, row in the file, column): cell bytes}.
Sources.raw reads a whole row-group column for a cell and keeps one column, which suits small row groups. ScaleEdit's
files are one row group of 26-28 GB with the source and the edited image in two columns, so cell by cell every record
read about 13 GB twice (2026-11-12: two shards ran 79 minutes without finishing, 33 GB per process). Here each
(file, row group, column) the shard needs is streamed once in small batches, up to its last needed row, keeping only
those cells. A pointer whose file cannot be fetched or read is left out; image_bytes then reads it through
Sources.raw, which raises the same error inside the per-record handling, so it is reported as before."""
import bisect
import pyarrow.parquet as pq
need, meta = collections.defaultdict(dict), {}
for r in rows:
for key in ("jpg", "cand_jpg"):
src = json.loads(r[f"{key}_ptr"])
if src["type"] != "hf_parquet_cell":
continue
try:
p = srcs.path(src)
if p not in meta:
# pre_buffer=False: pyarrow 26 pre-buffers by default, which loads the whole column chunk (16 GB on
# ScaleEdit) before the first batch; unbuffered pages stream (1.4 GB for 3,000 rows, 2026-11-12)
pf = pq.ParquetFile(p, buffer_size=8 << 20, pre_buffer=False)
starts, n = [], 0
for i in range(pf.metadata.num_row_groups):
starts.append(n)
n += pf.metadata.row_group(i).num_rows
meta[p] = (pf, starts)
except Exception: # noqa: BLE001 (reported per record by image_bytes)
continue
starts = meta[p][1]
rg = bisect.bisect_right(starts, src["row"]) - 1
need[(p, rg, src["column"])][src["row"] - starts[rg]] = tuple(src.get("path", []))
cells = {}
for (p, rg, col), want in sorted(need.items()):
pf, starts = meta[p]
last, i = max(want), 0
try:
for batch in pf.iter_batches(batch_size=32, row_groups=[rg], columns=[col], use_threads=False):
arr = batch.column(0)
for j in range(i, i + batch.num_rows):
if j in want:
cell = arr[j - i].as_py()
for k in want[j]:
cell = cell[k]
cells[(p, starts[rg] + j, col)] = cell if isinstance(cell, bytes) else bytes(cell)
i += batch.num_rows
if i > last:
break
except Exception: # noqa: BLE001 (a damaged file: the cells not read here are read, and reported, per record)
pass
return cells
def build_shard(job) -> dict:
set_dir, cache, spill, out, shard, rows, want_records = job
srcs = RS.Sources(cache, set_dir)
cells = prefetch_cells(srcs, rows)
counts = collections.Counter()
buf = bytearray()
skipped = []
problems = []
for r in rows:
if r["texts"] is None: # its instruction was not found in the source
problems.append({"shard": shard, "ordinal": r["ordinal"], "field": "query_text",
"pointer": r.get("query_text_source"), "reason": "instruction not found in the source, or changed"})
counts["instruction_missing"] += 1
continue
order = r["feature_order"].split(",")
values = {k: [v.encode("utf-8") for v in vs] for k, vs in json.loads(r["texts"]).items()}
bad = False
for key in ("jpg", "cand_jpg"):
try:
values[key] = [image_bytes(json.loads(r[f"{key}_ptr"]), r, key, srcs, spill, cache, shard, counts, cells)]
except Exception as e: # noqa: BLE001 (unavailable, gone, changed upstream, damaged download, ...)
kind = {Unavailable: "unavailable", UpstreamChanged: "upstream changed", ShippedDamaged: "shipped image damaged",
FileNotFoundError: "not fetched"}.get(type(e), type(e).__name__)
counts[kind.replace(" ", "_")] += 1
problems.append({"shard": shard, "ordinal": r["ordinal"], "field": key, "pointer": r[f"{key}_ptr"],
"reason": f"{kind}: {str(e)[:200]}"})
bad = True
if not bad:
buf += RS.frame_record(encode_example(order, values))
if len(rows) != want_records:
raise ValueError(f"{shard}: {len(rows)} records, shards.parquet says {want_records}")
skipped = sorted({p["ordinal"] for p in problems})
name = shard if not skipped else shard + ".incomplete" # never a complete-looking shard with records missing
if out:
os.makedirs(out, exist_ok=True)
with open(os.path.join(out, name + ".tmp"), "wb") as fh:
fh.write(buf)
os.replace(os.path.join(out, name + ".tmp"), os.path.join(out, name))
return {"shard": shard, "written_as": name, "records": len(rows) - len(skipped), "skipped": len(skipped),
"bytes": len(buf), "skipped_examples": [(p["ordinal"], p["reason"]) for p in problems[:5]], "problems": problems,
**counts}
def image_bytes(src, r, key, srcs, spill, cache, shard, counts, cells=None) -> bytes:
if src["type"] == "unavailable":
counts["unavailable"] += 1
raise Unavailable(f"record {r['ordinal']} {key}: {src.get('reason', 'not available')}")
if src["type"] == "url": # a published URL (Pico-Banana: Apple's CDN, Open Images)
b = transform(check_upstream(fetch_url(src, cache), src), src["transform"])
counts["upstream"] += 1
return b
if src["type"] == "local_tar_member": # our bytes, shipped in the set's folder
b = srcs.raw(src)
if hashlib.sha256(b).hexdigest() != r[f"{key}_sha256"]:
raise ShippedDamaged(f"{src.get('file')} member {src.get('member')}: sha256 differs from our training image")
counts["ours"] += 1
return b
if src["type"] == "hf_split_tar_member":
p = os.path.join(spill, spill_name(src))
if os.path.exists(p + ".changed"):
raise UpstreamChanged(f"{src['member']}: the archive member differs from the one we matched (upstream_sha256)")
if os.path.exists(p + ".missing") or not os.path.exists(p):
raise FileNotFoundError(f"{src['member']}: not in the archive")
with open(p, "rb") as fh:
counts["upstream"] += 1
return fh.read()
check_upstream_file(srcs, src) # a parquet cell at the pinned revision
raw = cells.get((srcs.path(src), src["row"], src["column"])) if cells else None
b = transform(check_upstream(raw if raw is not None else srcs.raw(src), src), src["transform"])
counts["upstream"] += 1
return b
def main():
ap = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
ap.add_argument("--set-dir", required=True, help="the editing set's folder (with set.json and records.parquet)")
ap.add_argument("--out", help="folder for the rebuilt shards (none: build and check only)")
ap.add_argument("--cache", default="hf_cache", help="folder for the downloaded upstream files")
ap.add_argument("--spill", help="folder for the re-encoded images of tar sources (default <cache>/spill/<set>)")
ap.add_argument("--shards", help="comma-separated shard names (default: all)")
ap.add_argument("--procs", type=int, default=os.cpu_count() or 4)
ap.add_argument("--delete-parts", action="store_true", help="delete each downloaded tar part after reading it")
ap.add_argument("--problems", help="JSON lines, one per image or instruction that could not be rebuilt (default: "
"<out>/rebuild_problems.jsonl, else ./rebuild_edit_problems.jsonl)")
args = ap.parse_args()
import pyarrow.parquet as pq
set_dir = os.path.abspath(args.set_dir)
meta = json.load(open(os.path.join(set_dir, "set.json")))
# the set's name in the summary line and in every problem line: the released set.json names it by dataset_id
name = meta.get("dataset_id") or meta.get("name") or os.path.basename(set_dir)
spill = args.spill or os.path.join(args.cache, "spill", meta.get("name", os.path.basename(set_dir)))
shards = {r["shard"]: r["records"] for r in pq.read_table(os.path.join(set_dir, "shards.parquet")).to_pylist()}
pick = set(args.shards.split(",")) if args.shards else set(shards)
# with --shards, only those shards' records are read (all 4.46M of ScaleEdit took about 11 GB here for two shards)
rec = pq.read_table(os.path.join(set_dir, "records.parquet"),
filters=[("shard", "in", sorted(pick))] if args.shards else None).to_pylist()
if meta.get("text_source"):
rec = [r for r in rec if r["shard"] in pick]
st_t = fill_instructions(rec, meta["text_source"], args.cache)
print(f"instructions from {meta['text_source']['url']}: {st_t['instructions_fetched']} fetched, "
f"{st_t['instructions_missing']} not found", flush=True)
by_shard = collections.defaultdict(list)
for r in rec:
if r["shard"] in pick:
by_shard[r["shard"]].append(r)
t0 = time.time()
st = prepass_tars([r for rs in by_shard.values() for r in rs], args.cache, spill, args.delete_parts)
jobs = [(set_dir, args.cache, spill, args.out, s, sorted(by_shard[s], key=lambda r: r["ordinal"]), shards[s])
for s in sorted(by_shard)]
done, problems = collections.Counter(), []
# workers are started fresh (spawn), not forked: a forked worker inherits this process's records and copies them as
# it touches them (15 GB per worker on ScaleEdit); each job carries only its own shard's records
with cf.ProcessPoolExecutor(max(1, min(args.procs, len(jobs))), mp_context=multiprocessing.get_context("spawn")) as ex:
for res in ex.map(build_shard, jobs):
problems += res.pop("problems")
done.update({k: v for k, v in res.items() if isinstance(v, int)})
print(f"{res['shard']}: {res['records']} records ({res.get('upstream', 0)} upstream images, "
f"{res.get('ours', 0)} ours)" + (f"; {res['skipped']} skipped: {res['skipped_examples'][:2]}"
if res.get('skipped') else ""), flush=True)
print(json.dumps({"set": name, "shards": len(jobs), **done, "tar_archives": st["archives"],
"seconds": round(time.time() - t0)}), flush=True)
if problems:
path = args.problems or (os.path.join(args.out, "rebuild_problems.jsonl") if args.out else "rebuild_edit_problems.jsonl")
with open(path, "w") as fh:
for p in problems:
fh.write(json.dumps({"set": name, **p}) + "\n")
print(f"INCOMPLETE: {len({(p['shard'], p['ordinal']) for p in problems})} records left out; every image or "
f"instruction that could not be rebuilt is listed in {path}; their shards are written as <shard>.incomplete",
flush=True)
return 1
return 0
if __name__ == "__main__":
sys.exit(main())