KBench / agent /tools /occupancy.py
ZMC2019's picture
Add agent/: the kernel-optimization skill and four subagents
1ab6c33 verified
Raw
History Blame Contribute Delete
2.38 kB
"""Occupancy / register / shared-memory budget, and persistent-grid co-residency.
Two questions this answers that cost the most time when guessed:
1. which resource is limiting occupancy -- registers, shared memory, or block size
2. whether a persistent kernel's grid actually fits (if it does not, a grid-wide barrier DEADLOCKS)
python3 occupancy.py --threads 256 --regs 96 --smem 49152 [--blocks 264]
"""
import argparse
import torch
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--threads", type=int, required=True)
ap.add_argument("--regs", type=int, required=True, help="registers per thread (ncu: launch__registers_per_thread)")
ap.add_argument("--smem", type=int, default=0, help="dynamic shared memory per block, bytes")
ap.add_argument("--blocks", type=int, default=0, help="grid size, to check persistent co-residency")
a = ap.parse_args()
p = torch.cuda.get_device_properties(0)
sm = p.multi_processor_count
max_thr = p.max_threads_per_multi_processor
regs_sm = p.regs_per_multiprocessor
smem_sm = getattr(p, "shared_memory_per_multiprocessor", p.shared_memory_per_block_optin)
warps_blk = (a.threads + 31) // 32
by_thread = max_thr // a.threads
by_regs = regs_sm // (a.regs * warps_blk * 32) if a.regs else 999
by_smem = (smem_sm // a.smem) if a.smem else 999
blocks_sm = max(0, min(by_thread, by_regs, by_smem))
limiter = min((by_thread, "block size"), (by_regs, "registers"), (by_smem, "shared memory"))[1]
occ = blocks_sm * warps_blk * 32 / max_thr if max_thr else 0
print(f"device {p.name} SMs={sm} max_threads/SM={max_thr} regs/SM={regs_sm} smem/SM={smem_sm//1024}KB")
print(f"blocks/SM: by-threads {by_thread}, by-registers {by_regs}, by-smem {by_smem}"
f" -> {blocks_sm} (limiter: {limiter})")
print(f"achieved occupancy {occ:.0%} resident blocks total {blocks_sm*sm}")
if a.regs >= 168:
print(" !! >=168 regs/thread: spills are likely; check SASS for LDL/STL")
if a.blocks:
cap = blocks_sm * sm
ok = a.blocks <= cap
print(f"\npersistent grid {a.blocks} vs co-resident capacity {cap}: {'FITS' if ok else 'DOES NOT FIT'}")
if not ok:
print(" !! a grid-wide barrier WILL DEADLOCK: blocks that never get scheduled cannot arrive.")
if __name__ == "__main__":
main()