#!/usr/bin/env python3 """Rebuild OpenEmbed training shards from released records (text sets, and image sets via pinned source pointers). Each dataset folder ``//`` holds set.json, records.parquet (every stored field of every training record; images as pointers into a pinned public source, with the sha256 and length of our training bytes), filters.parquet and shards.parquet (md5 / crc32c per shard). This script re-creates every record (tf.train.Example, RecordV2 schema of the training code), writes the TFRecord shards and checks each record's sha256 and each shard's md5 and crc32c. Text sets need nothing else, except a few released without their texts (set.json "text_source"), whose texts are fetched from the pinned public source; image sets fetch their source files from the pinned revision. The few images that no public source reproduces ship in the set's own folder (a ``local_tar_member`` pointer with ``"base": "set"`` names a tar file relative to that folder) and are read from there. pip install pyarrow huggingface_hub crc32c Pillow==12.3.0 python tools/openembed_data/rebuild_shards.py --out shards/ --sets text/allnli python tools/openembed_data/rebuild_shards.py --no-write --set-dir text/allnli Provenance. Each record names the shard and record of the earlier conversion it came from. Our training shards carry our internal storage location in that string; the release writes ``openembed://...`` instead, so a rebuild equals our training shards in every other byte and is checked against the ``*_public`` values. Given the internal prefixes (OPENEMBED_PROVENANCE_MAP, a JSON list of [public prefix, internal prefix] pairs, with ``--check train``) the rebuild is byte-identical to the training shards. """ from __future__ import annotations import argparse import base64 import collections import concurrent.futures as cf import hashlib import io import json import os import shutil import struct import sys import tempfile import time FIELDS = ( ("record_key", "int", "scalar"), ("dataset_id", "str", "scalar"), ("wemm_type", "str", "scalar"), ("task_subtype", "str", "scalar"), ("modality_sig", "str", "scalar"), ("query_image", "bytes", "scalar"), ("query_text", "str", "scalar"), ("instruction", "str", "scalar"), ("target_image", "bytes", "scalar"), ("target_text", "str", "scalar"), ("neg_texts", "str", "list"), ("neg_images", "bytes", "list"), ("neg_scores", "float", "list"), ("pos_score", "float", "scalar"), ("pos_rank", "int", "scalar"), ("graded_score", "float", "scalar"), ("target_key", "int", "scalar"), ("group_key", "int", "scalar"), ("license", "str", "scalar"), ("provenance", "str", "scalar"), ) PILLOW_FOR_REENCODING = "12.3.0" # the version that reproduces our converters' JPEG bytes SCALARS = ("record_key", "dataset_id", "wemm_type", "task_subtype", "modality_sig", "query_text", "instruction", "target_text", "pos_score", "pos_rank", "graded_score", "target_key", "group_key", "license") # ----------------------------------------------------------------------------------------------- CRC-32C, framing def _crc32c_backend(): try: import crc32c as _c return lambda data, value=0: _c.crc32c(data, value), "crc32c" except ImportError: pass try: import google_crc32c as _g return lambda data, value=0: _g.extend(value, data), "google-crc32c" except ImportError: pass table = [] for i in range(256): c = i for _ in range(8): c = (c >> 1) ^ 0x82F63B78 if c & 1 else c >> 1 table.append(c) def slow(data, value=0): c = value ^ 0xFFFFFFFF for b in bytes(data): c = table[(c ^ b) & 0xFF] ^ (c >> 8) return c ^ 0xFFFFFFFF return slow, "pure-python (slow)" CRC32C, CRC32C_BACKEND = _crc32c_backend() def masked_crc32c(data: bytes) -> int: c = CRC32C(data) return (((c >> 15) | (c << 17)) + 0xA282EAD8) & 0xFFFFFFFF def frame_record(payload: bytes) -> bytes: ln = struct.pack(" bytes: if n < 0: n += 1 << 64 out = bytearray() while True: b = n & 0x7F n >>= 7 if n: out.append(b | 0x80) else: out.append(b) return bytes(out) def _ld(field: int, payload: bytes) -> bytes: return _varint((field << 3) | 2) + _varint(len(payload)) + payload def _feature(kind: str, values: list) -> bytes: if kind in ("str", "bytes"): return _ld(1, b"".join(_ld(1, v.encode("utf-8") if isinstance(v, str) else bytes(v)) for v in values)) if kind == "float": return _ld(2, _ld(1, struct.pack(f"<{len(values)}f", *values)) if values else b"") if kind == "int": return _ld(3, _ld(1, b"".join(_varint(int(v)) for v in values)) if values else b"") raise ValueError(kind) def encode_record(rec: dict) -> bytes: """RecordV2 field mapping -> serialized tf.train.Example (features sorted by name, packed numeric lists).""" entries = [] for name, kind, card in sorted(FIELDS): v = rec[name] entries.append(_ld(1, _ld(1, name.encode("utf-8")) + _ld(2, _feature(kind, [v] if card == "scalar" else list(v))))) return _ld(1, b"".join(entries)) # ----------------------------------------------------------------------------------------------- image sources class Sources: """Fetches image bytes from pinned sources; each source file is downloaded once per process.""" def __init__(self, cache_dir: str, set_dir: str | None = None): self.cache_dir = cache_dir self.set_dir = set_dir # the dataset's folder, for images shipped in it ("base": "set") self.files: dict[tuple, str] = {} self.parquet: dict[str, object] = {} self.zips: dict[str, object] = {} self.tars: dict[str, dict] = {} self.columns: "collections.OrderedDict" = collections.OrderedDict() # (file, row group, column) -> cells self.downloaded = 0 def path(self, src: dict) -> str: key = (src.get("repo"), src.get("revision"), src.get("file"), src.get("url"), src.get("base")) p = self.files.get(key) if p is None: if src["type"].startswith("hf_"): local = os.path.join(self.cache_dir, src["repo"].replace("/", "__"), src["file"]) if os.path.isfile(local): # already in the cache folder (downloaded or copied) p = local else: from huggingface_hub import hf_hub_download p = hf_hub_download(src["repo"], src["file"], repo_type="dataset", revision=src["revision"], local_dir=os.path.join(self.cache_dir, src["repo"].replace("/", "__"))) self.downloaded += os.path.getsize(p) elif src["type"] == "local_tar_member" and src.get("base") == "set": # shipped in the set's folder if not self.set_dir: raise ValueError(f"{src['file']}: the pointer names a file in the dataset's folder; none given") p = os.path.join(self.set_dir, src["file"]) if not os.path.exists(p): raise FileNotFoundError(f"{p}: this file is part of the dataset's folder; download the whole folder") elif src["type"] in ("local_tar_member", "archive_member"): p = os.path.join(self.cache_dir, src["file"]) if not os.path.exists(p): raise FileNotFoundError(f"{p}: put the official file {src['file']} here ({src.get('url', '')})") else: raise ValueError(f"unknown source type {src['type']}") self.files[key] = p return p def raw(self, src: dict) -> bytes: t = src["type"] if t == "hf_zip_member": import zipfile p = self.path(src) z = self.zips.get(p) or self.zips.setdefault(p, zipfile.ZipFile(p)) return z.read(src["member"]) if t == "hf_parquet_cell": import bisect import pyarrow.parquet as pq p = self.path(src) ent = self.parquet.get(p) if ent is None: pf = pq.ParquetFile(p) starts, n = [], 0 for i in range(pf.metadata.num_row_groups): starts.append(n) n += pf.metadata.row_group(i).num_rows ent = self.parquet[p] = {"pf": pf, "starts": starts} rg = bisect.bisect_right(ent["starts"], src["row"]) - 1 # row: index in the file key = (p, rg, src["column"]) col = self.columns.get(key) if col is None: # a row group's column can be the whole file (one row group of ~1 GB); while len(self.columns) >= 1: # fetches come sorted by file and row, so one at a time is enough self.columns.popitem(last=False) col = self.columns[key] = ent["pf"].read_row_group(rg, columns=[src["column"]]).column(0) else: self.columns.move_to_end(key) cell = col[src["row"] - ent["starts"][rg]].as_py() for k in src.get("path", []): cell = cell[k] return cell if isinstance(cell, bytes) else bytes(cell) if t == "archive_member": return self.archive_member(src) if t == "hf_arrow_cell": # a datasets save_to_disk file (Arrow IPC stream) import pyarrow as pa p = self.path(src) ent = self.parquet.get(p) if ent is None: if len(self.parquet) > 4: self.parquet.clear() ent = self.parquet[p] = {"table": pa.ipc.open_stream(pa.memory_map(p)).read_all()} cell = ent["table"].column(src["column"])[src["row"]].as_py() for k in src.get("path", []): cell = cell[k] return cell if isinstance(cell, bytes) else bytes(cell) if t == "local_tar_member": return self.tar_member(self.path(src), src["member"], src.get("offset"), src.get("size")) raise ValueError(f"unknown source type {t}") def archive_member(self, src: dict) -> bytes: """A member of a published archive: read from the archive in the cache folder (zip, or uncompressed tar), or from its extracted copy (/ or //).""" name, member = src["archive"], src["member"] p = os.path.join(self.cache_dir, name) if os.path.isfile(p): if name.endswith(".zip"): import zipfile z = self.zips.get(p) or self.zips.setdefault(p, zipfile.ZipFile(p)) return z.read(member) if name.endswith(".tar"): return self.tar_member(p, member, None, None) stem = name for ext in (".tar.gz", ".tgz", ".tar", ".zip"): if stem.endswith(ext): stem = stem[: -len(ext)] break for q in (os.path.join(self.cache_dir, member), os.path.join(self.cache_dir, stem, member)): if os.path.isfile(q): with open(q, "rb") as fh: return fh.read() raise FileNotFoundError(f"{member}: put {name} in {self.cache_dir} (a zip or an uncompressed tar is read as " f"is; extract a compressed tar there): {src.get('how', '')}") def tar_member(self, p: str, member: str, off, size) -> bytes: """A tar member: at its recorded data offset when the header there names it, else by a name index.""" ent = self.tars.get(p) if ent is None: ent = self.tars[p] = {"fh": open(p, "rb"), "index": None} fh = ent["fh"] if off is not None and size is not None and off >= 512: fh.seek(off - 512) # the member's header block precedes its data hdr = fh.read(512) name = hdr[:100].split(b"\0", 1)[0].decode("utf-8", "replace") prefix = hdr[345:500].split(b"\0", 1)[0].decode("utf-8", "replace") if hdr[257:263] == b"ustar\x00" else "" if (prefix + "/" + name if prefix else name) == member: return fh.read(size) if ent["index"] is None: # another copy of the archive: find the member by name import tarfile with tarfile.open(p) as tf: ent["index"] = {m.name: (m.offset_data, m.size) for m in tf if m.isfile()} off, size = ent["index"][member] fh.seek(off) return fh.read(size) def video_frames(self, src: dict, tr: dict) -> list: """The k frames our uCO3D converter took from one video (PyAV decode at the centres of k equal segments, RGB, LANCZOS downscale to at most max_pixels, JPEG); the last video's frames are kept.""" key = (src.get("repo"), src.get("file"), src.get("member"), tr["k"], tr["max_pixels"]) if getattr(self, "_video", (None,))[0] == key: return self._video[1] import av from PIL import Image data, k, images = self.raw(src), int(tr["k"]), [] with av.open(io.BytesIO(data)) as container: stream = container.streams.video[0] tb = float(stream.time_base) if stream.time_base else 0.0 duration = float(stream.duration * stream.time_base) if stream.duration and tb else \ (container.duration / 1e6 if container.duration else 0.0) if duration > 0 and tb > 0: for j in range(k): t = (j + 0.5) * duration / k container.seek(int(t / tb), stream=stream, backward=True, any_frame=False) for f in container.decode(stream): if f.pts is None or f.pts * tb >= t - 1e-3: images.append(f.to_image()) break if not images: # no usable timing: decode in order with av.open(io.BytesIO(data)) as container: frames = list(container.decode(container.streams.video[0])) picks = sorted({min(len(frames) - 1, int((j + 0.5) * len(frames) / k)) for j in range(k)}) if frames else [] images = [frames[q].to_image() for q in picks] out = [] for im in images: im = im.convert("RGB") w, h = im.size if w * h > tr["max_pixels"]: f = (tr["max_pixels"] / (w * h)) ** 0.5 im = im.resize((max(2, int(w * f)), max(2, int(h * f))), Image.LANCZOS) buf = io.BytesIO() im.save(buf, format="JPEG", **tr.get("jpeg", {})) out.append(buf.getvalue()) self._video = (key, out) return out def image(self, src: dict) -> bytes: tr = src.get("transform") or {"op": "none"} if tr["op"] == "video_frame": return self.video_frames(src, tr)[int(tr["index"])] b = self.raw(src) if tr["op"] == "none": return b if tr["op"] == "pil_jpeg": import PIL from PIL import Image if PIL.__version__ != PILLOW_FOR_REENCODING and not getattr(Sources, "_warned", False): Sources._warned = True print(f"warning: images are re-encoded with Pillow {PIL.__version__}; the recorded bytes were made with " f"Pillow {PILLOW_FOR_REENCODING} (pip install Pillow=={PILLOW_FOR_REENCODING}), other versions can " f"give other bytes and fail the sha256 check", file=sys.stderr, flush=True) im = Image.open(io.BytesIO(b)) if tr.get("exif_transpose") and im.getexif().get(0x0112) is not None: from PIL import ImageOps # as the datasets library decodes images: EXIF im.load() # orientation applied when the tag is present im = ImageOps.exif_transpose(im) if tr.get("mode"): im = im.convert(tr["mode"]) if tr.get("crop"): # (x0, y0, x1, y1), after the mode conversion im = im.crop(tuple(int(v) for v in tr["crop"])) out = io.BytesIO() im.save(out, format="JPEG", **tr.get("save", {})) return out.getvalue() if tr["op"] == "pil_rgba_on_white_png": # MapQA: RGBA composited on white, saved as PNG from PIL import Image with Image.open(io.BytesIO(b)) as im: im = im.convert("RGBA") rgb = Image.new("RGB", im.size, tuple(tr.get("background", (255, 255, 255)))) rgb.paste(im, mask=im.split()[3]) out = io.BytesIO() rgb.save(out, format="PNG") return out.getvalue() raise ValueError(f"unknown transform {tr['op']}") # ----------------------------------------------------------------------------------------------- rebuild def _b64(b: bytes) -> str: return base64.b64encode(b).decode() def to_train(p: str, pmap: list) -> str: """Public provenance -> training provenance: every occurrence of each public prefix, longest prefix first.""" for public, internal in sorted(pmap, key=lambda x: -len(x[0])): p = p.replace(public, internal) return p def order_key(srcs: "Sources", src_json: str) -> tuple: """Fetch order: by source file, then by position in it (zip entry offset, parquet column and row, member).""" try: src = json.loads(src_json) pos = src.get("row", src.get("offset", 0)) if src["type"] in ("hf_zip_member",) or (src["type"] == "archive_member" and src["archive"].endswith(".zip")): p = srcs.path(src) if src["type"] == "hf_zip_member" else os.path.join(srcs.cache_dir, src["archive"]) if os.path.isfile(p): import zipfile z = srcs.zips.get(p) or srcs.zips.setdefault(p, zipfile.ZipFile(p)) pos = z.getinfo(src["member"]).header_offset return (src.get("repo") or "", src.get("file") or src.get("archive") or "", src.get("column") or "", pos if isinstance(pos, int) else 0, src.get("member") or "", int((src.get("transform") or {}).get("index", 0))) except Exception: # noqa: BLE001 - an unusual pointer is fetched last; image() reports its problem return ("~", "", "", 0, "", 0) # ----------------------------------------------------------------------------------------------- shared-source pre-pass # Records are spread over the shards in random order, so in a hard-negative page set every shard touches most row groups # of the source parquet files (colpali_pdf_hn: 255 of 1,235 row groups per shard, 937 GB read for a 55 GB source), and # the 4 frames of a uCO3D video sit in 4 shards (each video read and decoded 4 times). For such sets a pre-pass fetches # every pointer once in source order (one task per parquet row group, one per zip file: each row group or video is read # once) and keeps the image bytes in a temporary folder; the shard pass then takes them from there. Every image is still # checked against its recorded sha256 in the shard pass, and a pointer the pre-pass could not fetch is fetched there. PREPASS_TYPES = ("hf_parquet_cell", "hf_zip_member") def _ptr_key(src_json: str) -> str: return hashlib.sha1(src_json.encode("utf-8")).hexdigest() def image_pointers(r: dict): for col in ("query_image_source", "target_image_source"): if r.get(col): yield r[col] yield from (s for s in (r.get("neg_images_source") or []) if s) def _source_path(job) -> tuple: """(local path or None, bytes downloaded) of one pointer's source file (downloaded into the cache if missing).""" cache_dir, src = job s = Sources(cache_dir) try: return s.path(src), s.downloaded except Exception: # noqa: BLE001 - the shard pass fetches it again and reports the problem return None, 0 def plan_prepass(by_shard: dict, cache_dir: str, mode: str, procs: int) -> tuple[list, float, int]: """Pointers worth fetching in the pre-pass, grouped into tasks (one per parquet row group and column, one per zip file), the re-read factor (source units the shard pass would read, counted once per shard that touches them, over the distinct units) and the bytes downloaded while planning (missing source files, fetched in parallel).""" if mode == "never": return [], 1.0, 0 import bisect parsed, files = [], {} for shard, rows in by_shard.items(): for r in rows: for sj in image_pointers(r): try: src = json.loads(sj) except ValueError: continue if src.get("type") in PREPASS_TYPES: fk = (src.get("repo"), src.get("revision"), src.get("file"), src.get("url")) files.setdefault(fk, src) parsed.append((shard, sj, src, fk)) if not parsed: return [], 1.0, 0 with cf.ThreadPoolExecutor(max_workers=max(1, min(8, procs, len(files)))) as tp: got = dict(zip(files, tp.map(_source_path, [(cache_dir, s) for s in files.values()]))) downloaded = sum(n for _, n in got.values()) starts = {} unit_shards = collections.defaultdict(set) unit_ptrs = collections.defaultdict(set) for shard, sj, src, fk in parsed: p = got[fk][0] if p is None: continue try: if src["type"] == "hf_parquet_cell": if p not in starts: import pyarrow.parquet as pq md = pq.ParquetFile(p).metadata acc, n = [], 0 for i in range(md.num_row_groups): acc.append(n) n += md.row_group(i).num_rows starts[p] = acc unit = (p, src.get("column"), bisect.bisect_right(starts[p], src["row"]) - 1) task = unit # one task per row group and column else: unit, task = (p, src["member"]), (p,) # one task per zip file (its videos in entry order) except Exception: # noqa: BLE001 - left to the shard pass, which reports it continue unit_shards[unit].add(shard) unit_ptrs[task].add(sj) if not unit_shards: return [], 1.0, downloaded factor = sum(len(v) for v in unit_shards.values()) / len(unit_shards) if mode == "auto" and factor < 1.5: return [], factor, downloaded srcs = Sources(cache_dir) tasks = [sorted(v, key=lambda sj: order_key(srcs, sj)) for v in unit_ptrs.values()] return sorted(tasks, key=len, reverse=True), factor, downloaded def prepass_file(job) -> tuple[dict, int]: """Fetch one source file's pointers in order and append the image bytes to out_path; {pointer key: (offset, len)}.""" pointers, cache_dir, out_path = job srcs = Sources(cache_dir) index, off = {}, 0 with open(out_path, "wb") as fh: for sj in pointers: try: b = srcs.image(json.loads(sj)) except Exception: # noqa: BLE001 - fetched again (and reported) by the shard pass continue fh.write(b) index[_ptr_key(sj)] = (off, len(b)) off += len(b) return index, srcs.downloaded def rebuild_shard(job) -> dict: """Rebuild one shard. A record goes into the written shard only when every image was fetched with the recorded sha256 and length and the record re-serializes to its recorded sha256; any other record is left out and listed in res["problems"] (shard, ordinal, field, pointer, reason), and the shard is then written as .incomplete.""" shard, rows, pmap, check, out, cache_dir = job[:6] spill = job[6] if len(job) > 6 else {} # pointer key -> (pre-pass file, offset, length) set_dir = job[7] if len(job) > 7 else None rows = sorted(rows, key=lambda r: r["ordinal"]) res = {"shard": shard, "records": len(rows), "record_ok": 0, "record_bad": 0, "image_missing": 0, "image_bad": 0, "ordinals_contiguous": [r["ordinal"] for r in rows] == list(range(len(rows))), "examples": [], "problems": [], "written": 0} srcs = Sources(cache_dir, set_dir) spill_fh = {} def problem(r, field, pointer, reason): res["problems"].append({"shard": shard, "ordinal": r["ordinal"], "field": field, "pointer": pointer, "reason": reason}) def from_spill(src_json): ent = spill.get(_ptr_key(src_json)) if ent is None: return None p, off, n = ent fh_s = spill_fh.get(p) or spill_fh.setdefault(p, open(p, "rb")) fh_s.seek(off) return fh_s.read(n) modes = ["train", "public"] if check == "both" else [check] # both: one pass, images fetched once sums = {m: [hashlib.md5(), 0, 0] for m in modes} fh = None if out is not None: path = os.path.join(out, shard) os.makedirs(os.path.dirname(path), exist_ok=True) fh = open(path + ".partial", "wb") def image(src_json, sha, ln): """(bytes, None) or (None, reason).""" if not ln: return b"", None try: b = from_spill(src_json) if spill else None if b is None: b = srcs.image(json.loads(src_json)) except Exception as e: # noqa: BLE001 res["image_missing"] += 1 return None, f"not fetched: {type(e).__name__}: {str(e)[:200]}" if len(b) != ln or hashlib.sha256(b).hexdigest() != sha: res["image_bad"] += 1 return None, f"differs from the training image (length {len(b)}, expected {ln}; sha256 differs)" return b, None def build(r, got, bad): if r.get("_problem"): # e.g. its texts were not found in the source problem(r, r["_problem"][0], r["_problem"][1], r["_problem"][2]) bad = True if bad: res["record_bad"] += 1 if len(res["examples"]) < 3: res["examples"].append(r["ordinal"]) return rec = {k: r[k] for k in SCALARS} rec["neg_texts"] = list(r["neg_texts"] or []) rec["neg_scores"] = list(r["neg_scores"] or []) rec["query_image"] = got.get("query_image", b"") rec["target_image"] = got.get("target_image", b"") rec["neg_images"] = [got.get(("neg", j), b"") for j in range(len(r.get("neg_images_source") or []))] frames, ok = {}, True for m in modes: rec["provenance"] = to_train(r["provenance"], pmap) if m == "train" else r["provenance"] rec["license"] = r.get("_license_train", r["license"]) if m == "train" else r["license"] payload = encode_record(rec) want = r["record_sha256"] if m == "train" else r["record_sha256_public"] if hashlib.sha256(payload).hexdigest() != want: ok = False problem(r, "record", None, f"the rebuilt record differs from record_sha256{'' if m == 'train' else '_public'}") frames[m] = frame_record(payload) if not ok: res["record_bad"] += 1 if len(res["examples"]) < 3: res["examples"].append(r["ordinal"]) return for m, frame in frames.items(): h = sums[m] h[0].update(frame) h[1] = CRC32C(frame, h[1]) h[2] += len(frame) if fh is not None: fh.write(frames[modes[-1]]) res["written"] += 1 res["record_ok"] += 1 fields = [("query_image", "query_image_source", "query_image_sha256", "query_image_len"), ("target_image", "target_image_source", "target_image_sha256", "target_image_len")] CHUNK = 8192 # records whose images are fetched together, in source order (a typical # shard at once, so each source file or row group is read once per shard) for start in range(0, len(rows), CHUNK): chunk = rows[start:start + CHUNK] jobs = [] for i, r in enumerate(chunk): for f, sk, hk, lk in fields: if r.get(lk): jobs.append((r.get(sk), i, f, r.get(hk), r.get(lk))) for j, (sj, h, n) in enumerate(zip(r.get("neg_images_source") or [], r.get("neg_images_sha256") or [], r.get("neg_images_len") or [])): if n: jobs.append((sj, i, ("neg", j), h, n)) got, bad = collections.defaultdict(dict), set() for sj, i, f, h, n in sorted(jobs, key=lambda x: order_key(srcs, x[0]) if x[0] else ("~", "", "", 0, "", 0)): b, why = image(sj, h, n) if why is not None: bad.add(i) problem(chunk[i], f if isinstance(f, str) else f"neg_images[{f[1]}]", sj, why) else: got[i][f] = b for i, r in enumerate(chunk): build(r, got[i], i in bad) for f_s in spill_fh.values(): f_s.close() if fh is not None: fh.close() final = path if res["record_ok"] == len(rows) else path + ".incomplete" os.replace(path + ".partial", final) res["written_as"] = os.path.basename(final) for m, (h, c, n) in sums.items(): res[m] = {"md5": _b64(h.digest()), "crc32c": _b64(c.to_bytes(4, "big")), "bytes": n} res.update(res[modes[-1]]) res["downloaded"] = srcs.downloaded return res # ------------------------------------------------------------- texts fetched from their public source (2026-11-12) # Some text sets are released without their texts (the publishers' terms): each record names its query, positive and # negative items in the source at a pinned revision (records.parquet column "text_source"; set.json "text_source" # describes the source), and the texts are re-made here as our builders made them, then cleaned as the training # adapter did. Every record is still checked against its sha256 afterwards. MEDIA_PLACEHOLDERS = ("<|image_1|>", "", "<|image_pad|>", "<|IMAGE|>", "<|video_pad|>", "<|VIDEO|>", "