import io, os, tarfile, numpy as np, torch from PIL import Image import generate as G from model import GPT from tokenizers import Tokenizer G.IMG_SIDE, G.LATENT, G.N_IMG = 128, 8, 64 tok = Tokenizer.from_file("../data_mm/tokenizer.json") vq = G.load_vq("../ckpt/vq_ds16_t2i.pt", "cuda") def prep(im): im = im.convert("RGB").resize((128,128), Image.BICUBIC) return np.asarray(im, dtype=np.float32)/127.5-1.0 real=[] tf = tarfile.open("../data_mm/shards/cc3m-0000.tar") for m in tf: if m.isfile() and m.name.endswith(".jpg"): real.append(prep(Image.open(io.BytesIO(tf.extractfile(m).read())))) if len(real)>=60: break x = torch.from_numpy(np.stack(real)).permute(0,3,1,2).cuda() with torch.no_grad(): rc = vq.encode(x)[2][2].view(-1,64).cpu().numpy() ck = torch.load("out_v2a/ckpt_iter5100.pt", map_location="cuda", weights_only=False) mt = GPT(ck["cfg"]).cuda(); mt.load_state_dict(ck["model"]); mt.eval() torch.manual_seed(0) with torch.device("cuda"): mr = GPT(ck["cfg"]) mr.eval() gen={} for nm,mo in (("trained",mt),("random",mr)): out=[] for i in range(20): torch.manual_seed(500+i) c,_ = G.text_to_image(mo, tok, "a duck on a pond", "cuda", 0.9, 50) out.append(c.cpu().numpy()) gen[nm]=np.stack(out) print("%-10s %10s %12s" % ("source","uniq/img","top10 overlap")) ref_hist = np.bincount(rc.ravel(), minlength=16384).astype(float); ref_hist/=ref_hist.sum() ref_top = set(np.argsort(-ref_hist)[:10]) print("%-10s %10.1f %12s" % ("real", rc.reshape(len(rc),-1).shape[1] and np.mean([len(np.unique(r)) for r in rc]), "-")) for nm in ("trained","random"): g = gen[nm].reshape(-1,64) h = np.bincount(g.ravel(), minlength=16384).astype(float); h/=h.sum() top = set(np.argsort(-h)[:10]) print("%-10s %10.1f %12d/10" % (nm, np.mean([len(np.unique(r)) for r in g]), len(top & ref_top))) print(" cosine vs real: %.3f" % (h@ref_hist/(np.linalg.norm(h)*np.linalg.norm(ref_hist)+1e-9)))