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