feat(exp): 四个 Arm 的实验编排与基准脚本

同一模型、同一批 5184 张图、同样 100 epoch,只换监督信号:
- Arm C: VLM 重描述(唯一长 caption)
- Arm D: 同 C 数据,模型缩到 13.4M(5.1M 非嵌入)
- Arm E: prompt 压成 4 个共享模板
- Arm F: 颜色 + 车身两级模板

结果:C/D 颜色词被忽略(码一致率 0.75 / 0.60),
E 降到 0.000 且色相 3/4 命中,F 在 20 格交叉积上只剩 1 列稳定。

bench_strata: strata(Qwen3.8)视觉描述的延迟与吞吐基准,1.06 s/img。
compare_gen: 多检查点批量出图对比。pdl.sh: 分片下载辅助。
This commit is contained in:
liuhuajie committed 2026-12-03 10:37:55 +08:00
1 parent 5d2d3a2fb5
commit 9e29277715
7 files changed
+307

No files matched your search

+88
View File
@@ -0,0 +1,88 @@
"""Benchmark the local strata vision endpoint on captioning."""
import base64
import io
import json
import tarfile
import time
import urllib.request
import numpy as np
from PIL import Image
URL = "http://127.0.0.1:8080/v1/chat/completions"
MODEL = "qwen3.8-flash-next-gyro-gyro-s"
def post(payload, timeout=300):
data = json.dumps(payload).encode()
req = urllib.request.Request(URL, data=data, headers={"Content-Type": "application/json"})
t0 = time.time()
with urllib.request.urlopen(req, timeout=timeout) as r:
body = json.loads(r.read().decode())
return body, time.time() - t0
def b64_jpeg(im, side=512):
im = im.convert("RGB")
w, h = im.size
s = side / max(w, h)
if s < 1:
im = im.resize((int(w * s), int(h * s)), Image.BICUBIC)
buf = io.BytesIO()
im.save(buf, format="JPEG", quality=88)
return base64.b64encode(buf.getvalue()).decode()
def main():
blobs = []
with tarfile.open("../data_mm/shards/cc3m-0000.tar") as tf:
for m in tf:
if m.isfile() and m.name.endswith(".txt"):
cap = tf.extractfile(m).read().decode("utf-8", "ignore").strip()
if "car" in cap.lower():
key = m.name[:-4]
try:
jm = tf.getmember(key + ".jpg")
except KeyError:
continue
blobs.append(Image.open(io.BytesIO(tf.extractfile(jm).read())))
if len(blobs) >= 4:
break
prompt = ("Describe this image in one detailed sentence. "
"Include the main subject's colour, what it is doing, and the setting. "
"Answer with the sentence only, no preamble.")
print(f"{'run':>4} {'wall_s':>7} {'ptok':>5} {'ctok':>5} {'tok/s':>7} caption")
for i, im in enumerate(blobs):
b64 = b64_jpeg(im)
payload = {
"model": MODEL,
"messages": [{
"role": "user",
"content": [
{"type": "text", "text": prompt},
{"type": "image_url", "image_url": {"url": f"data:image/jpeg;base64,{b64}"}},
],
}],
"max_tokens": 80,
"temperature": 0.2,
"chat_template_kwargs": {"enable_thinking": False},
}
try:
body, dt = post(payload)
except Exception as e:
print(f"{i:>4} ERROR {e}")
continue
ch = body["choices"][0]["message"]
txt = (ch.get("content") or "").strip().replace("\n", " ")
usage = body.get("usage", {})
pt, ct = usage.get("prompt_tokens", 0), usage.get("completion_tokens", 0)
tps = ct / dt if dt > 0 else 0
print(f"{i:>4} {dt:7.2f} {pt:5d} {ct:5d} {tps:7.1f} {txt[:110]}")
if ch.get("reasoning_content"):
print(f" (reasoning: {ch['reasoning_content'][:80]})")
if __name__ == "__main__":
main()
+103
View File
@@ -0,0 +1,103 @@
"""Compare generation from: random init vs trained checkpoint vs real data.
Settles the question "did it learn anything at all, or is the output the same
as an untrained model?".
"""
import argparse
import io
import os
import tarfile
import torch
from PIL import Image, ImageDraw
from tokenizers import Tokenizer
import generate as G
from model import GPT
PROMPT = "a duck on a pond"
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--ckpt", default="out_v2a/ckpt_iter5100.pt")
ap.add_argument("--tok", default="../data_mm/tokenizer.json")
ap.add_argument("--vq_ckpt", default="../ckpt/vq_ds16_t2i.pt")
ap.add_argument("--shard", default="../data_mm/shards/cc3m-0000.tar")
ap.add_argument("--n", type=int, default=4)
ap.add_argument("--out", default="../data_mm/compare")
args = ap.parse_args()
device = "cuda"
G.IMG_SIDE, G.LATENT, G.N_IMG = 128, 8, 64
tok = Tokenizer.from_file(args.tok)
vq = G.load_vq(args.vq_ckpt, device)
os.makedirs(args.out, exist_ok=True)
ck = torch.load(args.ckpt, map_location=device, weights_only=False)
cfg = ck["cfg"]
# 1) random init, same architecture, never trained
torch.manual_seed(0)
with torch.device(device):
m_rand = GPT(cfg)
m_rand.eval()
# 2) trained checkpoint
m_trained = GPT(cfg).to(device)
m_trained.load_state_dict(ck["model"])
m_trained.eval()
rows = {}
for name, model in (("random init", m_rand), ("trained 2 epoch", m_trained)):
tiles = []
for i in range(args.n):
torch.manual_seed(100 + i)
codes, _ = G.text_to_image(model, tok, PROMPT, device, 0.9, 50)
tiles.append(G.codes_to_pil(vq, codes, device))
rows[name] = tiles
# 3) real training images, same prompt keyword "duck"
real = []
with tarfile.open(args.shard) as tf:
for mem in tf:
if not mem.isfile() or not mem.name.endswith(".txt"):
continue
cap = tf.extractfile(mem).read().decode("utf-8", "ignore").strip()
if "duck" not in cap.lower():
continue
key = os.path.splitext(mem.name)[0]
try:
img_mem = tf.getmember(key + ".jpg")
except KeyError:
continue
im = Image.open(io.BytesIO(tf.extractfile(img_mem).read())).convert("RGB")
real.append(im.resize((G.IMG_SIDE, G.IMG_SIDE), Image.BICUBIC))
if len(real) >= args.n:
break
rows["real cc3m"] = real
S = G.IMG_SIDE
labels = list(rows.keys())
canvas = Image.new("RGB", (S * args.n, (S + 20) * len(labels)), (255, 255, 255))
d = ImageDraw.Draw(canvas)
for r, lab in enumerate(labels):
d.text((4, r * (S + 20) + 3), lab, fill=(30, 30, 30))
for c, im in enumerate(rows[lab]):
canvas.paste(im, (c * S, r * (S + 20) + 20))
p = os.path.join(args.out, "compare.png")
canvas.save(p)
print(f"saved {p} size={canvas.size}")
# quick numeric check: code histogram distance to real data
with torch.no_grad():
for name, model in (("random init", m_rand), ("trained 2 epoch", m_trained)):
torch.manual_seed(7)
codes, _ = G.text_to_image(model, tok, PROMPT, device, 0.9, 50)
u = len(torch.unique(codes))
print(f"{name}: {u} unique codes used in one image (of 16384)")
if __name__ == "__main__":
main()
Executable
+33
View File
@@ -0,0 +1,33 @@
#!/bin/bash
# Arm C: VLM-recaptioned data -> dataset -> train -> colour eval
set -e
cd /home/lhj/projects/tiny-gpt/mm
PY=/home/lhj/projects/tiny-gpt/.venv/bin/python
echo "=== 1. unload strata to free VRAM ==="
curl -s -X POST http://127.0.0.1:8080/unload -H 'Content-Type: application/json' -d '{}' || true
sleep 6
nvidia-smi --query-gpu=memory.used --format=csv,noheader
echo "=== 2. build dataset from VLM captions ==="
$PY build_from_captions.py \
--shards ../data_mm/shards/*.tar \
--captions ../data_mm_car_q/captions.jsonl \
--out_dir ../data_mm_car_q 2>&1 | tail -6
echo "=== 3. train Arm C ==="
$PY train.py \
--data ../data_mm_car_q/train.bin --row_len 128 \
--batch_size 64 --grad_accum 2 \
--max_iters 4050 --warmup 100 \
--eval_interval 405 --eval_iters 20 \
--log_interval 405 --save_interval 405 \
--mtp 0 --out_dir out_car_c 2>&1 | grep -E 'eval|total time|peak'
echo "=== 4. colour controllability ==="
$PY colour_eval.py \
--ckpt out_car_c/ckpt.pt \
--tok ../data_mm_car_q/tokenizer.json \
--label armC 2>&1 | tail -12
echo "=== ALL DONE ==="
Executable
+23
View File
@@ -0,0 +1,23 @@
#!/bin/bash
# Arm D: same 5,184 VLM captions, same iters, but a much smaller model.
# Hypothesis: the 45M model memorised the dataset (val image-token acc 0.002)
# and therefore encodes "car -> that exact image" instead of the colour attribute.
# If capacity is the binding constraint, a ~5M non-embedding model must generalise.
set -e
cd /home/lhj/projects/tiny-gpt/mm
PY=/home/lhj/projects/tiny-gpt/.venv/bin/python
echo "=== train Arm D (small) ==="
$PY train.py \
--data ../data_mm_car_q/train.bin --val_data ../data_mm_car_q/val.bin --row_len 128 \
--n_layer 4 --n_embd 256 --n_head 8 --n_kv_head 4 \
--ngram_vocab 65536 --ngram_dim 32 \
--batch_size 64 --grad_accum 2 \
--max_iters 4050 --warmup 100 \
--eval_interval 405 --eval_iters 20 \
--log_interval 405 --save_interval 0 \
--mtp 0 --out_dir out_car_d 2>&1 | grep -Ev '^\s*$'
echo "=== probe Arm D ==="
$PY probe_ctrl.py --ckpt out_car_d/ckpt.pt --label armD 2>&1 | tail -10
echo "=== ARM D DONE ==="
Executable
+22
View File
@@ -0,0 +1,22 @@
#!/bin/bash
# Arm E: identical images and model as Arm C, but the text side is collapsed to
# 4 shared templates ("a {colour} car"). Diagnosis being tested: with unique
# captions the colour word is redundant (the sentence already identifies the
# image), so the model memorises instead of learning the attribute. Make the
# prompt shared and the attribute becomes the only informative token.
set -e
cd /home/lhj/projects/tiny-gpt/mm
PY=/home/lhj/projects/tiny-gpt/.venv/bin/python
echo "=== train Arm E (shared short prompts, 45M) ==="
$PY train.py \
--data ../data_mm_car_s/train.bin --val_data ../data_mm_car_s/val.bin --row_len 128 \
--batch_size 64 --grad_accum 2 \
--max_iters 4050 --warmup 100 \
--eval_interval 405 --eval_iters 20 \
--log_interval 405 --save_interval 0 \
--mtp 0 --out_dir out_car_e 2>&1 | grep -Ev '^\s*$'
echo "=== probe Arm E ==="
$PY probe_simple.py --ckpt out_car_e/ckpt.pt --label armE 2>&1 | tail -14
echo "=== ARM E DONE ==="
Executable
+20
View File
@@ -0,0 +1,20 @@
#!/bin/bash
# Arm F: same images, same model as Arm E, but the prompt carries two attributes
# ("a red sedan"). Arm E can only control colour and loses the object; this asks
# whether a second lexical axis composes or interferes.
set -e
cd /home/lhj/projects/tiny-gpt/mm
PY=/home/lhj/projects/tiny-gpt/.venv/bin/python
echo "=== train Arm F (colour + body prompts, 45M) ==="
$PY train.py \
--data ../data_mm_car_t/train.bin --val_data ../data_mm_car_t/val.bin --row_len 128 \
--batch_size 64 --grad_accum 2 \
--max_iters 4050 --warmup 100 \
--eval_interval 405 --eval_iters 20 \
--log_interval 405 --save_interval 0 \
--mtp 0 --out_dir out_car_f 2>&1 | grep -Ev '^\s*$'
echo "=== probe Arm F ==="
$PY probe_body.py --ckpt out_car_f/ckpt.pt --label armF 2>&1 | tail -14
echo "=== ARM F DONE ==="