Skip to content

GPU 内存模型

理解 CUDA 内存层次结构对于优化光线追踪性能至关重要。

内存层次结构

内存类型

类型容量延迟作用域用途
Global数 GB400+ cycles全局场景数据、输出缓冲
L2 Cache数 MB~30 cycles自动缓存全局内存访问
Shared48KB/SM~5 cycles块内BVH 栈、临时数据
Local256KB/SM~5 cycles线程局部变量
Register255/线程1 cycle线程计算中间值

内存合并访问

全局内存访问应尽量合并,使同一 warp 的访问落在连续地址:

cpp
// 好:合并访问
float value = global_array[threadIdx.x];

// 坏:随机访问
float value = global_array[random_index[threadIdx.x]];

BVH 遍历内存优化

使用 Shared Memory 存储遍历栈:

cpp
__global__ void render_kernel(...) {
    // Shared Memory 存储 BVH 栈
    __shared__ int shared_stack[32][64];  // 32 threads, depth 64

    int* my_stack = shared_stack[threadIdx.x];
    // ... 遍历代码
}

场景数据布局

优化数据布局以提高缓存命中率:

cpp
// 结构体数组 (AoS) - 不推荐
struct Sphere {
    vec3 center;
    float radius;
    Material material;
};
Sphere spheres[N];

// 数组结构体 (SoA) - 推荐
struct SphereSoA {
    vec3 centers[N];
    float radii[N];
    Material materials[N];
};

内存使用分析

数据类型大小估算
球体数组GlobalN × 32 bytes
BVH 节点Global(2N-1) × 32 bytes
光线缓冲GlobalW×H × 32 bytes
输出图像GlobalW×H × 12 bytes
BVH 栈Shared32 × 64 × 4 bytes

参考资料

  • [CUDA Programming Guide] NVIDIA
  • [Aila & Karras 2010] "Understanding Ray Traversal Efficiency"

Technical Whitepaper · Built with VitePress