"""8-bit weights for the engine's integer multiply: each big linear weight [M][K] is rotated (ConvRot: 256-block regular Hadamard on the input side, matching the kernel that rotates activations), then rounded to int8 with one scale per output and block of GS inputs. Writes .bin/.idx in the same index format as pack.py: kind q8: int8 texels (o, k16) = w[o][16k16..16k16+15], rows k16 in order (M K) kind qs: fp32 scales [M][K/GS] (M K/GS) Usage: py.sh pack_int8.py [GS] [rot 0/1]""" import sys sys.path[:0] = ["/home/debian/gpu-engine-test/tsbuild/anima"] import torch import comfy.utils from anima_qnn import rot_weight OUT = sys.argv[1] GS = int(sys.argv[2]) if len(sys.argv) > 2 else 64 ROT = (sys.argv[3] if len(sys.argv) > 3 else "1") == "1" sd = comfy.utils.load_torch_file("/home/debian/models/anima/anima-turbo-v1.1.safetensors") g = lambda k: sd["model.diffusion_model." + k].float() blob, idx, off = open(OUT + ".bin", "wb"), open(OUT + ".idx", "w"), 0 def put(name, kind, a, M, K): global off b = a.tobytes() pad = (-off) % 4096 blob.write(b"\0" * pad); off += pad blob.write(b); idx.write(f"{name} {kind} {M} {K} {off} {len(b)}\n"); off += len(b) def q8(name, w): M, K = w.shape if ROT: w = rot_weight(w) t = w.view(M, K // GS, GS) s = t.abs().amax(-1, keepdim=True).clamp_min(1e-12) / 127 q = (t / s).round().clamp(-127, 127).to(torch.int8).view(M, K) put(name, "q8", q.view(M, K // 16, 16).permute(1, 0, 2).contiguous().numpy(), M, K) put(name + ".s", "qs", s.view(M, K // GS).contiguous().numpy(), M, K // GS) for i in range(28): b = f"blocks.{i}." sa, ca = b + "self_attn.", b + "cross_attn." q8(f"{i}.sa_qkv", torch.cat([g(sa + "q_proj.weight"), g(sa + "k_proj.weight"), g(sa + "v_proj.weight")])) q8(f"{i}.sa_o", g(sa + "output_proj.weight")) q8(f"{i}.ca_q", g(ca + "q_proj.weight")) q8(f"{i}.ca_o", g(ca + "output_proj.weight")) q8(f"{i}.l1", g(b + "mlp.layer1.weight")) q8(f"{i}.l2", g(b + "mlp.layer2.weight")) blob.close(); idx.close() print("bytes", off, "GS", GS, "rot", ROT)