diff --git a/mm/build_data.py b/mm/build_data.py new file mode 100644 index 0000000..4d13b64 --- /dev/null +++ b/mm/build_data.py @@ -0,0 +1,259 @@ +"""Build a unified token stream from CC3M webdataset shards. + +Two passes: + pass 1 collect captions, train a 16k byte-level BPE + pass 2 image -> 256 VQ tokens (LlamaGen VQ-16), caption -> BPE ids, + emit one fixed-length interleaved sequence per pair + +Why 16k text vocab instead of GPT-2's 50257: measured throughput on this GPU +drops from 81k tok/s to 56k tok/s purely from the output head at 66k vocab. +CC3M captions are short and simple, so 16k is plenty. + +Vocab layout (must match model.py): + [0, 16000) text BPE + [16000, 32384) image VQ codes + 32384.. specials +""" +import argparse +import io +import json +import os +import re +import sys +import tarfile + +import numpy as np +import torch +import torch.nn.functional as F +from PIL import Image +from tokenizers import Tokenizer, decoders, models, pre_tokenizers, trainers + +TEXT_VOCAB = 16000 +IMAGE_VOCAB = 16384 +IMAGE_OFFSET = TEXT_VOCAB +PAD, BOS, EOS, IMG_S, IMG_E, TXT_S, TXT_E = range(32384, 32391) +VOCAB_SIZE = 32391 +IMG_SIDE = 256 +LATENT = IMG_SIDE // 16 # 16 +N_IMG_TOKENS = LATENT * LATENT # 256 +SEQ_LEN = 320 + +def iter_samples(shard_paths): + """Yield (key, jpeg_bytes, caption) from webdataset tars, streaming by key. + + Tolerates truncated shards (downloads still in flight): stops that shard + and moves on instead of raising. + """ + for path in shard_paths: + try: + tf = tarfile.open(path) + except Exception as e: + print(f" skip {path}: {e}") + continue + cur_key, img, txt = None, None, None + try: + for m in tf: + if not m.isfile(): + continue + base = os.path.basename(m.name) + key, ext = os.path.splitext(base) + ext = ext.lower() + if ext not in (".jpg", ".jpeg", ".png", ".txt", ".json"): + continue + if key != cur_key: + if cur_key is not None and img is not None and txt: + yield cur_key, img, txt + cur_key, img, txt = key, None, None + if ext in (".jpg", ".jpeg", ".png"): + img = tf.extractfile(m).read() + elif ext == ".txt": + raw = tf.extractfile(m).read() + txt = raw.decode("utf-8", errors="ignore").strip() + elif ext == ".json": + try: + meta = json.loads(tf.extractfile(m).read().decode("utf-8", errors="ignore")) + if not txt and isinstance(meta, dict) and "caption" in meta: + c = meta["caption"] + txt = c if isinstance(c, str) else (c[0] if c else "") + except Exception: + pass + if cur_key is not None and img is not None and txt: + yield cur_key, img, txt + except Exception as e: + print(f" partial {os.path.basename(path)}: {type(e).__name__} (ok, moving on)") + finally: + tf.close() + + +def train_tokenizer(shards, out_path, vocab_size=TEXT_VOCAB): + tok = Tokenizer(models.BPE(unk_token="")) + tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False) + tok.decoder = decoders.ByteLevel() + trainer = trainers.BpeTrainer( + vocab_size=vocab_size, + special_tokens=[""], + initial_alphabet=pre_tokenizers.ByteLevel.alphabet(), + min_frequency=2, + ) + + def gen(): + for _, _, cap in iter_samples(shards): + yield cap + + tok.train_from_iterator(gen(), trainer) + tok.save(out_path) + print(f"tokenizer saved: {out_path} vocab={tok.get_vocab_size()}") + return tok + + +def load_vq(ckpt_path, device): + sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "vendor", "llamagen_vq")) + from vq_model import VQ_16 + + model = VQ_16() + sd = torch.load(ckpt_path, map_location="cpu", weights_only=False) + if isinstance(sd, dict) and "model" in sd: + sd = sd["model"] + missing, unexpected = model.load_state_dict(sd, strict=False) + if missing: + print(f" warn: {len(missing)} missing keys, e.g. {missing[:3]}") + model.eval().to(device) + return model + + +@torch.no_grad() +def encode_images(vq, blobs, device, batch=48): + imgs = [] + for b in blobs: + try: + im = Image.open(io.BytesIO(b)).convert("RGB") + except Exception: + imgs.append(None) + continue + w, h = im.size + s = IMG_SIDE / min(w, h) + im = im.resize((max(IMG_SIDE, int(round(w * s))), max(IMG_SIDE, int(round(h * s)))), Image.BICUBIC) + w, h = im.size + left, top = (w - IMG_SIDE) // 2, (h - IMG_SIDE) // 2 + im = im.crop((left, top, left + IMG_SIDE, top + IMG_SIDE)) + arr = np.asarray(im, dtype=np.float32) / 127.5 - 1.0 + imgs.append(arr) + + valid = [(i, a) for i, a in enumerate(imgs) if a is not None] + out = [None] * len(imgs) + for s in range(0, len(valid), batch): + chunk = valid[s : s + batch] + x = torch.from_numpy(np.stack([a for _, a in chunk])).permute(0, 3, 1, 2).to(device) + _, _, info = vq.encode(x) + idx = info[2].view(len(chunk), N_IMG_TOKENS).cpu().numpy() + for (orig_i, _), row in zip(chunk, idx): + out[orig_i] = row.astype(np.uint16) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--shards", nargs="+", required=True) + ap.add_argument("--vq_ckpt", type=str, default="../ckpt/vq_ds16_t2i.pt") + ap.add_argument("--out_dir", type=str, default="../data_mm") + ap.add_argument("--val_frac", type=float, default=0.02) + ap.add_argument("--img_first_prob", type=float, default=0.5) + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--device", type=str, default="cuda") + ap.add_argument("--img_side", type=int, default=256, choices=[128, 256, 512], + help="128 -> 8x8=64 image tokens, 256 -> 16x16=256") + ap.add_argument("--seq_len", type=int, default=0, help="0 = auto from img_side") + ap.add_argument("--filter", type=str, default=None, + help="keep only captions containing this word (word-boundary, plural ok)") + args = ap.parse_args() + + global IMG_SIDE, LATENT, N_IMG_TOKENS, SEQ_LEN + IMG_SIDE = args.img_side + LATENT = IMG_SIDE // 16 + N_IMG_TOKENS = LATENT * LATENT + if args.seq_len > 0: + SEQ_LEN = args.seq_len + else: + SEQ_LEN = N_IMG_TOKENS + 64 + print(f"image {IMG_SIDE}px -> {LATENT}x{LATENT} = {N_IMG_TOKENS} tokens, seq_len {SEQ_LEN}") + + os.makedirs(args.out_dir, exist_ok=True) + tok_path = os.path.join(args.out_dir, "tokenizer.json") + if os.path.exists(tok_path): + print(f"reusing tokenizer {tok_path}") + tok = Tokenizer.from_file(tok_path) + else: + print("pass 1: training tokenizer") + tok = train_tokenizer(args.shards, tok_path) + + print("pass 2: encoding image-text pairs") + vq = load_vq(args.vq_ckpt, args.device) + + rng = np.random.default_rng(0) + train_rows, val_rows = [], [] + n_ok = n_skip = 0 + batch_blobs, batch_caps = [], [] + + def flush(): + nonlocal n_ok, n_skip + if not batch_blobs: + return + codes = encode_images(vq, batch_blobs, args.device) + for c, cap in zip(codes, batch_caps): + if c is None: + n_skip += 1 + continue + ids = tok.encode(cap).ids + ids = [i for i in ids if i < TEXT_VOCAB][: SEQ_LEN - N_IMG_TOKENS - 8] + if len(ids) < 2: + n_skip += 1 + continue + img = (c + IMAGE_OFFSET).astype(np.uint16) + if rng.random() < args.img_first_prob: + seq = [BOS, IMG_S, *img.tolist(), IMG_E, TXT_S, *ids, TXT_E, EOS] + else: + seq = [BOS, TXT_S, *ids, TXT_E, IMG_S, *img.tolist(), IMG_E, EOS] + row = np.full(SEQ_LEN, PAD, dtype=np.uint16) + row[: len(seq)] = seq + (val_rows if rng.random() < args.val_frac else train_rows).append(row) + n_ok += 1 + batch_blobs.clear() + batch_caps.clear() + + filt = re.compile(r"\b" + re.escape(args.filter) + r"s?\b", re.I) if args.filter else None + if filt: + print(f"filter: {filt.pattern}") + + for _, blob, cap in iter_samples(args.shards): + if filt and not filt.search(cap): + continue + batch_blobs.append(blob) + batch_caps.append(cap) + if len(batch_blobs) >= 256: + flush() + if n_ok % 2560 == 0 and n_ok > 0: + print(f" encoded {n_ok} skipped {n_skip}") + if args.limit and n_ok >= args.limit: + break + flush() + + tr = np.stack(train_rows) if train_rows else np.zeros((0, SEQ_LEN), np.uint16) + va = np.stack(val_rows) if val_rows else np.zeros((0, SEQ_LEN), np.uint16) + tr.tofile(os.path.join(args.out_dir, "train.bin")) + va.tofile(os.path.join(args.out_dir, "val.bin")) + meta = { + "seq_len": SEQ_LEN, "vocab_size": VOCAB_SIZE, "text_vocab": TEXT_VOCAB, + "image_vocab": IMAGE_VOCAB, "image_offset": IMAGE_OFFSET, + "n_img_tokens": N_IMG_TOKENS, "img_side": IMG_SIDE, + "pad": PAD, "bos": BOS, "eos": EOS, "img_s": IMG_S, "img_e": IMG_E, + "txt_s": TXT_S, "txt_e": TXT_E, + "train_rows": int(tr.shape[0]), "val_rows": int(va.shape[0]), + } + with open(os.path.join(args.out_dir, "meta.json"), "w") as f: + json.dump(meta, f, indent=2) + print(f"done: train {tr.shape[0]} rows, val {va.shape[0]} rows, skipped {n_skip}") + print(f"tokens/epoch: {tr.shape[0]*SEQ_LEN:,}") + + +if __name__ == "__main__": + main() diff --git a/mm/build_from_captions.py b/mm/build_from_captions.py new file mode 100644 index 0000000..3aaa98e --- /dev/null +++ b/mm/build_from_captions.py @@ -0,0 +1,136 @@ +"""Build a token dataset from captions.jsonl (VLM recaptions) instead of alt-text. + +Reads the append-only caption file produced by caption_all.py, pairs each key +with its image from the shard, VQ-encodes the image and tokenises the NEW +caption, then writes the same flat uint16 format build_data.py produces. + +Keeping the format identical means the same train.py / generate.py / colour_eval.py +work unchanged, so Arm A (alt-text) and Arm C (VLM captions) differ only in data. +""" +import argparse +import io +import json +import os +import shutil +import tarfile + +import numpy as np +import torch +from PIL import Image +from tokenizers import Tokenizer + +from build_data import ( + IMAGE_VOCAB, IMAGE_OFFSET, PAD, BOS, EOS, IMG_S, IMG_E, TXT_S, TXT_E, + VOCAB_SIZE, encode_images, load_vq, +) +import build_data + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--shards", nargs="+", required=True) + ap.add_argument("--captions", default="../data_mm_car_q/captions.jsonl") + ap.add_argument("--out_dir", default="../data_mm_car_q") + ap.add_argument("--tok", default="../data_mm/tokenizer.json") + ap.add_argument("--vq_ckpt", default="../ckpt/vq_ds16_t2i.pt") + ap.add_argument("--img_side", type=int, default=128) + ap.add_argument("--seq_len", type=int, default=128) + ap.add_argument("--val_frac", type=float, default=0.02) + ap.add_argument("--img_first_prob", type=float, default=0.5) + ap.add_argument("--device", default="cuda") + args = ap.parse_args() + + build_data.IMG_SIDE = args.img_side + build_data.LATENT = args.img_side // 16 + build_data.N_IMG_TOKENS = build_data.LATENT ** 2 + build_data.SEQ_LEN = args.seq_len + N_IMG, SEQ = build_data.N_IMG_TOKENS, args.seq_len + + caps = {} + with open(args.captions) as f: + for line in f: + try: + d = json.loads(line) + caps[d["key"]] = d["new"] + except Exception: + pass + print(f"loaded {len(caps)} recaptions") + + tok = Tokenizer.from_file(args.tok) + vq = load_vq(args.vq_ckpt, args.device) + rng = np.random.default_rng(0) + train_rows, val_rows = [], [] + n_ok = n_skip = 0 + blobs, texts = [], [] + + def flush(): + nonlocal n_ok, n_skip + if not blobs: + return + codes = encode_images(vq, blobs, args.device) + for c, cap in zip(codes, texts): + if c is None or not cap: + n_skip += 1 + continue + ids = [i for i in tok.encode(cap).ids if i < 16000][: SEQ - N_IMG - 8] + if len(ids) < 2: + n_skip += 1 + continue + img = (c + IMAGE_OFFSET).astype(np.uint16) + if rng.random() < args.img_first_prob: + seq = [BOS, IMG_S, *img.tolist(), IMG_E, TXT_S, *ids, TXT_E, EOS] + else: + seq = [BOS, TXT_S, *ids, TXT_E, IMG_S, *img.tolist(), IMG_E, EOS] + row = np.full(SEQ, PAD, dtype=np.uint16) + row[: len(seq)] = seq + (val_rows if rng.random() < args.val_frac else train_rows).append(row) + n_ok += 1 + blobs.clear() + texts.clear() + + for shard in args.shards: + try: + tf = tarfile.open(shard) + except Exception: + continue + try: + for m in tf: + if not m.isfile() or not m.name.endswith(".jpg"): + continue + key = m.name[:-4] + if key not in caps: + continue + blobs.append(tf.extractfile(m).read()) + texts.append(caps[key]) + if len(blobs) >= 64: + flush() + if n_ok % 640 == 0 and n_ok > 0: + print(f" built {n_ok}", flush=True) + except Exception as e: + print(f" partial {os.path.basename(shard)}: {e}", flush=True) + finally: + tf.close() + flush() + + tr = np.stack(train_rows) if train_rows else np.zeros((0, SEQ), np.uint16) + va = np.stack(val_rows) if val_rows else np.zeros((0, SEQ), np.uint16) + tr.tofile(os.path.join(args.out_dir, "train.bin")) + va.tofile(os.path.join(args.out_dir, "val.bin")) + meta = { + "seq_len": SEQ, "vocab_size": VOCAB_SIZE, "text_vocab": 16000, + "image_vocab": IMAGE_VOCAB, "image_offset": IMAGE_OFFSET, + "n_img_tokens": N_IMG, "img_side": args.img_side, + "pad": PAD, "bos": BOS, "eos": EOS, "img_s": IMG_S, "img_e": IMG_E, + "txt_s": TXT_S, "txt_e": TXT_E, + "train_rows": int(tr.shape[0]), "val_rows": int(va.shape[0]), + "caption_source": "strata_qwen3.8_flash_next", + } + with open(os.path.join(args.out_dir, "meta.json"), "w") as f: + json.dump(meta, f, indent=2) + shutil.copy(args.tok, os.path.join(args.out_dir, "tokenizer.json")) + print(f"done: train {tr.shape[0]}, val {va.shape[0]}, skipped {n_skip}") + print(f"tokens/epoch: {tr.shape[0]*SEQ:,}") + + +if __name__ == "__main__": + main() diff --git a/mm/caption_all.py b/mm/caption_all.py new file mode 100644 index 0000000..2c40e2c --- /dev/null +++ b/mm/caption_all.py @@ -0,0 +1,150 @@ +"""Caption CC3M images through the local strata OpenAI-compatible endpoint. + +Two-phase on purpose: + phase 1 (this script) -> captions.jsonl, append-only and resumable + phase 2 (recaption.py) -> turn jsonl + images into a token dataset + +Resumable because 5k images at ~1.3 s each is a ~2 h job; a crash should not +throw away finished work. +""" +import argparse +import base64 +import io +import json +import os +import re +import tarfile +import time +import urllib.request + +from PIL import Image + +COLOURS = ["red", "blue", "green", "yellow", "white", "black", "silver", + "grey", "gray", "orange", "brown", "gold"] + +PROMPT = ("Describe this image in one detailed sentence. Include the main " + "subject's colour, what it is doing, and the setting. " + "Output the sentence only, no preamble.") + + +def b64_jpeg(im, side=512): + im = im.convert("RGB") + w, h = im.size + s = side / max(w, h) + if s < 1: + im = im.resize((int(w * s), int(h * s)), Image.BICUBIC) + buf = io.BytesIO() + im.save(buf, format="JPEG", quality=88) + return base64.b64encode(buf.getvalue()).decode() + + +def caption_one(url, model, im, timeout=180, retries=3): + payload = { + "model": model, + "messages": [{ + "role": "user", + "content": [ + {"type": "text", "text": PROMPT}, + {"type": "image_url", + "image_url": {"url": "data:image/jpeg;base64," + b64_jpeg(im)}}, + ], + }], + "max_tokens": 90, + "temperature": 0.2, + "chat_template_kwargs": {"enable_thinking": False}, + } + last = None + for a in range(retries): + try: + req = urllib.request.Request( + url, data=json.dumps(payload).encode(), + headers={"Content-Type": "application/json"}) + with urllib.request.urlopen(req, timeout=timeout) as r: + body = json.loads(r.read().decode()) + txt = (body["choices"][0]["message"].get("content") or "").strip() + txt = " ".join(txt.split()) + if txt: + return txt + last = "empty content" + except Exception as e: + last = str(e)[:120] + time.sleep(2 + 2 * a) + raise RuntimeError(last) + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--shards", nargs="+", required=True) + ap.add_argument("--filter", default="car") + ap.add_argument("--out", default="../data_mm_car_q/captions.jsonl") + ap.add_argument("--url", default="http://127.0.0.1:8080/v1/chat/completions") + ap.add_argument("--model", default="qwen3.8-flash-next-gyro-gyro-s") + ap.add_argument("--limit", type=int, default=0) + args = ap.parse_args() + + os.makedirs(os.path.dirname(args.out) or ".", exist_ok=True) + done = set() + if os.path.exists(args.out): + with open(args.out) as f: + for line in f: + try: + done.add(json.loads(line)["key"]) + except Exception: + pass + print(f"resume: {len(done)} already captioned", flush=True) + + filt = re.compile(r"\b" + re.escape(args.filter) + r"s?\b", re.I) + n = 0 + t0 = time.time() + fout = open(args.out, "a") + for shard in args.shards: + try: + tf = tarfile.open(shard) + except Exception: + continue + try: + for m in tf: + if not m.isfile() or not m.name.endswith(".txt"): + continue + key = m.name[:-4] + if key in done: + continue + cap = tf.extractfile(m).read().decode("utf-8", "ignore").strip() + if not filt.search(cap): + continue + try: + jm = tf.getmember(key + ".jpg") + except KeyError: + continue + try: + im = Image.open(io.BytesIO(tf.extractfile(jm).read())) + if min(im.size) < 200: + continue + txt = caption_one(args.url, args.model, im) + except Exception as e: + print(f" skip {key}: {e}", flush=True) + continue + rec = {"key": key, "shard": os.path.basename(shard), + "old": cap, "new": txt, + "has_colour": any(re.search(r"\b" + w + r"\b", txt.lower()) for w in COLOURS)} + fout.write(json.dumps(rec, ensure_ascii=False) + "\n") + fout.flush() + n += 1 + if n % 100 == 0: + el = time.time() - t0 + print(f" {n} new ({len(done)+n} total) " + f"{el/n:.2f} s/img eta {(5184-n)*el/n/60:.0f} min", flush=True) + if args.limit and n >= args.limit: + raise SystemExit(0) + except SystemExit: + raise + except Exception as e: + print(f" partial {os.path.basename(shard)}: {e}", flush=True) + finally: + tf.close() + fout.close() + print(f"done: {n} newly captioned, {len(done)+n} total", flush=True) + + +if __name__ == "__main__": + main() diff --git a/mm/recaption.py b/mm/recaption.py new file mode 100644 index 0000000..f10b8c4 --- /dev/null +++ b/mm/recaption.py @@ -0,0 +1,168 @@ +"""Rebuild a dataset with VLM-generated captions instead of CC3M alt-text. + +Motivation: CC3M captions are hypernym-ed and generic ("a car parked on a +street"), which carries almost no controllable information. If caption quality +is the binding constraint, swapping in dense captions on the SAME images should +measurably improve prompt controllability and output diversity. + +Usage: + python recaption.py --shards ../data_mm/shards/*.tar --filter car \ + --vlm ../ckpt/vlm --out_dir ../data_mm_car_q --img_side 128 +""" +import argparse +import io +import json +import os +import re +import sys +import tarfile + +import numpy as np +import torch +from PIL import Image + +from build_data import ( + IMAGE_VOCAB, IMAGE_OFFSET, PAD, BOS, EOS, IMG_S, IMG_E, TXT_S, TXT_E, + VOCAB_SIZE, iter_samples, load_vq, encode_images, +) +import build_data + + +def load_vlm(path, device="cuda"): + from transformers import BlipForConditionalGeneration, BlipProcessor + + proc = BlipProcessor.from_pretrained(path, local_files_only=True) + model = BlipForConditionalGeneration.from_pretrained( + path, torch_dtype=torch.float16, local_files_only=True + ).to(device).eval() + return model, proc + + +@torch.no_grad() +def caption_batch(model, proc, blobs, device="cuda", max_new=50): + out = [] + for b in blobs: + try: + im = Image.open(io.BytesIO(b)).convert("RGB") + except Exception: + out.append(None) + continue + inp = proc(images=im, return_tensors="pt") + inp = {k: (v.half().to(device) if v.dtype == torch.float32 else v.to(device)) + for k, v in inp.items()} + ids = model.generate(**inp, max_new_tokens=max_new, num_beams=3) + cap = proc.decode(ids[0], skip_special_tokens=True) + cap = " ".join(cap.split()) + out.append(cap if cap else None) + return out + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--shards", nargs="+", required=True) + ap.add_argument("--vq_ckpt", default="../ckpt/vq_ds16_t2i.pt") + ap.add_argument("--vlm", default="../ckpt/blip") + ap.add_argument("--out_dir", default="../data_mm_car_q") + ap.add_argument("--tok", default="../data_mm/tokenizer.json") + ap.add_argument("--filter", default="car") + ap.add_argument("--img_side", type=int, default=128) + ap.add_argument("--seq_len", type=int, default=128) + ap.add_argument("--val_frac", type=float, default=0.02) + ap.add_argument("--img_first_prob", type=float, default=0.5) + ap.add_argument("--min_side", type=int, default=200, help="skip images smaller than this") + ap.add_argument("--limit", type=int, default=0) + ap.add_argument("--device", default="cuda") + args = ap.parse_args() + + build_data.IMG_SIDE = args.img_side + build_data.LATENT = args.img_side // 16 + build_data.N_IMG_TOKENS = build_data.LATENT ** 2 + build_data.SEQ_LEN = args.seq_len + N_IMG = build_data.N_IMG_TOKENS + SEQ = args.seq_len + + from tokenizers import Tokenizer + tok = Tokenizer.from_file(args.tok) + os.makedirs(args.out_dir, exist_ok=True) + + print("loading VQ + VLM ...") + vq = load_vq(args.vq_ckpt, args.device) + vlm, proc = load_vlm(args.vlm, args.device) + + filt = re.compile(r"\b" + re.escape(args.filter) + r"s?\b", re.I) + rng = np.random.default_rng(0) + train_rows, val_rows = [], [] + n_ok = n_skip = n_small = 0 + blobs, old_caps = [], [] + + def flush(): + nonlocal n_ok, n_skip, n_small + if not blobs: + return + codes = encode_images(vq, blobs, args.device) + newcaps = caption_batch(vlm, proc, blobs, args.device) + for c, cap, old in zip(codes, newcaps, old_caps): + if c is None or not cap: + n_skip += 1 + continue + ids = [i for i in tok.encode(cap).ids if i < 16000][: SEQ - N_IMG - 8] + if len(ids) < 2: + n_skip += 1 + continue + img = (c + IMAGE_OFFSET).astype(np.uint16) + if rng.random() < args.img_first_prob: + seq = [BOS, IMG_S, *img.tolist(), IMG_E, TXT_S, *ids, TXT_E, EOS] + else: + seq = [BOS, TXT_S, *ids, TXT_E, IMG_S, *img.tolist(), IMG_E, EOS] + row = np.full(SEQ, PAD, dtype=np.uint16) + row[: len(seq)] = seq + (val_rows if rng.random() < args.val_frac else train_rows).append(row) + n_ok += 1 + blobs.clear() + old_caps.clear() + + for _, blob, cap in iter_samples(args.shards): + if not filt.search(cap): + continue + try: + im = Image.open(io.BytesIO(blob)) + if min(im.size) < args.min_side: + n_small += 1 + continue + except Exception: + n_skip += 1 + continue + blobs.append(blob) + old_caps.append(cap) + if len(blobs) >= 64: + flush() + if n_ok % 640 == 0 and n_ok > 0: + print(f" recaptioned {n_ok} skipped {n_skip} too_small {n_small}", flush=True) + if args.limit and n_ok >= args.limit: + break + flush() + + tr = np.stack(train_rows) if train_rows else np.zeros((0, SEQ), np.uint16) + va = np.stack(val_rows) if val_rows else np.zeros((0, SEQ), np.uint16) + tr.tofile(os.path.join(args.out_dir, "train.bin")) + va.tofile(os.path.join(args.out_dir, "val.bin")) + meta = { + "seq_len": SEQ, "vocab_size": VOCAB_SIZE, "text_vocab": 16000, + "image_vocab": IMAGE_VOCAB, "image_offset": IMAGE_OFFSET, + "n_img_tokens": N_IMG, "img_side": args.img_side, + "pad": PAD, "bos": BOS, "eos": EOS, "img_s": IMG_S, "img_e": IMG_E, + "txt_s": TXT_S, "txt_e": TXT_E, + "train_rows": int(tr.shape[0]), "val_rows": int(va.shape[0]), + "caption_source": "florence2_more_detailed", + } + with open(os.path.join(args.out_dir, "meta.json"), "w") as f: + json.dump(meta, f, indent=2) + # reuse the same tokenizer so the text vocab is identical to the baseline + import shutil + shutil.copy(args.tok, os.path.join(args.out_dir, "tokenizer.json")) + print(f"done: train {tr.shape[0]}, val {va.shape[0]}, skipped {n_skip}, too_small {n_small}") + print(f"tokens/epoch: {tr.shape[0]*SEQ:,}") + + +if __name__ == "__main__": + main() diff --git a/mm/retok_body.py b/mm/retok_body.py new file mode 100644 index 0000000..9615ba8 --- /dev/null +++ b/mm/retok_body.py @@ -0,0 +1,125 @@ +"""Rewrite the text side into "a {colour} {body}" prompts (two control axes). + +Colour is available for ~97% of rows. Body type is only stated in ~34% of the +VLM captions; rows without it keep the truthful generic word "car" instead of +being dropped, so the dataset size stays 5,184 but carries a second attribute +where it is actually known. +""" +import argparse +import json +import os +import re +import shutil + +import numpy as np +from tokenizers import Tokenizer + +from model import BOS, EOS, IMG_S, IMG_E, TXT_S, TXT_E, PAD, IMAGE_OFFSET, IMAGE_VOCAB + +COLOURS = ["red", "blue", "green", "yellow", "white", "black", "silver", + "grey", "gray", "orange", "brown"] +COLOUR_RE = re.compile(r"\b(" + "|".join(COLOURS) + r")\b", re.I) + +# order matters: the more specific phrase must be tested first +BODY_MAP = [ + ("convertible", [r"convertible", r"cabriolet", r"roadster"]), + ("sports", [r"sports car", r"sportscar", r"coupe", r"supercar"]), + ("race", [r"race car", r"racing car", r"rally car", r"stock car"]), + ("suv", [r"suv", r"4x4", r"crossover"]), + ("truck", [r"truck", r"pickup", r"lorry"]), + ("van", [r"van", r"minivan"]), + ("hatchback", [r"hatchback"]), + ("sedan", [r"sedan", r"saloon"]), + ("wagon", [r"wagon", r"estate car"]), +] +TEMPLATES = ["a {c} {b}", "a photo of a {c} {b}", "a {c} {b} on the road", + "a close up of a {c} {b}"] + + +def parse(text): + found = COLOUR_RE.findall(text) + colour = found[0].lower() if found else "" + if colour == "gray": + colour = "grey" + body = "" + low = text.lower() + for name, pats in BODY_MAP: + if any(re.search(p, low) for p in pats): + body = name + break + return colour, body + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src_dir", default="../data_mm_car_q") + ap.add_argument("--out_dir", default="../data_mm_car_t") + ap.add_argument("--row_len", type=int, default=128) + ap.add_argument("--img_first_prob", type=float, default=0.35) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + tok = Tokenizer.from_file(os.path.join(args.src_dir, "tokenizer.json")) + rng = np.random.default_rng(args.seed) + os.makedirs(args.out_dir, exist_ok=True) + + stats = {} + for split in ("train", "val"): + raw = np.asarray(np.memmap(os.path.join(args.src_dir, f"{split}.bin"), + dtype=np.uint16, mode="r")) + rows = raw.reshape(-1, args.row_len) + out = [] + combo = {} + n_body = 0 + for r in rows: + ids = [int(t) for t in r] + try: + i = ids.index(IMG_S) + t0 = ids.index(TXT_S) + t1 = ids.index(TXT_E) + except ValueError: + continue + img = [t for t in ids[i + 1 : i + 65] if IMAGE_OFFSET <= t < IMAGE_OFFSET + IMAGE_VOCAB] + txt_ids = [t for t in ids[t0 + 1 : t1] if 0 <= t < 16000] + if len(img) != 64: + continue + colour, body = parse(tok.decode(txt_ids)) + if not colour and not body: + prompt = "a car" + elif not body: + prompt = TEMPLATES[int(rng.integers(len(TEMPLATES)))].format(c=colour, b="car") + elif not colour: + prompt = TEMPLATES[int(rng.integers(len(TEMPLATES)))].format(c="", b=body).replace("a ", "a ") + else: + prompt = TEMPLATES[int(rng.integers(len(TEMPLATES)))].format(c=colour, b=body) + n_body += int(bool(body)) + combo[(colour, body)] = combo.get((colour, body), 0) + 1 + pids = [t for t in tok.encode(prompt).ids if t < 16000] + seq = ([BOS, TXT_S, *pids, TXT_E, IMG_S, *img, IMG_E, EOS] + if rng.random() >= args.img_first_prob else + [BOS, IMG_S, *img, IMG_E, TXT_S, *pids, TXT_E, EOS]) + row = np.full(args.row_len, PAD, dtype=np.uint16) + row[: len(seq)] = np.array(seq, dtype=np.uint16) + out.append(row) + arr = np.stack(out) + arr.tofile(os.path.join(args.out_dir, f"{split}.bin")) + stats[split] = dict(rows=int(arr.shape[0]), with_body=n_body) + print(f"{split}: {arr.shape[0]} rows, body label on {n_body} rows") + if split == "train": + top = sorted(combo.items(), key=lambda x: -x[1])[:12] + print(" top (colour, body):", top) + + shutil.copy(os.path.join(args.src_dir, "tokenizer.json"), + os.path.join(args.out_dir, "tokenizer.json")) + with open(os.path.join(args.out_dir, "meta.json"), "w") as f: + json.dump({"seq_len": args.row_len, "vocab_size": 32391, "text_vocab": 16000, + "image_vocab": IMAGE_VOCAB, "image_offset": IMAGE_OFFSET, + "n_img_tokens": 64, "img_side": 128, "pad": PAD, "bos": BOS, + "eos": EOS, "img_s": IMG_S, "img_e": IMG_E, "txt_s": TXT_S, + "txt_e": TXT_E, "templates": TEMPLATES, + "caption_source": "colour_plus_body_templated", "splits": stats}, f, indent=2) + print("done ->", args.out_dir) + + +if __name__ == "__main__": + main() diff --git a/mm/retok_short.py b/mm/retok_short.py new file mode 100644 index 0000000..361378f --- /dev/null +++ b/mm/retok_short.py @@ -0,0 +1,103 @@ +"""Re-tokenise the text half of an existing dataset into short shared prompts. + +Why: with the VLM captions every row has a near-unique sentence, so the model +can use the whole sentence as an index (memorise caption -> codes) and the +colour adjective carries no extra information. Validation image-token accuracy +0.002 vs train 0.993 says exactly that. + +This script keeps the image codes untouched and rewrites only the text side to a +few shared templates, so many images now share a prompt and the model is forced +to model the conditional distribution instead of an index lookup. +""" +import argparse +import json +import os +import re +import shutil + +import numpy as np +from tokenizers import Tokenizer + +from model import BOS, EOS, IMG_S, IMG_E, TXT_S, TXT_E, PAD, IMAGE_OFFSET, IMAGE_VOCAB + +COLOURS = ["red", "blue", "green", "yellow", "white", "black", "silver", + "grey", "gray", "orange", "brown"] +COLOUR_RE = re.compile(r"\b(" + "|".join(COLOURS) + r")\b", re.I) +TEMPLATES = ["a {c} car", "a photo of a {c} car", "a {c} car on the road", + "a close up of a {c} car"] + + +def main(): + ap = argparse.ArgumentParser() + ap.add_argument("--src_dir", default="../data_mm_car_q") + ap.add_argument("--out_dir", default="../data_mm_car_s") + ap.add_argument("--row_len", type=int, default=128) + ap.add_argument("--img_first_prob", type=float, default=0.35) + ap.add_argument("--seed", type=int, default=0) + args = ap.parse_args() + + tok = Tokenizer.from_file(os.path.join(args.src_dir, "tokenizer.json")) + rng = np.random.default_rng(args.seed) + os.makedirs(args.out_dir, exist_ok=True) + + stats = {} + for split in ("train", "val"): + path = os.path.join(args.src_dir, f"{split}.bin") + raw = np.asarray(np.memmap(path, dtype=np.uint16, mode="r")) + rows = raw.reshape(-1, args.row_len) + out = [] + single = none_col = 0 + for r in rows: + ids = [int(t) for t in r] + try: + i = ids.index(IMG_S) + t0 = ids.index(TXT_S) + t1 = ids.index(TXT_E) + except ValueError: + continue + img = [t for t in ids[i + 1 : i + 65] if IMAGE_OFFSET <= t < IMAGE_OFFSET + IMAGE_VOCAB] + txt_ids = [t for t in ids[t0 + 1 : t1] if 0 <= t < 16000] + if len(img) != 64: + continue + text = tok.decode(txt_ids) + found = COLOUR_RE.findall(text) + if found: + colour = found[0].lower() + single += int(len(set(x.lower() for x in found)) == 1) + else: + colour = "" + none_col += 1 + if not colour: + prompt = "a car" + else: + prompt = TEMPLATES[int(rng.integers(len(TEMPLATES)))].format(c=colour) + pids = [t for t in tok.encode(prompt).ids if t < 16000] + seq = ([BOS, TXT_S, *pids, TXT_E, IMG_S, *img, IMG_E, EOS] + if rng.random() >= args.img_first_prob else + [BOS, IMG_S, *img, IMG_E, TXT_S, *pids, TXT_E, EOS]) + row = np.full(args.row_len, PAD, dtype=np.uint16) + row[: len(seq)] = np.array(seq, dtype=np.uint16) + out.append(row) + arr = np.stack(out) + arr.tofile(os.path.join(args.out_dir, f"{split}.bin")) + stats[split] = dict(rows=int(arr.shape[0]), single_colour=single, no_colour=none_col) + print(f"{split}: {arr.shape[0]} rows, single-colour {single}, " + f"no-colour {none_col} -> prompts collapsed to {len(TEMPLATES)} templates") + + shutil.copy(os.path.join(args.src_dir, "tokenizer.json"), + os.path.join(args.out_dir, "tokenizer.json")) + meta = { + "seq_len": args.row_len, "vocab_size": 32391, "text_vocab": 16000, + "image_vocab": 16384, "image_offset": 16000, "n_img_tokens": 64, + "img_side": 128, "pad": PAD, "bos": BOS, "eos": EOS, + "img_s": IMG_S, "img_e": IMG_E, "txt_s": TXT_S, "txt_e": TXT_E, + "caption_source": "short_templated_from_strata_captions", + "templates": TEMPLATES, "splits": stats, + } + with open(os.path.join(args.out_dir, "meta.json"), "w") as f: + json.dump(meta, f, indent=2) + print("done ->", args.out_dir) + + +if __name__ == "__main__": + main()