集中准备手撕代码、系统设计、性能分析三类核心问题。每天练习1-2道手撕题。
// Shared Memory优化的矩阵乘法 #define TILE_SIZE 16 __global__ void matmul_shared(float *A, float *B, float *C, int N) { __shared__ float As[TILE_SIZE][TILE_SIZE]; __shared__ float Bs[TILE_SIZE][TILE_SIZE]; int bx = blockIdx.x, by = blockIdx.y; int tx = threadIdx.x, ty = threadIdx.y; int row = by * TILE_SIZE + ty; int col = bx * TILE_SIZE + tx; float sum = 0.0f; for (int t = 0; t < N/TILE_SIZE; ++t) { // 协作加载到Shared Memory As[ty][tx] = A[row * N + t * TILE_SIZE + tx]; Bs[ty][tx] = B[(t * TILE_SIZE + ty) * N + col]; __syncthreads(); // 计算部分和 for (int k = 0; k < TILE_SIZE; ++k) sum += As[ty][k] * Bs[k][tx]; __syncthreads(); } C[row * N + col] = sum; }
// 高效Softmax实现 __global__ void softmax_kernel(float *input, float *output, int n) { __shared__ float shared_max; __shared__ float shared_sum; int tid = threadIdx.x + blockIdx.x * blockDim.x; // Step 1: 找最大值 (Warp归约) float val = (tid < n) ? input[tid] : -INFINITY; float max_val = val; for (int offset = 16; offset > 0; offset >>= 1) { float other = __shfl_down_sync(0xFFFFFFFF, max_val, offset); max_val = fmaxf(max_val, other); } // Step 2: 计算exp和求和 float exp_val = (tid < n) ? expf(val - max_val) : 0.0f; // ... 归约求和 ... // Step 3: 归一化 if (tid < n) output[tid] = exp_val / sum_val; }
// 系统架构
┌─────────────────────────────────────────┐
│ Load Balancer │
├─────────────────────────────────────────┤
│ │ │ │ │ │
│ ▼ ▼ ▼ ▼ │
│ ┌─────┐ ┌─────┐ ┌─────┐ ┌─────┐ │
│ │GPU 0│ │GPU 1│ │GPU 2│ │GPU 3│ │
│ └─────┘ └─────┘ └─────┘ └─────┘ │
│ │
│ ┌─────────────────────────────────────┐ │
│ │ KV Cache Manager │ │
│ │ (PagedAttention + CoW) │ │
│ └─────────────────────────────────────┘ │
│ │
│ ┌─────────────────────────────────────┐ │
│ │ Request Scheduler │ │
│ │ (Continuous Batching) │ │
│ └─────────────────────────────────────┘ │
└─────────────────────────────────────────┘