CheezOne's picture
v2 preview: token-level text conditioning, short + zh/ja/ko prompts in training, 47 MB trimmed encoder
61fcb70 verified
Raw History Blame Contribute Delete
3.15 kB
"""Export the v2 pixel generator for the browser.
Writes <run>/web/: onnx/model.onnx, onnx/model_quantized.onnx (tokens int64 [B,256], text f32 [B,32,384], text_mask f32 [B,32] -> logits)
palette.json, null.json (unconditional text token), config.json; checks torch/ONNX parity incl. sampled-sprite agreement.
Usage: python pix2_export.py <run_dir> [--encoder-browser CheezOne/...]
"""
import argparse, json, os, sys
import numpy as np, torch
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import pix2_train as P
def main():
ap = argparse.ArgumentParser(); ap.add_argument("run"); ap.add_argument("--encoder-browser", default="CheezOne/paraphrase-multilingual-MiniLM-L12-v2-zh-ja-ko-en")
a = ap.parse_args()
P.DEV = "cpu"; m, cfg = P.load(a.run); m = m.cpu().float().eval()
torch.backends.mha.set_fastpath_enabled(False) # fused encoder-layer kernel has no ONNX symbolic
web = os.path.join(a.run, "web"); os.makedirs(os.path.join(web, "onnx"), exist_ok=True)
fp32, q = os.path.join(web, "onnx", "model.onnx"), os.path.join(web, "onnx", "model_quantized.onnx")
g = torch.Generator().manual_seed(0); L, D = cfg["txt_len"], cfg["text_dim"]
tok = torch.randint(0, cfg["vocab"] + 1, (2, 256), generator=g); h = torch.randn(2, L, D, generator=g); mk = torch.ones(2, L); mk[0, 8:] = 0
with torch.no_grad():
torch.onnx.export(m, (tok, h, mk), fp32, input_names=["tokens", "text", "text_mask"], output_names=["logits"], opset_version=17, dynamo=False,
dynamic_axes={"tokens": {0: "b"}, "text": {0: "b", 1: "l"}, "text_mask": {0: "b", 1: "l"}, "logits": {0: "b"}})
from onnxruntime.quantization import quantize_dynamic, QuantType
quantize_dynamic(fp32, q, weight_type=QuantType.QInt8, per_channel=True, op_types_to_quantize=["MatMul", "Gemm", "Gather"])
import onnxruntime as ort
rep = {"size_mb": {"fp32": round(os.path.getsize(fp32) / 1e6, 1), "int8": round(os.path.getsize(q) / 1e6, 1)}}
tok = torch.randint(1, cfg["vocab"], (4, 256), generator=g); tok[:, ::3] = cfg["vocab"]
h = torch.randn(4, L, D, generator=g); mk = torch.zeros(4, L); mk[:, :6] = 1
with torch.no_grad(): ref = m(tok, h, mk).numpy()
for name, path in [("fp32", fp32), ("int8", q)]:
got = ort.InferenceSession(path, providers=["CPUExecutionProvider"]).run(None, {"tokens": tok.numpy(), "text": h.numpy(), "text_mask": mk.numpy()})[0]
rep[name] = {"max_abs_diff": float(np.abs(ref - got).max()), "argmax_agree": float((ref.argmax(-1) == got.argmax(-1)).mean())}
pal = np.load(os.path.join(a.run, "palette.npy"), allow_pickle=False)
json.dump(pal.tolist(), open(os.path.join(web, "palette.json"), "w"), separators=(",", ":"))
json.dump([round(float(v), 6) for v in m.null.detach().view(-1)], open(os.path.join(web, "null.json"), "w"))
json.dump({**cfg, "steps": 16, "cfg_scale": 3.0, "encoder_browser": a.encoder_browser}, open(os.path.join(web, "config.json"), "w"), indent=1)
print(json.dumps(rep, indent=1)); json.dump(rep, open(os.path.join(a.run, "onnx_report.json"), "w"), indent=1)
if __name__ == "__main__":
main()