#!/bin/bash # nsys/ncu wrapper that emits a DIAGNOSIS, not a report dump. # # ./profile.sh nsys python3 bench.py # is the time even in a kernel? # ./profile.sh ncu python3 bench.py # which resource is saturated? # KERNEL=my_kern ./profile.sh ncu python3 bench.py # restrict to matching kernels (regex) # # ncu needs GPU performance counters. Run the container with --cap-add SYS_ADMIN, or have the host set # NVreg_RestrictProfilingToAdminUsers=0. `ncu --version` succeeding proves nothing -- it never touches # a counter. Without permission you get ERR_NVGPUCTRPERM. set -uo pipefail MODE=${1:-ncu}; shift if [ "$MODE" = "nsys" ]; then O=/tmp/_nsys.$$ nsys profile -o $O --force-overwrite true --trace=cuda,nvtx,osrt "$@" >/dev/null 2>&1 echo "== per-kernel totals ==" nsys stats --report cuda_gpu_kern_sum $O.nsys-rep 2>/dev/null | sed -n '/Time (%)/,$p' | head -14 echo echo "Read this first: if the summed kernel time is far below wall time, you are HOST-BOUND --" echo "launch gaps, dispatch, or H2D/D2H. Fix that before opening ncu." echo "Report kept at $O.nsys-rep -- open the timeline for gaps and missing overlap." exit 0 fi REP=/tmp/_ncu.$$; LOG=/tmp/_ncu.log.$$ ncu --target-processes all ${KERNEL:+--kernel-name regex:$KERNEL} --launch-skip 3 --launch-count 3 \ --section SpeedOfLight --section MemoryWorkloadAnalysis \ --section WarpStateStats --section Occupancy \ --metrics sm__throughput.avg.pct_of_peak_sustained_elapsed,\ gpu__dram_throughput.avg.pct_of_peak_sustained_elapsed,\ l1tex__t_sectors_per_request.avg,\ l1tex__data_bank_conflicts_pipe_lsu_mem_shared.sum,\ sm__warps_active.avg.pct_of_peak_sustained_active,\ launch__registers_per_thread \ -o $REP --force-overwrite "$@" >$LOG 2>&1 if grep -q ERR_NVGPUCTRPERM $LOG; then echo "ERR_NVGPUCTRPERM -- no access to GPU performance counters." echo " fix: run the container with --cap-add SYS_ADMIN, or set" echo " NVreg_RestrictProfilingToAdminUsers=0 on the host." exit 1 fi if [ ! -f $REP.ncu-rep ]; then echo "ncu produced no report. Last lines:"; tail -5 $LOG; exit 1 fi ncu -i $REP.ncu-rep --csv 2>/dev/null > /tmp/_ncu.csv.$$ python3 - /tmp/_ncu.csv.$$ <<'PY' import csv, sys rows = list(csv.DictReader(open(sys.argv[1]))) if not rows: print("no kernels matched." + (" Loosen or drop KERNEL=." if __import__("os").environ.get("KERNEL") else "")) raise SystemExit(1) kern = rows[0].get("Kernel Name", "?") def get(name): for r in rows: if r.get("Metric Name", "").strip() == name: try: return float(r["Metric Value"].replace(",", "")) except Exception: return None # ncu prints 'n/a' for metrics it could not collect return None sm = get("sm__throughput.avg.pct_of_peak_sustained_elapsed") dram = get("gpu__dram_throughput.avg.pct_of_peak_sustained_elapsed") sect = get("l1tex__t_sectors_per_request.avg") bank = get("l1tex__data_bank_conflicts_pipe_lsu_mem_shared.sum") occ = get("sm__warps_active.avg.pct_of_peak_sustained_active") regs = get("launch__registers_per_thread") f = lambda v, u="": "n/a" if v is None else f"{v:.1f}{u}" print(f"kernel: {kern[:70]}") print(f"SM {f(sm,'%')} DRAM {f(dram,'%')} occupancy {f(occ,'%')} " f"sectors/req {f(sect)} bank-conflicts {f(bank)} regs/thread {f(regs)}") print("\nDIAGNOSIS") if sm is not None and dram is not None: if sm > 60 and dram < 40: print(" COMPUTE-BOUND -> tensor cores, better instruction mix, less redundant work") elif dram > 60 and sm < 40: print(" BANDWIDTH-BOUND -> cut traffic, fuse passes, improve reuse") elif sm < 40 and dram < 40: print(" LATENCY-BOUND -> read WarpStateStats; more loads in flight (cp.async/TMA), more ILP") else: print(" MIXED -> attack whichever of SM/DRAM is higher first") else: print(" SpeedOfLight metrics unavailable -- open the report by hand.") if sect and sect > 4.5: print(f" UNCOALESCED: {sect:.1f} sectors/request (4 is ideal) -> fix layout/access pattern") if bank: print(f" SHARED-MEM BANK CONFLICTS: {bank:.0f} -> swizzle (do NOT pad 2-byte types)") if occ and occ < 30: print(f" LOW OCCUPANCY {occ:.0f}% -> run tools/occupancy.py to find the limiter") if regs and regs >= 168: print(f" {regs:.0f} regs/thread -> spills likely; check SASS for LDL/STL") print("\nReminder: never take a TIMING from a run under ncu -- it serializes and replays kernels.") PY echo "full report: ncu -i $REP.ncu-rep --page details" rm -f /tmp/_ncu.csv.$$ $LOG