"""Throughput of on-GPU weight reconstruction (codebook gather) and of the online activation-side Hadamard transforms, which is what an inference engine must sustain to keep the storage stream busy. """ import json, os, sys, time import torch sys.path.insert(0, os.path.dirname(__file__)) import codec DEV = "cuda" RES = os.path.join(os.path.dirname(__file__), "..", "results") def bench_decode(stages, nweights=1 << 24, reps=20): C = torch.randn(stages, 256, codec.D_SUB, device=DEV, dtype=torch.float16) n = nweights // codec.D_SUB idx = torch.randint(0, 256, (stages, n), device=DEV, dtype=torch.uint8) scale = torch.randn(nweights // 2048, 1, device=DEV, dtype=torch.float16) def run(): acc = C[0][idx[0].long()] for s in range(1, stages): acc = acc + C[s][idx[s].long()] return (acc.view(-1, 2048) * scale).view(-1) for _ in range(3): run() torch.cuda.synchronize() t0 = time.perf_counter() for _ in range(reps): run() torch.cuda.synchronize() dt = (time.perf_counter() - t0) / reps packed = nweights * stages * codec.CB_BITS / codec.D_SUB / 8 return dict(stages=stages, bits=stages * codec.BITS_PER_STAGE, weights_per_s=nweights / dt, fp16_equiv_GBs=nweights * 2 / dt / 1e9, packed_GBs=packed / dt / 1e9) def bench_hadamard(dim=8192, batch=1, reps=200): x = torch.randn(batch, dim, device=DEV) for _ in range(3): codec._fwht(x) torch.cuda.synchronize() t0 = time.perf_counter() for _ in range(reps): codec._fwht(x) torch.cuda.synchronize() return (time.perf_counter() - t0) / reps * 1e6 # microseconds def bench_matmul(): out = {} for m, k, n in [(1, 8192, 2048), (32, 8192, 2048), (2048, 8192, 2048)]: a = torch.randn(m, k, device=DEV, dtype=torch.float16) b = torch.randn(k, n, device=DEV, dtype=torch.float16) for _ in range(3): a @ b torch.cuda.synchronize() reps = 50 t0 = time.perf_counter() for _ in range(reps): a @ b torch.cuda.synchronize() dt = (time.perf_counter() - t0) / reps out[f"{m}x{k}x{n}"] = dict(tflops=2 * m * k * n / dt / 1e12, ms=dt * 1e3) return out if __name__ == "__main__": res = {"decode": [bench_decode(s) for s in [2, 3, 4]], "hadamard_us": {str(d): bench_hadamard(d) for d in [2048, 4096, 8192]}, "matmul": bench_matmul(), "gpu": torch.cuda.get_device_name(0)} for d in res["decode"]: print(f"decode {d['bits']:.1f} bit: {d['weights_per_s']/1e9:.2f} Gweight/s " f"= {d['fp16_equiv_GBs']:.1f} GB/s fp16-equivalent, " f"{d['packed_GBs']:.2f} GB/s of packed bytes consumed") print("hadamard (us):", {k: round(v, 1) for k, v in res["hadamard_us"].items()}) for k, v in res["matmul"].items(): print(f"matmul {k}: {v['tflops']:.2f} TFLOP/s") json.dump(res, open(os.path.join(RES, "decode_bench.json"), "w"), indent=2)