From 9e29277715e4da3d979139c0b3ff5c31182de815 Mon Sep 17 00:00:00 2001 From: lhj <403133128@qq.com> Date: Thu, 3 Dec 2026 10:37:55 +0800 Subject: [PATCH] =?UTF-8?q?feat(exp):=20=E5=9B=9B=E4=B8=AA=20Arm=20?= =?UTF-8?q?=E7=9A=84=E5=AE=9E=E9=AA=8C=E7=BC=96=E6=8E=92=E4=B8=8E=E5=9F=BA?= =?UTF-8?q?=E5=87=86=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 同一模型、同一批 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: 分片下载辅助。 --- mm/bench_strata.py | 88 ++++++++++++++++++++++++++++++++++++++ mm/compare_gen.py | 103 +++++++++++++++++++++++++++++++++++++++++++++ mm/run_armc.sh | 33 +++++++++++++++ mm/run_armd.sh | 23 ++++++++++ mm/run_arme.sh | 22 ++++++++++ mm/run_armf.sh | 20 +++++++++ pdl.sh | 18 ++++++++ 7 files changed, 307 insertions(+) create mode 100644 mm/bench_strata.py create mode 100644 mm/compare_gen.py create mode 100755 mm/run_armc.sh create mode 100755 mm/run_armd.sh create mode 100755 mm/run_arme.sh create mode 100755 mm/run_armf.sh create mode 100755 pdl.sh diff --git a/mm/bench_strata.py b/mm/bench_strata.py new file mode 100644 index 0000000..8cb8930 --- /dev/null +++ b/mm/bench_strata.py @@ -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() diff --git a/mm/compare_gen.py b/mm/compare_gen.py new file mode 100644 index 0000000..0f2fb75 --- /dev/null +++ b/mm/compare_gen.py @@ -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() diff --git a/mm/run_armc.sh b/mm/run_armc.sh new file mode 100755 index 0000000..82f75d8 --- /dev/null +++ b/mm/run_armc.sh @@ -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 ===" diff --git a/mm/run_armd.sh b/mm/run_armd.sh new file mode 100755 index 0000000..8156cbf --- /dev/null +++ b/mm/run_armd.sh @@ -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 ===" diff --git a/mm/run_arme.sh b/mm/run_arme.sh new file mode 100755 index 0000000..ec02ef9 --- /dev/null +++ b/mm/run_arme.sh @@ -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 ===" diff --git a/mm/run_armf.sh b/mm/run_armf.sh new file mode 100755 index 0000000..9f07888 --- /dev/null +++ b/mm/run_armf.sh @@ -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 ===" diff --git a/pdl.sh b/pdl.sh new file mode 100755 index 0000000..1c78246 --- /dev/null +++ b/pdl.sh @@ -0,0 +1,18 @@ +#!/bin/bash +# parallel segmented download: pdl.sh URL OUTFILE [SEGMENTS] +URL="$1"; OUT="$2"; N="${3:-16}" +SIZE=$(curl -sIL --max-time 40 "$URL" | grep -i '^content-length:' | tail -1 | tr -d '\r' | awk '{print $2}') +if [ -z "$SIZE" ]; then echo "no content-length"; exit 1; fi +echo "total $SIZE bytes, $N segments" +CHUNK=$(( (SIZE + N - 1) / N )) +for i in $(seq 0 $((N-1))); do + S=$(( i * CHUNK )); E=$(( S + CHUNK - 1 )) + [ $E -ge $SIZE ] && E=$(( SIZE - 1 )) + ( curl -sL --retry 6 --retry-delay 3 --max-time 5400 -r ${S}-${E} "$URL" -o "${OUT}.p${i}" ) & +done +wait +for i in $(seq 0 $((N-1))); do cat "${OUT}.p${i}"; done > "$OUT" +rm -f "${OUT}".p* +ACT=$(stat -c%s "$OUT") +echo "result: $ACT / $SIZE" +if [ "$ACT" = "$SIZE" ]; then echo OK; else echo MISMATCH; fi