[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,89 +2,273 @@
|
||||
id: wiki-2026-0508-gpu-programming-with-cuda
|
||||
title: GPU Programming with CUDA
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [HW-CUDA-001]
|
||||
aliases: [CUDA, GPU programming, kernel, Triton, cuBLAS, cuDNN, ROCm, HIP]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: ["Hardware|[Hardware", gpu, cuda, Parallel-Computing, c-cpp, ai-acceleration]
|
||||
confidence_score: 0.95
|
||||
verification_status: applied
|
||||
tags: [cuda, gpu-programming, kernel, parallel, triton, hip]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: CUDA / C++ / Triton / Python
|
||||
framework: CUDA Toolkit / cuBLAS / Triton / Numba
|
||||
---
|
||||
|
||||
# GPU Programming with CUDA (CUDA를 이용한 GPU 프로그래밍)
|
||||
# GPU Programming with CUDA
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "하드웨어의 수천 개 코어를 지휘하는 지휘자가 되어, 데이터의 파도를 병렬 연산의 폭풍으로 바꿔라" — NVIDIA의 하드웨어를 활용하여 일반적인 프로그래밍 언어(C/C++)로 고도의 병렬 연산을 수행하게 하는 컴퓨팅 플랫폼이자 프로그래밍 모델.
|
||||
## 매 한 줄
|
||||
> **"매 NVIDIA GPU 의 의 의 parallel kernel 의 write"**. 매 kernel + grid + block + warp + memory hierarchy. 매 modern: Triton (Python), cuBLAS / cuDNN (libraries), CUDA Graphs (efficient launch). 매 alternative: HIP (AMD), Metal (Apple), WGSL (cross-platform).
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Single Instruction, Multiple Threads (SIMT)" — 하나의 명령을 수많은 데이터에 동시에 적용하기 위해 작업을 그리드(Grid), 블록(Block), 스레드(Thread) 단위로 쪼개어 GPU 하드웨어에 매핑하는 병렬 코딩 패턴.
|
||||
- **핵심 개념:**
|
||||
- **Kernel:** GPU에서 병렬로 실행되는 함수 단위.
|
||||
- **[[memory|memory]] Hierarchy:** Host(CPU)와 Device(GPU) 간의 메모리 복사, 그리고 Global, Shared, Local 메모리의 전략적 활용.
|
||||
- **Parallelism [[Optimization|Optimization]]:** 스레드 간의 데이터 동기화와 메모리 접근 패턴(Coalescing) 최적화.
|
||||
- **Libraries:** cuBLAS, cuDNN 등 딥러닝 연산에 최적화된 저수준 라이브러리 활용.
|
||||
- **의의:** 딥러닝 프레임워크(PyTorch, TensorFlow)의 밑바닥을 지탱하며, AI 연구자가 하드웨어의 성능을 100% 이끌어낼 수 있게 함.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 그래픽 연산 언어(Shader)를 빌려 쓰던 불편함에서 벗어나, 표준 프로그래밍 언어와 유사한 문법으로 범용 GPU 연산(GPGPU)을 수행하는 시대로 진화.
|
||||
- **정책 변화:** Antigravity 프로젝트는 대규모 벡터 연산이나 커스텀 신경망 레이어 최적화가 필요할 때, CUDA 커널을 직접 작성하거나 최적화된 하드웨어 가속 라이브러리를 호출하여 성능 병목을 해결함.
|
||||
### 매 hierarchy
|
||||
- **Grid** = blocks.
|
||||
- **Block** = threads (typically 128-256).
|
||||
- **Warp** = 32 threads (SIMT).
|
||||
- **Thread** = unit of execution.
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- [[GPU-Architecture|GPU-Architecture]]-for-AI, [[Parallel-Computing|Parallel-Computing]], [[Distributed-Computing|Distributed-Computing]], [[Deep-Learning|Deep-Learning]]-Foundations
|
||||
- **Raw Source:** 10_Wiki/Topics/AI/GPU-Programming-with-CUDA.md
|
||||
### 매 memory
|
||||
- **Global** (HBM): 매 large, slow.
|
||||
- **L2 cache**.
|
||||
- **Shared** (SMEM): 매 fast on-chip.
|
||||
- **Register**: 매 fastest.
|
||||
- **Texture / constant**.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. **ML kernels** (matmul, attention).
|
||||
2. **HPC** (FFT, PDE).
|
||||
3. **Graphics** (raster + RT).
|
||||
4. **Image / video processing**.
|
||||
5. **Scientific** (CFD, MD).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
### 매 ecosystem
|
||||
- **CUDA Toolkit**: nvcc, cuBLAS, cuDNN, NCCL.
|
||||
- **Triton**: 매 OpenAI, Python kernel.
|
||||
- **CUTLASS**: 매 templated.
|
||||
- **Thrust**: 매 STL-like.
|
||||
- **Numba**: 매 Python @cuda.jit.
|
||||
- **HIP / ROCm**: AMD.
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
### Vector add (basic)
|
||||
```cuda
|
||||
__global__ void vec_add(float* a, float* b, float* c, int N) {
|
||||
int i = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (i < N) c[i] = a[i] + b[i];
|
||||
}
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
int main() {
|
||||
float *d_a, *d_b, *d_c;
|
||||
cudaMalloc(&d_a, N * sizeof(float));
|
||||
cudaMalloc(&d_b, N * sizeof(float));
|
||||
cudaMalloc(&d_c, N * sizeof(float));
|
||||
cudaMemcpy(d_a, h_a, N * sizeof(float), cudaMemcpyHostToDevice);
|
||||
cudaMemcpy(d_b, h_b, N * sizeof(float), cudaMemcpyHostToDevice);
|
||||
|
||||
int block = 256, grid = (N + block - 1) / block;
|
||||
vec_add<<<grid, block>>>(d_a, d_b, d_c, N);
|
||||
|
||||
cudaMemcpy(h_c, d_c, N * sizeof(float), cudaMemcpyDeviceToHost);
|
||||
cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Matrix multiply (shared memory tiling)
|
||||
```cuda
|
||||
__global__ void matmul_shared(float* A, float* B, float* C, int N) {
|
||||
__shared__ float As[TILE][TILE];
|
||||
__shared__ float Bs[TILE][TILE];
|
||||
|
||||
int tx = threadIdx.x, ty = threadIdx.y;
|
||||
int row = blockIdx.y * TILE + ty;
|
||||
int col = blockIdx.x * TILE + tx;
|
||||
|
||||
float sum = 0;
|
||||
for (int t = 0; t < N / TILE; ++t) {
|
||||
As[ty][tx] = A[row * N + t * TILE + tx];
|
||||
Bs[ty][tx] = B[(t * TILE + ty) * N + col];
|
||||
__syncthreads();
|
||||
for (int k = 0; k < TILE; ++k)
|
||||
sum += As[ty][k] * Bs[k][tx];
|
||||
__syncthreads();
|
||||
}
|
||||
C[row * N + col] = sum;
|
||||
}
|
||||
```
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Reduction (parallel sum)
|
||||
```cuda
|
||||
__global__ void reduce_sum(float* in, float* out, int N) {
|
||||
__shared__ float sdata[256];
|
||||
int tid = threadIdx.x;
|
||||
int i = blockIdx.x * blockDim.x + tid;
|
||||
sdata[tid] = (i < N) ? in[i] : 0;
|
||||
__syncthreads();
|
||||
|
||||
for (int s = blockDim.x / 2; s > 0; s >>= 1) {
|
||||
if (tid < s) sdata[tid] += sdata[tid + s];
|
||||
__syncthreads();
|
||||
}
|
||||
if (tid == 0) atomicAdd(out, sdata[0]);
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Triton (Python kernel)
|
||||
```python
|
||||
import triton
|
||||
import triton.language as tl
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
@triton.jit
|
||||
def matmul_kernel(a_ptr, b_ptr, c_ptr, M, N, K, BLOCK_M: tl.constexpr, BLOCK_N: tl.constexpr, BLOCK_K: tl.constexpr):
|
||||
pid_m = tl.program_id(0)
|
||||
pid_n = tl.program_id(1)
|
||||
|
||||
offs_m = pid_m * BLOCK_M + tl.arange(0, BLOCK_M)
|
||||
offs_n = pid_n * BLOCK_N + tl.arange(0, BLOCK_N)
|
||||
|
||||
acc = tl.zeros((BLOCK_M, BLOCK_N), dtype=tl.float32)
|
||||
for k in range(0, K, BLOCK_K):
|
||||
offs_k = k + tl.arange(0, BLOCK_K)
|
||||
a = tl.load(a_ptr + offs_m[:, None] * K + offs_k[None, :])
|
||||
b = tl.load(b_ptr + offs_k[:, None] * N + offs_n[None, :])
|
||||
acc += tl.dot(a, b)
|
||||
|
||||
tl.store(c_ptr + offs_m[:, None] * N + offs_n[None, :], acc)
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Numba (Python @cuda.jit)
|
||||
```python
|
||||
from numba import cuda
|
||||
import numpy as np
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
@cuda.jit
|
||||
def add_kernel(a, b, out):
|
||||
i = cuda.grid(1)
|
||||
if i < a.size: out[i] = a[i] + b[i]
|
||||
|
||||
a = np.arange(1_000_000, dtype=np.float32)
|
||||
b = np.arange(1_000_000, dtype=np.float32)
|
||||
d_a = cuda.to_device(a); d_b = cuda.to_device(b)
|
||||
d_out = cuda.device_array_like(a)
|
||||
add_kernel[(a.size + 255) // 256, 256](d_a, d_b, d_out)
|
||||
out = d_out.copy_to_host()
|
||||
```
|
||||
|
||||
### cuBLAS (use library)
|
||||
```cuda
|
||||
#include <cublas_v2.h>
|
||||
cublasHandle_t handle; cublasCreate(&handle);
|
||||
const float alpha = 1, beta = 0;
|
||||
cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, M, N, K, &alpha, A, M, B, K, &beta, C, M);
|
||||
// 매 vs hand-written 의 1.5-3x faster
|
||||
```
|
||||
|
||||
### CUDA Graphs (efficient launch)
|
||||
```cuda
|
||||
cudaGraph_t graph;
|
||||
cudaGraphCreate(&graph, 0);
|
||||
// 매 build graph (sequence of kernels)
|
||||
cudaStream_t stream;
|
||||
cudaStreamBeginCapture(stream, cudaStreamCaptureModeGlobal);
|
||||
kernel1<<<...>>>(...);
|
||||
kernel2<<<...>>>(...);
|
||||
cudaStreamEndCapture(stream, &graph);
|
||||
|
||||
cudaGraphExec_t exec;
|
||||
cudaGraphInstantiate(&exec, graph, nullptr, nullptr, 0);
|
||||
// 매 매 frame 의 의 launch with single call
|
||||
cudaGraphLaunch(exec, stream);
|
||||
```
|
||||
|
||||
### Stream (async)
|
||||
```cuda
|
||||
cudaStream_t stream;
|
||||
cudaStreamCreate(&stream);
|
||||
cudaMemcpyAsync(d_a, h_a, size, cudaMemcpyHostToDevice, stream);
|
||||
kernel<<<grid, block, 0, stream>>>(d_a, ...);
|
||||
cudaMemcpyAsync(h_b, d_b, size, cudaMemcpyDeviceToHost, stream);
|
||||
cudaStreamSynchronize(stream);
|
||||
```
|
||||
|
||||
### Profiling (Nsight Compute)
|
||||
```bash
|
||||
ncu --set full -o profile ./my_app
|
||||
ncu-ui profile.ncu-rep
|
||||
# 매 occupancy, instruction throughput, memory bandwidth
|
||||
```
|
||||
|
||||
### HIP (AMD equivalent)
|
||||
```cpp
|
||||
__global__ void hip_add(float* a, float* b, float* c, int N) {
|
||||
int i = hipBlockIdx_x * hipBlockDim_x + hipThreadIdx_x;
|
||||
if (i < N) c[i] = a[i] + b[i];
|
||||
}
|
||||
hipLaunchKernelGGL(hip_add, dim3((N+255)/256), dim3(256), 0, 0, a, b, c, N);
|
||||
```
|
||||
|
||||
### Custom op in PyTorch
|
||||
```cpp
|
||||
// 매 register
|
||||
TORCH_LIBRARY(my_ops, m) {
|
||||
m.def("vec_add(Tensor a, Tensor b) -> Tensor");
|
||||
}
|
||||
|
||||
torch::Tensor vec_add(torch::Tensor a, torch::Tensor b) {
|
||||
auto c = torch::empty_like(a);
|
||||
int N = a.numel();
|
||||
vec_add_kernel<<<(N+255)/256, 256>>>(a.data_ptr<float>(), b.data_ptr<float>(), c.data_ptr<float>(), N);
|
||||
return c;
|
||||
}
|
||||
```
|
||||
|
||||
### Occupancy calculator
|
||||
```cuda
|
||||
int max_blocks_per_sm = 0;
|
||||
cudaOccupancyMaxActiveBlocksPerMultiprocessor(&max_blocks_per_sm, kernel, threads_per_block, 0);
|
||||
// 매 50%+ occupancy ideal
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| New kernel | Triton (Python easy) |
|
||||
| Production matmul | cuBLAS |
|
||||
| ML attention | Flash Attention |
|
||||
| Hand-tuned | CUTLASS / pure CUDA |
|
||||
| Graph workload | CUDA Graphs |
|
||||
| AMD | HIP / ROCm |
|
||||
| Cross-platform | WGSL / Metal / Vulkan |
|
||||
|
||||
**기본값**: 매 use library (cuBLAS/cuDNN) when possible + 매 Triton for Python research + 매 CUDA Graphs for repeated launches + 매 profile with Nsight.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[GPU]] · [[Parallel-Programming]]
|
||||
- 변형: [[CUDA]] · [[Triton]] · [[HIP]]
|
||||
- 응용: [[cuBLAS]] · [[Flash Attention]] · [[Compute-Shader]]
|
||||
- Adjacent: [[GPU-Architecture]] · [[Numba]] · [[Cutlass]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: 매 ML kernel research. 매 HPC. 매 custom op.
|
||||
**언제 X**: 매 framework op sufficient.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Hand-write before profile**: 매 wrong opt.
|
||||
- **Ignore occupancy**: 매 underutilize.
|
||||
- **No SMEM tiling**: 매 memory-bound.
|
||||
- **Sync host every kernel**: 매 latency.
|
||||
- **No CUDA Graphs for repeated**: 매 launch overhead.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (CUDA programming guide, Triton docs, NVIDIA HPC).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — kernels + 매 vec / matmul / Triton / Numba / Graphs / cuBLAS code |
|
||||
|
||||
Reference in New Issue
Block a user