메뉴
HN
Hacker News • 1일 전

에이전트 기반 CUDA 커널 최적화 도구 공개

IMP
6/10
핵심 요약

해커뉴스에 LangGraph 기반 '에이전트형 CUDA 커널 옵티마이저'가 공개되었습니다. 워크로드 설명만 입력하면 GPU 구현을 자동 생성하고, 컴파일·정확성 검증·벤치마크·개선을 반복하며 가장 빠른 검증 커널을 선별합니다. NVIDIA 문서 조회와 Nsight Compute 프로파일링 카운터 확인도 지원해 GPU 커널 최적화 업무의 자동화 가능성을 보여준다는 점에서 주목할 만합니다.

번역된 본문

CUDA 커널 옵티마이저

목차: 작동 방식 / 설정 / 실행 / 예시 / 결과 및 한계 / 워크플로 그래프

에이전트형 CUDA 커널 옵티마이저는 워크로드 설명을 GPU 구현으로 변환하는 도구로, 코드 생성, 정확성 검증, 벤치마킹, 개선을 자동으로 반복하는 사이클을 통해 동작합니다. LangGraph 기반으로 구동되며, 에이전트는 커널 구현과 실행(런치) 구성을 탐색하고, GPU 속성을 조회하며, 최적화 가이던스를 위해 NVIDIA 문서를 검색하고 Nsight Compute 카운터를 확인하여 다음 실험에 반영할 수 있습니다. 각 실험은 기록되며, 검증된 구현 중 가장 빠른 것이 유지됩니다. 모델은 커널 코드와 케이스별 실행 구성을 모두 변경할 수 있습니다. 독립형 C++ 하네스가 NVRTC로 커널을 컴파일하고 CUDA 드라이버 API를 통해 실행한 뒤 출력을 저장합니다. Python은 비교와 후보 선택을 담당합니다.

작동 방식

  1. 시그니처, 입력 케이스, 참조 커널, 초기 커널을 로드하거나 생성합니다.
  2. 참조 커널을 실행하고 초기 구현을 평가합니다.
  3. 변경을 제안하고 컴파일한 뒤, 출력을 NumPy로 비교하고 커널 지연 시간을 측정합니다.
  4. 결과를 다음 시도에 피드백하고, 반복 예산 내에서 유효하지 않은 후보를 수리합니다.
  5. 가장 빠른 검증된 후보, 실행 이력, 타이밍 히트맵을 저장합니다.

모든 케이스는 검증을 통과해야 합니다. 순위는 성능 케이스 전체의 지연 시간 기하 평균으로 매겨지며, 작은 정확성 케이스는 점수에 영향을 주지 않습니다. 타이밍은 기본적으로 10회 워밍업 실행과 CUDA 이벤트를 이용한 100회 측정 실행으로 수행합니다. 컴파일 시간과 프로파일러 리플레이 타이밍은 순위에서 제외됩니다.

설정

Windows와 RTX 3060 노트북 GPU에서 개발되었습니다. Python 3.12+, NVIDIA GPU 및 호환되는 CUDA 툴킷/드라이버, CMake 3.24+, C++17 컴파일러, OpenAI API 키가 필요합니다. 아래 빌드 명령은 C++ 도구가 설치된 Visual Studio 2026을 기준으로 합니다. 저장소 루트에서:

python -m venv .venv .venv\Scripts\python -m pip install -r optimizer_agent/requirements.txt cmake -S cuda_test_harness -B cuda_test_harness/build -DCMAKE_BUILD_TYPE=Release cmake --build cuda_test_harness/build --parallel

저장소 루트에 .env 파일을 생성합니다: OPENAI_API_KEY=여기에-키-입력

다음과 같이 실행합니다: .venv\Scripts\python optimizer_agent/optimizer_agent.py --description "직사각 행렬 단정밀도 GEMM." --max-iterations 7

기본 모델은 중간(medium) 추론 노력의 gpt-5-mini입니다. API 사용량은 본인 계정으로 청구됩니다. 모든 옵션은 -h로 확인하거나, 포함된 설정 예시는 --config optimizer_agent/example.json으로 확인할 수 있습니다. --signature, --reference, --initial-kernel, --input-cases로 직접 워크로드 구성 요소를 제공할 수 있으며, 생략된 요소는 추론되거나 생성됩니다.

이전 실행의 저장된 입력에서 이어서 실행하려면: .venv\Scripts\python optimizer_agent/optimizer_agent.py --description "직사각 행렬 단정밀도 GEMM." --input-cases results/run-001/input_cases.json --reference results/run-001/reference.cu --initial-kernel results/run-001/best.cu --max-iterations 7

이 예시는 이전 실행이 reference.cu를 생성했다고 가정합니다. 제공된 참조는 supplied-reference.cu로 저장됩니다. 입력 매니페스트는 바이너리 데이터 경로를 유지하므로 해당 파일은 그대로 보관해야 합니다.

선택적 플래그:

  • --use-nsight: 유효한 후보마다 성능 케이스를 프로파일링하고 프로파일러 도구를 모델에 노출합니다. Nsight Compute와 GPU 성능 카운터 접근 권한이 필요합니다.
  • --nvidia-research: 커널 생성 전 NVIDIA 가이던스를 검색합니다.

예시

RTX 3060 노트북 GPU에서 NVIDIA 리서치와 Nsight Compute를 활성화한 Float32 GEMM 예시입니다.

  • Run 022: 생성된 시작 커널을 최적화
  • Run 023: Run 022의 최고 커널에서 동일한 입력과 참조로 이어서 실행

결과 및 한계

각 세션은 results/run-NNN/ 아래에 디렉터리를 받으며, 커널 소스, 요청, 입출력 데이터, 모델/도구 응답, history.json, summary.json이 포함됩니다. 성공한 실행은 best.cu, 케이스별 리플레이 요청, 히트맵을 내보냅니다.

원문 보기
원문 보기 (영어)
CUDA Kernel Optimizer Contents How it works Setup Run Examples Results and limits Workflow graph An agentic CUDA kernel optimizer that turns workload descriptions into GPU implementations through an automated cycle of code generation, correctness checks, benchmarking, and refinement. Powered by LangGraph, the agent explores kernel implementations and launch configurations, queries GPU properties, and can research NVIDIA documentation for optimization guidance and inspect Nsight Compute counters to inform its next experiment. Each experiment is recorded, and the fastest validated implementation is retained. The model can change both kernel code and per-case launch configurations. A standalone C++ harness compiles kernels with NVRTC, launches them through the CUDA Driver API, and saves outputs. Python handles comparison and candidate selection. How it works Load or generate a signature, input cases, reference kernel, and initial kernel. Run the reference and evaluate the initial implementation. Propose a change, compile it, compare outputs with NumPy, and measure kernel latency. Feed results back into the next attempt; repair invalid candidates within the iteration budget. Save the fastest validated candidate, execution history, and a timing heatmap. Every case must pass validation. Ranking uses the geometric mean of latency across performance cases; small correctness cases do not affect the score. Timing defaults to 10 warmup launches and 100 measured launches using CUDA events. Compilation time and profiler replay timings are excluded from ranking. Setup Developed on Windows with an RTX 3060 Laptop GPU. Requires Python 3.12+, an NVIDIA GPU and compatible CUDA Toolkit/driver, CMake 3.24+, a C++17 compiler, and an OpenAI API key. The build commands below use Visual Studio 2026 with the C++ tools installed. From the repository root: python - m venv .venv .venv\Scripts\python - m pip install - r optimizer_agent / requirements.txt cmake - S cuda_test_harness - B cuda_test_harness / build - DCMAKE_BUILD_TYPE = Release cmake -- build cuda_test_harness / build -- parallel Create a .env file in the repository root: OPENAI_API_KEY = your-key-here Run .venv\Scripts\python optimizer_agent / optimizer_agent.py -- description " Single-precision GEMM with rectangular matrices. " -- max - iterations 7 The default model is gpt-5-mini with medium reasoning effort. API usage is billed to your account. Use -h for all options, or --config optimizer_agent/example.json for the included configuration example. Supply your own workload components with --signature , --reference , --initial-kernel , and --input-cases . Omitted components are inferred or generated. To continue from an earlier run using its saved inputs: .venv\Scripts\python optimizer_agent / optimizer_agent.py -- description " Single-precision GEMM with rectangular matrices. " -- input - cases results / run - 001 / input_cases.json -- reference results / run - 001 / reference.cu -- initial - kernel results / run - 001 / best.cu -- max - iterations 7 This example assumes the earlier run generated reference.cu ; supplied references are saved as supplied-reference.cu . Input manifests retain paths to their binary data, so keep those files available. Optional flags: --use-nsight : profile a performance case after each valid candidate and expose profiler tools to the model. Requires Nsight Compute and permission to access GPU performance counters. --nvidia-research : retrieve NVIDIA guidance before generating kernels. Examples Float32 GEMM on an RTX 3060 Laptop GPU, with NVIDIA research and Nsight Compute enabled. Run 022 Run 023 Optimizing the generated starting kernel. Continuing from run 022's best kernel with the same inputs and reference. Results and limits Each session gets a directory under results/run-NNN/ containing kernel sources, requests, input/output data, model/tool responses, history.json , and summary.json . Successful runs export best.cu , per-case replay requests, and heatmap.png / heatmap.svg . Nsight reports are saved when profiling is enabled. This is an experimental optimizer for individual kernels. Passing supplied cases does not prove general correctness, and a generated reference is not an independent correctness oracle. Improvements are workload-dependent; no comparison against cuBLAS or other vendor libraries is currently included. Keep the GPU otherwise idle when comparing timings. Generated input scripts execute locally as Python subprocesses without a sandbox. Generated CUDA kernels also run on the local GPU. Workflow graph The graph below is rendered from the compiled LangGraph workflow with Nsight profiling enabled. Dashed edges are conditional routes. Without --use-nsight , evaluation routes directly to the next attempt or finalization; NVIDIA research is skipped unless --nvidia-research is set.