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 兜底,不丢样本。
260 lines
9.6 KiB
Python
260 lines
9.6 KiB
Python
"""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="<unk>"))
|
|
tok.pre_tokenizer = pre_tokenizers.ByteLevel(add_prefix_space=False)
|
|
tok.decoder = decoders.ByteLevel()
|
|
trainer = trainers.BpeTrainer(
|
|
vocab_size=vocab_size,
|
|
special_tokens=["<unk>"],
|
|
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()
|