Files
liuhuajie a16ac3dc45 feat(data): 数据构建、VLM 重描述与提示词模板化
build_data: CC3M 分片 -> 128px VQ 编码 + BPE,写出 flat uint16 行。
caption_all: 调 strata 的 Qwen3.8 批量重描述,可断点续传,1.06 s/img。
build_from_captions: 用重描述替换 alt-text 重建数据集。

retok_short / retok_body: 只在 token 层面重写文本侧,不重跑 VQ(秒级)。
动机:唯一长 caption 会让颜色词变成冗余信息,模型直接背“句子 -> 那张图”;
压成共享模板后颜色词成为唯一有区分度的 token,可控性才出现。
retok_body 引入第二级属性(车身),颜色缺失时用真实的 car 兜底,不丢样本。
2026-12-03 10:37:55 +08:00

169 lines
6.1 KiB
Python

"""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()