NVIDIA Nsight Python Tutorial: How to Profile GPU Kernels
In this tutorial, we implement on Nsight Python, NVIDIA’s open-source Python interface to its kernel profilers.Instead of running a script under the Nsight Compute command line and digging through a report afterward, we mark the code we care about with nsight.
annotate, decorate a benchmark function with nsight.analyze.kernel, and get back a pandas DataFrame of hardware metrics per annotated region, per configuration, and per run.Since version 1.
0, the library attaches Nsight Compute to the running Python process, making it usable in Jupyter and Colab, and the upcoming 1.1 release adds an experimental CUPTI backend, explicit tool management, and custom information collectors.
We run everything on a free Colab T4: we install a current Nsight Compute next to the one Colab ships, profile a first kernel, decide how many runs a measurement needs, measure what cache and clock control do to the same kernel, sweep matrix sizes in fp32 and fp16 with a derived TFLOP/s metric, use hardware counters to tell compute-bound from memory-bound work, measure kernel fusion in bytes moved, record clocks and temperature per run, compare the CUPTI backend with Nsight Compute, and keep the raw report for deeper analysis.
Copy CodeCopiedUse a different Browserimport os import sys import glob import json import time import shutil import textwrap import traceback import subprocess RESULTS = {} def banner(title): print("\n" + "=" 78) print(title) print("=" 78) def section(name): def wrap(fn): def run(a, kw): banner(name) try: out = fn(a, kw) RESULTS[name] = out if isinstance(out, str) else "ok" return out except Exception as e: RESULTS[name] = f"SKIPPED / FAILED -> {type(e).
name}: {str(e).splitlines()[0][:160]}" print(f"\n[!] {name} did not complete: {type(e).name}: {e}") traceback.printexc(limit=3) return None return run return wrap def sh(cmd): """Run a shell command and return its stdout, stripped.""" return subprocess.
run(cmd, shell=True, captureoutput=True, text=True).stdout.strip() banner("1.Install a current Nsight Compute next to Colab's, then import nsight before CUDA") print(f" GPU: {sh('nvidia-smi --query-gpu=name,driverversion,memory.total,computecap --format=csv,noheader')}") preinstalled = shutil.
which("ncu") print(f" ncu already on PATH: {preinstalled} -> {sh('ncu --version | tail -1') if preinstalled else 'none'}") # nsight-python needs Nsight Compute 2026.2.1 or newer.
Colab ships an older ncu, but its image already # carries NVIDIA's CUDA apt repository, so a current release is one apt-get away.It installs into # /opt/nvidia/nsight-compute// and leaves the preinstalled one untouched.subprocess.run("apt-get update -qq > /tmp/ncuinstall.
log 2>&1", shell=True) for NCUVERSION in ("2026.3.1", "2026.2.1"): if subprocess.run(f"apt-get install -y -qq nsight-compute-{NCUVERSION} >> /tmp/ncuinstall.log 2>&1", shell=True).returncode == 0: break else: print(sh("tail -5 /tmp/ncuinstall.
log")) raise RuntimeError("could not install Nsight Compute 2026.2.1+ from NVIDIA's apt repository") # ask dpkg where the package put the ncu launcher rather than assuming /opt/nvidia/nsight-compute// ncupaths = sh(f"dpkg -L nsight-compute-{NCUVERSION} | grep -E '/ncu$'").
split() if not ncupaths: raise RuntimeError(f"dpkg lists no ncu executable in nsight-compute-{NCUVERSION}") NCUDIR = os.path.dirname(min(ncupaths, key=len)) # the top-level launcher, not a per-platform copy os.environ["PATH"] = NCUDIR + os.pathsep + os.
environ["PATH"] # nsight-python looks ncu up on PATH print(f" installed: {shutil.which('ncu')} -> {sh('ncu --version | tail -1')}") # nsight-python 1.1.0 (CUPTI backend, tool APIs, info collectors) is tagged but not yet on PyPI; # pin the commit this notebook was written against.
The [cupti] extra is used in step 9.NSIGHTCOMMIT = "bb96db4260b1823d86ecab9acfed0646d7af79ad" subprocess.run([sys.executable, "-m", "pip", "install", "-q", f"nsight-python @ git+https://github.com/NVIDIA/nsight-python@{NSIGHTCOMMIT}"], check=True) # The CUPTI backend needs cupti-python 13.
4, which wants a newer libcupti than Colab's torch is pinned to.# Install it into a separate directory that only step 9's child process puts on its path.CUPTIDIR = "/content/cuptienv" CUPTIEXTRA = subprocess.run([sys.
executable, "-m", "pip", "install", "-q", "--target", CUPTIDIR, "--no-deps", "cupti-python>=13.4.0", "nvidia-cuda-cupti~=13.4", "pyelftools"]).returncode == 0 import nsight # activates Nsight Compute's injection library: must come before anything initializes CUDA from nsight.
collection import ncu as ncubackend import numpy as np import pandas as pd import torch SILENT = nsight.VerbosityLevel.SILENT pd.setoption("display.width", 200) pd.setoption("display.maxcolumns", 30) print(f" nsight-python {nsight.version} | active tool: {nsight.
getactivetool()}" f" | injection error at import: {ncubackend.injectionloaderror}") print(f" torch {torch.version} (CUDA {torch.version.cuda}) | {torch.cuda.
getdevicename(0)}" f" | cupti-python installed: {CUPTIEXTRA}") print("\n Order matters: import nsight loads Nsight Compute into this Python process, and it can only") print(" attach to CUDA work started after that.
Every profiled function below runs in this same") print(" process; nsight-python starts ncu --mode attach on its own PID for each one.") We start by checking the GPU and the profiler.Nsight Python requires the Nsight Compute command-line tool, ncu, at version 2026.2.
1 or later, and finds it by looking it up on the PATH.Colab’s GPU image ships an older Nsight Compute.Still, it already has NVIDIA’s CUDA package repository configured, so we install Nsight Compute 2026.3.
1 with apt-get, ask dpkg where the ncu launcher landed, and put that directory first on the PATH.We then install Nsight Python, pinned to the commit of the 1.1.
0 pre-release this notebook was written against, and the cupti-python package into a separate directory, because it needs a newer CUPTI library than the one Colab’s PyTorch is pinned to.
The import order matters: import nsight loads Nsight Compute’s injection library into the Python process, and it can only attach to CUDA work started after that, so nsight must be imported before torch touches the GPU.
Copy CodeCopiedUse a different BrowserADD = lambda x, y: x + y # sums a metric if cuBLAS splits one matmul into several kernels @nsight.analyze.kernel(thermalmode="off", combinekernelmetrics=ADD) def firstmatmul(n: int) -> None: a = torch.randn(n, n, device="cuda") b = torch.
randn(n, n, device="cuda") with nsight.annotate("matmul"): = a @ b @section("2.Profile one kernel: what a ProfileResults row contains") def firstprofile(): df = firstmatmul(2048).todataframe() print(f"\n todataframe() columns: {list(df.columns)}\n") r = df.
iloc[0] t = float(r["AvgValue"]) print(f" annotation {r['Annotation']!r}, n = {r['n']}, kernel {r['Kernel']}") print(f" {r['Metric']} = {t:,.
0f} {r['Unit']} (runs {r['NumRuns']}, stable: {r['StableMeasurement']})") print(f" GPU {r['GPU']}, ComputeClock {r['ComputeClock']}, MemoryClock {r['MemoryClock']}") print(f" -> {2 2048 3 / (t 1e-9) / 1e12:.2f} TFLOP/s for a 2048 x 2048 fp32 matmul") print("\n Only the kernel launched inside nsight.
annotate() is profiled; torch.randn above it is not.") print(" With a single run, StableMeasurement is : one sample has no spread to judge.") return f"fp32 2048 matmul {t / 1e6:.3f} ms ({2 2048 3 / (t 1e-9) / 1e12:.
2f} TFLOP/s)" firstprofile() The first profile is a single fp32 matrix multiplication.The benchmark function creates its inputs, then wraps only the multiplication in nsight.annotate, so the random-number kernels that build the inputs are not measured.
Calling the decorated function starts ncu in attach mode on the notebook’s own process, runs the function, and returns a ProfileResults object whose to_dataframe method gives one row per annotation, configuration, and metric.We print the columns and rea
Related
相關文章
一加 Ace 7 Pro 火爆熱銷:首銷銷量同比上漲 225%
10月29日,「性能直升跨代之作」一加 Ace 7 系列發佈即開售,憑藉“性能直升一代、遊戲橫掃全場”的超旗艦體驗首銷告捷,一加 Ace 7 Pro 首銷銷量同比一加 Ace 6上漲225%,同時,一加 16 和一加 Ace 7 Pro 包攬2026 年安卓手機首銷銷量冠軍和亞軍。一加中國區總裁李傑表示:“一加 Ace 7 系列性能、屏幕、影像全面領先,好產品自己會說話。 一加 Ace 7 系列的實際體驗,相信大家上手之後會更加驚喜。
腦景中心啟幕、四款新品齊發!熵基科技加碼非侵入式腦機接口全棧技術與應用平臺
10月29日,以"BE THE CHANGE MAKER"為主題的熵基科技全球合作伙伴大會2026在東莞啟幕,會期將持續至10月31日。本屆大會聚焦原生AI發展趨勢,圍繞空間智能、腦機接口與人工智能融合創新,以及全球產業生態協同展開,集中呈現熵基科技在技術創新、產品研發與場景應用方面的最新進展。大會期間,ZKBrainScape腦景中心正式啟幕,MarsLume火星慧知AI全域解決方案全球發佈,熵基科技攜手生態夥伴聯合發佈四款腦機接口新品,並通過產業合作與技術交流,探索創新技術走向真實場景的更多路徑。
推理蒸餾開始改寫教師解題軌跡
Computer Science > Artificial Intelligence arXiv:2610.36445 (cs) [Submitted on 27 Oct 2026] Title:From Solver Trajectories to Teaching Trajectories: Cognition-Aligned Reasoning Distillation Authors:Yashuo Luo, Qianren Ma。
OpenAI官宣數學與物理學三大突破:AI攻克百年猜想,攜手全球學者開啟科學驗證新模式
為了將這些前沿的原始研究數據轉化為真正的科學理解,OpenAI創新性地嘗試了與外部學術社區進行深度合作的新模式,並針對不同領域的成果制定了多元化的發佈策略。在調和分析領域,模型成功給出了各維度下局部光滑(local smoothing)猜想的證明,從而在所有維度上直接解決了數學界的 Kakeya 猜想與 Stein 限制猜想。
Reddit 開源社區 r/opensource 封殺 AI 項目,開發者另起爐灶
管理團隊稱,當下 AI 的發展模式與開源理念相沖突,須以限制護住社區價值取向。一條新規,邊界模糊這條禁令迅速引爆爭論,因為它沒說清"AI 參與"的紅線在哪。如今開發普遍用 AI 輔助編程、代碼補全和自動測試,主體由人寫的項目也可能夾帶 AI 生成的片段;用戶甚至點出,Linux 內核也已出現 AI 生成代碼——若按字面執行,海量主流開源軟件都可能被擋在門外。
全球互聯網經歷“黑色十月”,這個中國AI在風暴來臨前留了後手
作者 | Saul 編輯 | 漠影 過去48小時,全球互聯網經歷“黑色十月”:支撐七成網站的PHP代碼,被AI挖出存在兩個CVSS9.2分的嚴重漏洞。更棘手的是,漏洞細節在補丁發佈前就遭洩露:據The Register報道,亞馬遜的威脅情報團隊在公開前四天就捕獲了利用嘗試; Cloudflare的監測數據顯示,攻擊嘗試在公開後兩小時內從數千次漲到數百萬次。