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