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 兜底,不丢样本。
137 lines
4.9 KiB
Python
137 lines
4.9 KiB
Python
"""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()
|