From 504c883b8c35f1757da264f4d7a7d8295b1610f7 Mon Sep 17 00:00:00 2001 From: Wenqing Lan Date: Mon, 6 Jul 2026 21:18:14 +0000 Subject: [PATCH 1/5] refine gpu stream perf --- .../micro_benchmarks/gpu_stream/gpu_stream.cu | 28 +- .../gpu_stream/gpu_stream_kernels.hpp | 417 ++++++++++++------ 2 files changed, 296 insertions(+), 149 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu index 64964a3df..3edc313c2 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu @@ -454,17 +454,19 @@ int GpuStream::RunStreamKernel(std::unique_ptr> &args, Kernel kerne return -1; } - // Validate data size - // Each thread processes one VecT element (128 bits / 16 bytes) for optimal memory bandwidth. - // Derived from VecT so any vector type change is caught at compile time. + // Each thread processes kUnroll VecT elements (128 bits / 16 bytes each) per loop iteration + // via a grid-stride loop. The grid is sized as a small multiple of the SM count to keep all + // SMs busy with long-lived blocks, while the loop + unroll provides memory-level parallelism. constexpr uint64_t kBytesPerThread = sizeof(VecT); static_assert(kBytesPerThread == 16, "Vector type must be 128-bit aligned for current PTX"); - uint64_t num_bytes_in_thread_block = num_threads_per_block * kBytesPerThread; - if (args->size % num_bytes_in_thread_block) { - std::cerr << "RunStreamKernel: Data size should be multiple of " << num_bytes_in_thread_block << std::endl; - return -1; - } - num_thread_blocks = args->size / num_bytes_in_thread_block; + + // Number of vector elements to process + uint64_t n = args->size / kBytesPerThread; + + // Use a fixed grid: numSMs * kGridMultiplier blocks. + // This keeps blocks long-lived (many loop iterations) and minimizes scheduling overhead. + constexpr int kGridMultiplier = 4; + num_thread_blocks = static_cast(args->gpu_device_prop.multiProcessorCount) * kGridMultiplier; args->sub.times_in_ms.resize(static_cast(Kernel::kCount)); @@ -488,20 +490,20 @@ int GpuStream::RunStreamKernel(std::unique_ptr> &args, Kernel kerne case Kernel::kCopy: CopyKernel<<sub.stream>>>( reinterpret_cast *>(args->sub.gpu_buf_ptrs[2].get()), - reinterpret_cast *>(args->sub.gpu_buf_ptrs[0].get())); + reinterpret_cast *>(args->sub.gpu_buf_ptrs[0].get()), n); args->sub.kernel_name = "COPY"; break; case Kernel::kScale: ScaleKernel<<sub.stream>>>( reinterpret_cast *>(args->sub.gpu_buf_ptrs[2].get()), - reinterpret_cast *>(args->sub.gpu_buf_ptrs[0].get()), static_cast(scalar)); + reinterpret_cast *>(args->sub.gpu_buf_ptrs[0].get()), static_cast(scalar), n); args->sub.kernel_name = "SCALE"; break; case Kernel::kAdd: AddKernel<<sub.stream>>>( reinterpret_cast *>(args->sub.gpu_buf_ptrs[2].get()), reinterpret_cast *>(args->sub.gpu_buf_ptrs[0].get()), - reinterpret_cast *>(args->sub.gpu_buf_ptrs[1].get())); + reinterpret_cast *>(args->sub.gpu_buf_ptrs[1].get()), n); size_factor = 3; args->sub.kernel_name = "ADD"; break; @@ -509,7 +511,7 @@ int GpuStream::RunStreamKernel(std::unique_ptr> &args, Kernel kerne TriadKernel<<sub.stream>>>( reinterpret_cast *>(args->sub.gpu_buf_ptrs[2].get()), reinterpret_cast *>(args->sub.gpu_buf_ptrs[0].get()), - reinterpret_cast *>(args->sub.gpu_buf_ptrs[1].get()), static_cast(scalar)); + reinterpret_cast *>(args->sub.gpu_buf_ptrs[1].get()), static_cast(scalar), n); size_factor = 3; args->sub.kernel_name = "TRIAD"; break; diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp index 8702b1421..348d33a87 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp @@ -9,6 +9,10 @@ #include "gpu_stream_utils.hpp" +#ifndef NON_HIP +#define NON_HIP (!defined(__HIP_PLATFORM_HCC__) && !defined(__HCC__) && !defined(__HIPCC__)) +#endif + /** * @brief Type trait mapping scalar types to their 128-bit aligned vector types. * @@ -17,178 +21,319 @@ * - float -> float4 (4 x 32-bit = 128-bit) */ template struct VectorType; -template <> struct VectorType { using type = double2; }; -template <> struct VectorType { using type = float4; }; +template <> struct VectorType { + using type = double2; +}; +template <> struct VectorType { + using type = float4; +}; template using VecT = typename VectorType::type; +// Number of vector elements each thread processes per unrolled loop iteration. +// This enables the compiler to pipeline multiple outstanding memory requests per thread, +// which is critical for saturating HBM bandwidth on modern GPUs. +constexpr int kUnroll = 4; + // Kernel declarations (visible to all compilers for function pointer usage) -template __global__ void CopyKernel(VecT *tgt, const VecT *src); -template __global__ void ScaleKernel(VecT *tgt, const VecT *src, const T scalar); -template __global__ void AddKernel(VecT *tgt, const VecT *src_a, const VecT *src_b); template -__global__ void TriadKernel(VecT *tgt, const VecT *src_a, const VecT *src_b, const T scalar); +__global__ void CopyKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src, uint64_t n); +template +__global__ void ScaleKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src, const T scalar, uint64_t n); +template +__global__ void AddKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src_a, + const VecT *__restrict__ src_b, uint64_t n); +template +__global__ void TriadKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src_a, + const VecT *__restrict__ src_b, const T scalar, uint64_t n); // Implementation section - only compiled by nvcc #ifdef __CUDACC__ -/** - * @brief Fetches a value from source memory and writes it to a register. - * - * @details This inline device function fetches a value from the specified source memory - * location and writes it to the provided register. The implementation references the following: - * 1) NCCL: - * https://github.com/NVIDIA/nccl/blob/7e515921295adaab72adf56ea71a0fafb0ecb5f3/src/collectives/device/common_kernel.h#L483 - * 2) RCCL: - * https://github.com/ROCmSoftwarePlatform/rccl/blob/5c8380ff5b5925cae4bce00b1879a5f930226e8d/src/collectives/device/common_kernel.h#L268 - * - * @tparam T The type of the value to fetch. - * @param[out] v The register to write the fetched value to. - * @param[in] p The source memory location to fetch the value from. - */ -template inline __device__ void Fetch(T &v, const T *p) { -#if defined(__HIP_PLATFORM_HCC__) || defined(__HCC__) || defined(__HIPCC__) - v = *p; +// Compiler memory barrier: prevents nvcc from reordering memory operations across this point. +// Ensures all loads above are issued before any stores below, forcing the register allocator +// to keep all loaded values live simultaneously (= multiple outstanding memory requests). +#define STREAM_BARRIER() asm volatile("" ::: "memory") + +// L2 cache-hinted load: uses createpolicy + ld.global.L2::cache_hint (PTX 7.8+, sm_80+) +// evict_last tells L2 to keep this data as long as possible, improving streaming BW by ~1.2%. +// Falls back to plain load on HIP/ROCm or if compiled for < sm_80. +inline __device__ void StreamLoadD2(double2 &v, const double2 *p) { +#if NON_HIP && (__CUDA_ARCH__ >= 800) + uint64_t policy; + asm("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(policy)); + asm("ld.global.L2::cache_hint.v2.f64 {%0,%1}, [%2], %3;" : "=d"(v.x), "=d"(v.y) : "l"(p), "l"(policy)); #else - if constexpr (std::is_same::value) { - asm volatile("ld.volatile.global.v2.f64 {%0,%1}, [%2];" : "=d"(v.x), "=d"(v.y) : "l"(p) : "memory"); - } else if constexpr (std::is_same::value) { - asm volatile("ld.volatile.global.v4.f32 {%0,%1,%2,%3}, [%4];" - : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) - : "l"(p) - : "memory"); - } + v = *p; #endif } -/** - * @brief Stores a value from register and writes it to target memory. - * - * @details This inline device function stores a value from the provided register - * and writes it to the specified target memory location. The implementation references the following: - * 1) NCCL: - * https://github.com/NVIDIA/nccl/blob/7e515921295adaab72adf56ea71a0fafb0ecb5f3/src/collectives/device/common_kernel.h#L486 - * 2) RCCL: - * https://github.com/ROCmSoftwarePlatform/rccl/blob/5c8380ff5b5925cae4bce00b1879a5f930226e8d/src/collectives/device/common_kernel.h#L276 - * - * @tparam T The type of the value to store. - * @param[out] p The target memory location to write the value to. - * @param[in] v The register containing the value to be stored. - */ -template inline __device__ void Store(T *p, const T &v) { -#if defined(__HIP_PLATFORM_HCC__) || defined(__HCC__) || defined(__HIPCC__) - *p = v; +inline __device__ void StreamLoadF4(float4 &v, const float4 *p) { +#if NON_HIP && (__CUDA_ARCH__ >= 800) + uint64_t policy; + asm("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(policy)); + asm("ld.global.L2::cache_hint.v4.f32 {%0,%1,%2,%3}, [%4], %5;" + : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) + : "l"(p), "l"(policy)); #else - if constexpr (std::is_same::value) { - asm volatile("st.volatile.global.v2.f64 [%0], {%1,%2};" ::"l"(p), "d"(v.x), "d"(v.y) : "memory"); - } else if constexpr (std::is_same::value) { - asm volatile("st.volatile.global.v4.f32 [%0], {%1,%2,%3,%4};" ::"l"(p), "f"(v.x), "f"(v.y), "f"(v.z), "f"(v.w) - : "memory"); - } + v = *p; #endif } +template inline __device__ void StreamLoad(VecT &v, const VecT *p) { + if constexpr (std::is_same::value) { + StreamLoadD2(v, p); + } else if constexpr (std::is_same::value) { + StreamLoadF4(v, p); + } +} + /** - * @brief Performs COPY, a simple copy operation from source to target. b = a - * - * @details This CUDA kernel performs a simple copy operation, copying data from the source array - * to the target array. This is used to measure transfer rates without any arithmetic operations. + * @brief Performs COPY using a grid-stride loop with manual 4x unrolling. b = a * - * @param[out] tgt The target array where data will be copied to (128-bit aligned). - * @param[in] src The source array from which data will be copied (128-bit aligned). + * @details Uses L2::evict_last cache hint on loads for ~1% better streaming BW. + * Uses a compiler barrier between loads and stores to prevent nvcc from serializing. */ -template __global__ void CopyKernel(VecT *tgt, const VecT *src) { - uint64_t index = blockIdx.x * blockDim.x + threadIdx.x; - VecT val; - Fetch(val, src + index); - Store(tgt + index, val); +template +__global__ __launch_bounds__(1024, 1) void CopyKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src, + uint64_t n) { + uint64_t tid = blockIdx.x * blockDim.x + threadIdx.x; + uint64_t stride = (uint64_t)gridDim.x * blockDim.x; + uint64_t stride2 = stride * 2; + uint64_t stride3 = stride * 3; + uint64_t chunk = stride * 4; + uint64_t bulk_end = (n / chunk) * chunk; + + for (uint64_t base = tid; base < bulk_end; base += chunk) { + VecT v0, v1, v2, v3; + StreamLoad(v0, src + base); + StreamLoad(v1, src + base + stride); + StreamLoad(v2, src + base + stride2); + StreamLoad(v3, src + base + stride3); + STREAM_BARRIER(); + tgt[base] = v0; + tgt[base + stride] = v1; + tgt[base + stride2] = v2; + tgt[base + stride3] = v3; + } + + for (uint64_t idx = bulk_end + tid; idx < n; idx += stride) { + tgt[idx] = src[idx]; + } } /** - * @brief Performs SCALE, a scaling operation on the source data. b = x * a - * - * @details This CUDA kernel performs a simple arithmetic operation by scaling the source data - * with a given scalar value and storing the result in the target array. - * - * @param[out] tgt The target array where the scaled data will be stored (128-bit aligned). - * @param[in] src The source array containing the data to be scaled (128-bit aligned). - * @param[in] scalar The scalar value used to scale the source data. + * @brief Performs SCALE with manual 4x unrolling. b = x * a */ -template __global__ void ScaleKernel(VecT *tgt, const VecT *src, const T scalar) { - uint64_t index = blockIdx.x * blockDim.x + threadIdx.x; - VecT val; - Fetch(val, src + index); - if constexpr (std::is_same::value) { - val.x *= scalar; - val.y *= scalar; - } else if constexpr (std::is_same::value) { - val.x *= scalar; - val.y *= scalar; - val.z *= scalar; - val.w *= scalar; +template +__global__ __launch_bounds__(1024, 1) void ScaleKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src, + const T scalar, uint64_t n) { + uint64_t tid = blockIdx.x * blockDim.x + threadIdx.x; + uint64_t stride = (uint64_t)gridDim.x * blockDim.x; + uint64_t stride2 = stride * 2; + uint64_t stride3 = stride * 3; + uint64_t chunk = stride * 4; + uint64_t bulk_end = (n / chunk) * chunk; + + for (uint64_t base = tid; base < bulk_end; base += chunk) { + VecT v0, v1, v2, v3; + StreamLoad(v0, src + base); + StreamLoad(v1, src + base + stride); + StreamLoad(v2, src + base + stride2); + StreamLoad(v3, src + base + stride3); + STREAM_BARRIER(); + if constexpr (std::is_same::value) { + v0.x *= scalar; + v0.y *= scalar; + v1.x *= scalar; + v1.y *= scalar; + v2.x *= scalar; + v2.y *= scalar; + v3.x *= scalar; + v3.y *= scalar; + } else if constexpr (std::is_same::value) { + v0.x *= scalar; + v0.y *= scalar; + v0.z *= scalar; + v0.w *= scalar; + v1.x *= scalar; + v1.y *= scalar; + v1.z *= scalar; + v1.w *= scalar; + v2.x *= scalar; + v2.y *= scalar; + v2.z *= scalar; + v2.w *= scalar; + v3.x *= scalar; + v3.y *= scalar; + v3.z *= scalar; + v3.w *= scalar; + } + tgt[base] = v0; + tgt[base + stride] = v1; + tgt[base + stride2] = v2; + tgt[base + stride3] = v3; + } + + for (uint64_t idx = bulk_end + tid; idx < n; idx += stride) { + VecT v = src[idx]; + if constexpr (std::is_same::value) { + v.x *= scalar; + v.y *= scalar; + } else if constexpr (std::is_same::value) { + v.x *= scalar; + v.y *= scalar; + v.z *= scalar; + v.w *= scalar; + } + tgt[idx] = v; } - Store(tgt + index, val); } /** - * @brief Performs ADD, an addition operation on two source arrays. c = a + b - * - * @details This CUDA kernel adds corresponding elements from two source arrays and stores the result - * in the target array. This operation is used to measure transfer rates with a simple arithmetic addition. - * - * @param[out] tgt The target array where the result of the addition will be stored (128-bit aligned). - * @param[in] src_a The first source array containing the first set of operands (128-bit aligned). - * @param[in] src_b The second source array containing the second set of operands (128-bit aligned). + * @brief Performs ADD with manual 4x unrolling. c = a + b */ -template __global__ void AddKernel(VecT *tgt, const VecT *src_a, const VecT *src_b) { - uint64_t index = blockIdx.x * blockDim.x + threadIdx.x; - VecT val_a; - VecT val_b; - Fetch(val_a, src_a + index); - Fetch(val_b, src_b + index); - if constexpr (std::is_same::value) { - val_a.x += val_b.x; - val_a.y += val_b.y; - } else if constexpr (std::is_same::value) { - val_a.x += val_b.x; - val_a.y += val_b.y; - val_a.z += val_b.z; - val_a.w += val_b.w; +template +__global__ __launch_bounds__(1024, 1) void AddKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src_a, + const VecT *__restrict__ src_b, uint64_t n) { + uint64_t tid = blockIdx.x * blockDim.x + threadIdx.x; + uint64_t stride = (uint64_t)gridDim.x * blockDim.x; + uint64_t stride2 = stride * 2; + uint64_t stride3 = stride * 3; + uint64_t chunk = stride * 4; + uint64_t bulk_end = (n / chunk) * chunk; + + for (uint64_t base = tid; base < bulk_end; base += chunk) { + VecT a0, a1, a2, a3, b0, b1, b2, b3; + StreamLoad(a0, src_a + base); + StreamLoad(a1, src_a + base + stride); + StreamLoad(a2, src_a + base + stride2); + StreamLoad(a3, src_a + base + stride3); + StreamLoad(b0, src_b + base); + StreamLoad(b1, src_b + base + stride); + StreamLoad(b2, src_b + base + stride2); + StreamLoad(b3, src_b + base + stride3); + STREAM_BARRIER(); + if constexpr (std::is_same::value) { + a0.x += b0.x; + a0.y += b0.y; + a1.x += b1.x; + a1.y += b1.y; + a2.x += b2.x; + a2.y += b2.y; + a3.x += b3.x; + a3.y += b3.y; + } else if constexpr (std::is_same::value) { + a0.x += b0.x; + a0.y += b0.y; + a0.z += b0.z; + a0.w += b0.w; + a1.x += b1.x; + a1.y += b1.y; + a1.z += b1.z; + a1.w += b1.w; + a2.x += b2.x; + a2.y += b2.y; + a2.z += b2.z; + a2.w += b2.w; + a3.x += b3.x; + a3.y += b3.y; + a3.z += b3.z; + a3.w += b3.w; + } + tgt[base] = a0; + tgt[base + stride] = a1; + tgt[base + stride2] = a2; + tgt[base + stride3] = a3; + } + + for (uint64_t idx = bulk_end + tid; idx < n; idx += stride) { + VecT a = src_a[idx]; + VecT b = src_b[idx]; + if constexpr (std::is_same::value) { + a.x += b.x; + a.y += b.y; + } else if constexpr (std::is_same::value) { + a.x += b.x; + a.y += b.y; + a.z += b.z; + a.w += b.w; + } + tgt[idx] = a; } - Store(tgt + index, val_a); } /** - * @brief Performs TRIAD, fused multiply/add operations on source arrays. c = b + x * a - * - * @details This CUDA kernel performs a fused multiply/add operation by multiplying elements from - * the first source array with a scalar value, adding the result to corresponding elements from - * the second source array, and storing the result in the target array. - * - * @param[out] tgt The target array where the result of the fused multiply/add operation will be stored (128-bit - * aligned). - * @param[in] src_a The first source array containing the first set of operands to be multiplied by the scalar - * (128-bit aligned). - * @param[in] src_b The second source array containing the second set of operands (128-bit aligned). - * @param[in] scalar The scalar value used in the multiply/add operation. + * @brief Performs TRIAD with manual 4x unrolling. c = b + x * a */ template -__global__ void TriadKernel(VecT *tgt, const VecT *src_a, const VecT *src_b, const T scalar) { - uint64_t index = blockIdx.x * blockDim.x + threadIdx.x; - VecT val_a; - VecT val_b; - Fetch(val_a, src_a + index); - Fetch(val_b, src_b + index); - if constexpr (std::is_same::value) { - val_b.x += (val_a.x * scalar); - val_b.y += (val_a.y * scalar); - } else if constexpr (std::is_same::value) { - val_b.x += (val_a.x * scalar); - val_b.y += (val_a.y * scalar); - val_b.z += (val_a.z * scalar); - val_b.w += (val_a.w * scalar); +__global__ __launch_bounds__(1024, 1) void TriadKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src_a, + const VecT *__restrict__ src_b, const T scalar, uint64_t n) { + uint64_t tid = blockIdx.x * blockDim.x + threadIdx.x; + uint64_t stride = (uint64_t)gridDim.x * blockDim.x; + uint64_t stride2 = stride * 2; + uint64_t stride3 = stride * 3; + uint64_t chunk = stride * 4; + uint64_t bulk_end = (n / chunk) * chunk; + + for (uint64_t base = tid; base < bulk_end; base += chunk) { + VecT a0, a1, a2, a3, b0, b1, b2, b3; + StreamLoad(a0, src_a + base); + StreamLoad(a1, src_a + base + stride); + StreamLoad(a2, src_a + base + stride2); + StreamLoad(a3, src_a + base + stride3); + StreamLoad(b0, src_b + base); + StreamLoad(b1, src_b + base + stride); + StreamLoad(b2, src_b + base + stride2); + StreamLoad(b3, src_b + base + stride3); + STREAM_BARRIER(); + if constexpr (std::is_same::value) { + b0.x += a0.x * scalar; + b0.y += a0.y * scalar; + b1.x += a1.x * scalar; + b1.y += a1.y * scalar; + b2.x += a2.x * scalar; + b2.y += a2.y * scalar; + b3.x += a3.x * scalar; + b3.y += a3.y * scalar; + } else if constexpr (std::is_same::value) { + b0.x += a0.x * scalar; + b0.y += a0.y * scalar; + b0.z += a0.z * scalar; + b0.w += a0.w * scalar; + b1.x += a1.x * scalar; + b1.y += a1.y * scalar; + b1.z += a1.z * scalar; + b1.w += a1.w * scalar; + b2.x += a2.x * scalar; + b2.y += a2.y * scalar; + b2.z += a2.z * scalar; + b2.w += a2.w * scalar; + b3.x += a3.x * scalar; + b3.y += a3.y * scalar; + b3.z += a3.z * scalar; + b3.w += a3.w * scalar; + } + tgt[base] = b0; + tgt[base + stride] = b1; + tgt[base + stride2] = b2; + tgt[base + stride3] = b3; + } + + for (uint64_t idx = bulk_end + tid; idx < n; idx += stride) { + VecT a = src_a[idx]; + VecT b = src_b[idx]; + if constexpr (std::is_same::value) { + b.x += a.x * scalar; + b.y += a.y * scalar; + } else if constexpr (std::is_same::value) { + b.x += a.x * scalar; + b.y += a.y * scalar; + b.z += a.z * scalar; + b.w += a.w * scalar; + } + tgt[idx] = b; } - Store(tgt + index, val_b); } #endif // __CUDACC__ \ No newline at end of file From 185314d26b76c683cf8269bb39eba958c02079ff Mon Sep 17 00:00:00 2001 From: Wenqing Lan Date: Thu, 29 Oct 2026 00:01:45 +0000 Subject: [PATCH 2/5] add autotune and preconfig to gpu stream --- MANIFEST.in | 1 + .../benchmarks/micro-benchmarks.md | 22 +- examples/benchmarks/gpu_stream.py | 8 +- .../benchmarks/micro_benchmarks/gpu_stream.py | 224 +++++---- .../micro_benchmarks/gpu_stream/gpu_stream.cu | 209 +++++---- .../gpu_stream/gpu_stream.hpp | 2 +- .../gpu_stream/gpu_stream_kernels.cu | 32 +- .../gpu_stream/gpu_stream_kernels.hpp | 426 ++++++------------ .../gpu_stream/gpu_stream_utils.cpp | 221 ++++----- .../gpu_stream/gpu_stream_utils.hpp | 25 +- .../micro_benchmarks/gpu_stream_profiles.json | 41 ++ .../micro_benchmarks/test_gpu_stream.py | 345 ++++++++------ 12 files changed, 748 insertions(+), 808 deletions(-) create mode 100644 superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json diff --git a/MANIFEST.in b/MANIFEST.in index 34d9d0272..4ebe62113 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,3 +1,4 @@ include LICENSE README.md recursive-include superbench *.py *.j2 *.yaml +include superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json global-exclude *.py[cod] __pycache__ diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index e8cda7eea..0ef42cc41 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -408,22 +408,20 @@ For measurements of peer-to-peer communication performance between AMD GPUs, GPU #### Introduction -Measure the memory bandwidth of GPU using the STREAM benchmark. The benchmark tests various memory operations including copy, scale, add, and triad for double and float datatypes. +Measures Copy, Scale, Add, and Triad bandwidth for float and double. Set `gpu_name: h100`, `gb300`, or `vr` to select [gpu_stream_profiles.json](../../../superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json), with one buffer size per GPU and block/unroll settings per workload. GPU names are not detected. -__Note__: When `--check_data` is enabled, each process allocates 6× `--size` bytes of host memory (data\_buf + check\_buf + 4 validation buffers, e.g. 24 GiB with the default 4 GiB `--size`). Under `default_local_mode` with 8 GPUs this totals ~192 GiB of host RAM. Recommend using a small `--size` such as `1048576` (1 MiB) when `--check_data` is enabled. +Omit `gpu_name` to autotune; unrecognized names and missing presets also use the fixed block/unroll sweep. `size` is bytes per array and overrides the preset buffer without disabling launch presets. If omitted, the GPU default is used (8 GiB without a profile). Both datatypes are selected unless `data_type` is specified. + +`check_data` checks output outside timing and needs 6x buffer size in host memory. Use small buffers for validation. #### Metrics -| Metric Name | Unit | Description | -|------------------------------------------------------------|------------------|-----------------------------------------------------------------------------------------------------------------------------------------| -| STREAM\_COPY\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_bw | bandwidth (GB/s) | The memory bandwidth of the GPU for the copy operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. | -| STREAM\_SCALE\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_bw | bandwidth (GB/s) | The memory bandwidth of the GPU for the scale operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. | -| STREAM\_ADD\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_bw | bandwidth (GB/s) | The memory bandwidth of the GPU for the add operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. | -| STREAM\_TRIAD\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_bw | bandwidth (GB/s) | The memory bandwidth of the GPU for the triad operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. | -| STREAM\_COPY\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_ratio | Efficiency (%) | The memory bandwidth efficiency of the GPU for the copy operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. | -| STREAM\_SCALE\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_ratio | Efficiency (%) | The memory bandwidth efficiency of the GPU for the scale operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. | -| STREAM\_ADD\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_ratio | Efficiency (%) | The memory bandwidth efficiency of the GPU for the add operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. | -| STREAM\_TRIAD\_(double\|float)\_buffer\_[0-9]+\_block\_[0-9]+\_ratio | Efficiency (%) | The memory bandwidth efficiency of the GPU for the triad operation with the selected data type (double for fp64, float for fp32), for the specified buffer size and block size. | +| Metric Name | Unit | Description | +|-------------|------|-------------| +| STREAM\_(COPY\|SCALE\|ADD\|TRIAD)\_(double\|float)\_bw | GB/s | Fresh preset bandwidth or the highest measured bandwidth from the fixed sweep. | +| STREAM\_(COPY\|SCALE\|ADD\|TRIAD)\_(double\|float)\_ratio | % | Efficiency from the same winning measurement; -1 if theoretical peak is unavailable. | + +For example: `gpu-stream:fp64/STREAM_ADD_double_bw`. Selected launch parameters stay in raw output. ### `ib-loopback` diff --git a/examples/benchmarks/gpu_stream.py b/examples/benchmarks/gpu_stream.py index 1aa67b15d..c7a4faba1 100644 --- a/examples/benchmarks/gpu_stream.py +++ b/examples/benchmarks/gpu_stream.py @@ -5,6 +5,8 @@ Commands to run: python3 examples/benchmarks/gpu_stream.py + +Omit gpu_name to autotune; add --gpu_name h100, gb300, or vr to use a preset. """ from superbench.benchmarks import BenchmarkRegistry, Platform @@ -12,12 +14,8 @@ if __name__ == '__main__': context = BenchmarkRegistry.create_benchmark_context( - 'gpu-stream', platform=Platform.CUDA, parameters='--num_warm_up 1 --num_loops 10 --data_type double' + 'gpu-stream', platform=Platform.CUDA, parameters='--num_warm_up 10 --num_loops 40 --data_type both' ) - # For ROCm environment, please specify the benchmark name and the platform as the following. - # context = BenchmarkRegistry.create_benchmark_context( - # 'gpu-stream', platform=Platform.ROCM, parameters='--num_warm_up 1 --num_loops 10' - # ) # To enable data checking, please add '--check_data'. benchmark = BenchmarkRegistry.launch_benchmark(context) diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream.py b/superbench/benchmarks/micro_benchmarks/gpu_stream.py index 142acb5a9..41ca78eae 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream.py +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream.py @@ -1,129 +1,161 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -"""Module of the GPU Stream Performance benchmark.""" +"""GPU STREAM bandwidth with chip presets and a fixed fallback sweep.""" +import json +import math import os +from pathlib import Path +import re +import shlex from superbench.common.utils import logger from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode from superbench.benchmarks.micro_benchmarks import MicroBenchmarkWithInvoke +_OPERATIONS = ['copy', 'scale', 'add', 'triad'] +_BLOCKS = [128, 256, 512, 1024] +_UNROLLS = [1, 2, 3, 4, 6, 8] +_DEFAULT_SIZE = 8 * 1024**3 +_TAG = re.compile(r'^STREAM_(COPY|SCALE|ADD|TRIAD)_(float|double)$') + + class GpuStreamBenchmark(MicroBenchmarkWithInvoke): - """The GPU stream performance benchmark class.""" - def __init__(self, name, parameters=''): - """Constructor. + """Report one bandwidth per operation and datatype.""" - Args: - name (str): benchmark name. - parameters (str): benchmark parameters. - """ + def __init__(self, name, parameters=''): + """Initialize the native benchmark.""" super().__init__(name, parameters) - self._bin_name = 'gpu_stream' + self._command_targets = [] def add_parser_arguments(self): - """Add the specified arguments.""" + """Retain the normal benchmark arguments; search dimensions are fixed.""" super().add_parser_arguments() - - self._parser.add_argument( - '--size', - type=int, - default=4096 * 1024**2, - required=False, - help='Size of data buffer in bytes.', - ) - - self._parser.add_argument( - '--num_warm_up', - type=int, - default=20, - required=False, - help='Number of warm up rounds', - ) - - self._parser.add_argument( - '--num_loops', - type=int, - default=100, - required=False, - help='Number of data buffer copies performed.', - ) - - self._parser.add_argument( - '--data_type', - type=str, - default='double', - choices=['float', 'double'], - required=False, - help='Data type of the buffer elements.', - ) - - self._parser.add_argument( - '--check_data', - action='store_true', - help='Enable data checking. Note: allocates 6x --size bytes of host memory per process ' - '(data_buf + check_buf + 4 validation buffers, e.g. 24 GiB with default 4 GiB --size). ' - 'Recommend using a small --size such as 1048576 (1 MiB) when this flag is enabled.', - ) + self._parser.add_argument('--gpu_name', type=str.lower, default=None, + help='GPU preset key (h100, gb300, vr). Omit to autotune.') + self._parser.add_argument('--size', type=int, default=None, + help='Bytes per array; overrides the chip default without changing launch presets.') + self._parser.add_argument('--num_warm_up', type=int, default=20) + self._parser.add_argument('--num_loops', type=int, default=100) + self._parser.add_argument('--data_type', choices=['float', 'double', 'both'], default='both') + self._parser.add_argument('--check_data', action='store_true', + help='Validate output. Requires 6x buffer size in host memory; use small sizes.') + + @staticmethod + def _check_config(tag, config): + """Check only the parameters needed to launch a preset.""" + match = _TAG.fullmatch(tag) + if match is None or not isinstance(config, dict): + raise ValueError('Invalid chip configuration key: {}'.format(tag)) + if set(config) != {'block_size', 'unroll'} or any(type(value) is not int for value in config.values()): + raise ValueError('{} needs integer block_size and unroll'.format(tag)) + if config['block_size'] not in _BLOCKS or config['unroll'] not in _UNROLLS: + raise ValueError('Unsupported block size/unroll for {}'.format(tag)) + + def _gpu_config(self): + """Select only the GPU name supplied by the user.""" + gpu_name = self._args.gpu_name + if gpu_name is None: + return {} + if not gpu_name.strip(): + raise ValueError('gpu_name must not be empty') + with Path(__file__).with_name('gpu_stream_profiles.json').open(encoding='utf-8') as stream: + profiles = json.load(stream) + if not isinstance(profiles, dict) or any(not isinstance(value, dict) for value in profiles.values()): + raise ValueError('Expected a chip-name to configuration mapping') + if gpu_name not in profiles: + logger.warning('No GPU STREAM preset for {}; using the fixed sweep.'.format(gpu_name)) + return {} + profile = profiles[gpu_name] + if set(profile) != {'buffer_size', 'kernels'} or not isinstance(profile['kernels'], dict): + raise ValueError('Each chip needs one buffer_size and a kernels mapping') + size = profile['buffer_size'] + if type(size) is not int or not 0 < size < 2**64 or size % 8: + raise ValueError('Chip buffer_size must be a positive multiple of 8 bytes') + configs = profile['kernels'] + for tag, config in configs.items(): + self._check_config(tag, config) + logger.info('GPU STREAM {}: {}.'.format(gpu_name, 'preset' if configs else 'fallback sweep')) + return profile + + def _command(self, dtype, operation, size, config=None): + """Use singleton native parameters for presets, or the native fixed sweep.""" + parts = [ + shlex.quote(self.__bin_path), '--size', str(size), '--data_type', dtype, '--operation', operation, + '--num_warm_up', str(self._args.num_warm_up), '--num_loops', str(self._args.num_loops), + ] + if config: + parts.extend(['--block_size', str(config['block_size']), '--unroll', str(config['unroll'])]) + if self._args.check_data: + parts.append('--check_data') + return ' '.join(parts) def _preprocess(self): - """Preprocess/preparation operations before the benchmarking. - - Return: - True if _preprocess() succeed. - """ + """Resolve size once, independently of chip launch presets.""" if not super()._preprocess(): return False - self.__bin_path = os.path.join(self._args.bin_dir, self._bin_name) - - args = '--size %d --num_warm_up %d --num_loops %d --data_type %s' % ( - self._args.size, self._args.num_warm_up, self._args.num_loops, self._args.data_type - ) - - if self._args.check_data: - args += ' --check_data' - - self._commands = ['%s %s' % (self.__bin_path, args)] - + self._commands, self._command_targets = [], [] + try: + if (self._args.num_warm_up < 0 or self._args.num_loops <= 0 or + self._args.num_warm_up + self._args.num_loops >= 2**64): + raise ValueError('Invalid warm-up/loop counts') + width = 4 if self._args.data_type == 'float' else 8 + if self._args.size is not None and (not 0 < self._args.size < 2**64 or self._args.size % width): + raise ValueError('Size must be a positive multiple of {} bytes'.format(width)) + profile = self._gpu_config() + configs = profile.get('kernels', {}) + size = self._args.size if self._args.size is not None else profile.get('buffer_size', _DEFAULT_SIZE) + dtypes = ['float', 'double'] if self._args.data_type == 'both' else [self._args.data_type] + commands, targets = [], [] + if not configs: + commands.append(self._command(self._args.data_type, 'all', size)) + targets.append({'STREAM_{}_{}'.format(op.upper(), dtype) for dtype in dtypes for op in _OPERATIONS}) + else: + for dtype in dtypes: + for operation in _OPERATIONS: + tag = 'STREAM_{}_{}'.format(operation.upper(), dtype) + config = configs.get(tag) + commands.append(self._command(dtype, operation, size, config)) + targets.append({tag}) + self._commands, self._command_targets = commands, targets + except (OSError, ValueError) as error: + self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) + logger.error('Invalid GPU STREAM configuration: {}.'.format(error)) + return False return True def _process_raw_result(self, cmd_idx, raw_output): - """Function to parse raw results and save the summarized results. - - self._result.add_raw_data() and self._result.add_result() need to be called to save the results. - - Args: - cmd_idx (int): the index of command corresponding with the raw_output. - raw_output (str): raw output string of the micro-benchmark. - - Return: - True if the raw output string is valid and result can be extracted. - """ + """Read only canonical native winners; launch details stay in raw output.""" self._result.add_raw_data('raw_output_' + str(cmd_idx), raw_output, self._args.log_raw_data) - try: - output_lines = [x.strip() for x in raw_output.strip().splitlines()] - count = 0 - for output_line in output_lines: - if output_line.startswith('STREAM_'): - count += 1 - tag, bw_str, ratio = output_line.split() - self._result.add_result(tag + '_bw', float(bw_str)) - self._result.add_result(tag + '_ratio', float(ratio)) - if count == 0: - raise BaseException('No valid results found.') - except BaseException as e: + if not 0 <= cmd_idx < len(self._commands): + raise ValueError('Unexpected command index') + results = {} + for line in raw_output.splitlines(): + if not line.startswith('STREAM_'): + continue + fields = line.split() + if len(fields) != 3 or _TAG.fullmatch(fields[0]) is None or fields[0] in results: + raise ValueError('Invalid or duplicate canonical result') + tag, bandwidth, ratio = fields + bandwidth, ratio = float(bandwidth), float(ratio) + if (not math.isfinite(bandwidth) or bandwidth <= 0 or not math.isfinite(ratio) or + (ratio < 0 and ratio != -1)): + raise ValueError('Invalid bandwidth/efficiency for {}'.format(tag)) + results[tag] = bandwidth, ratio + if set(results) != self._command_targets[cmd_idx]: + raise ValueError('Missing or unexpected workload results') + for tag, (bandwidth, ratio) in sorted(results.items()): + self._result.add_result(tag + '_bw', bandwidth) + self._result.add_result(tag + '_ratio', ratio) + except ValueError as error: self._result.set_return_code(ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) - logger.error( - 'The result format is invalid - round: {}, benchmark: {}, raw output: {}, message: {}.'.format( - self._curr_run_index, self._name, raw_output, str(e) - ) - ) + logger.error('Invalid GPU STREAM output: {}.'.format(error)) return False - return True diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu index 3edc313c2..b4734173d 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu @@ -8,11 +8,19 @@ #include "gpu_stream.hpp" #include +#include #include #include #include #include +namespace { +void PrintConfiguration(const char *record, const std::string &tag, uint64_t size, const LaunchConfig &config) { + std::cout << record << "\t" << tag << "\t" << size << "\t" << config.block_size << "\t" << config.unroll + << "\t" << (size / 16) / (config.block_size * config.unroll); +} +} // namespace + /** * @brief Destroys the CUDA events used for benchmarking. * @@ -303,6 +311,15 @@ template int GpuStream::PrepareBufAndStream(std::unique_ptrcheck_data) { + stream_kernels::InitializeData<<gpu_device_prop.multiProcessorCount * 32, 256, 0, args->sub.stream>>>( + args->sub.gpu_buf_ptrs[0].get(), args->sub.gpu_buf_ptrs[1].get(), args->size / sizeof(T)); + cuda_err = cudaGetLastError(); + if (cuda_err != cudaSuccess) { + std::cerr << "PrepareBufAndStream::InitializeData error: " << cudaGetErrorString(cuda_err) << std::endl; + return -1; + } + } return 0; } @@ -438,41 +455,33 @@ template int GpuStream::DestroyBufAndStream(std::unique_ptr -int GpuStream::RunStreamKernel(std::unique_ptr> &args, Kernel kernel, int num_threads_per_block) { +int GpuStream::RunStreamKernel(std::unique_ptr> &args, Kernel kernel, const LaunchConfig &config, + float *elapsed_ms) { cudaError_t cuda_err = cudaSuccess; - uint64_t num_thread_blocks; - int size_factor = 2; - if (num_threads_per_block == 0) { - std::cerr << "RunStreamKernel::num_threads_per_block must be > 0" << std::endl; - return -1; - } - - // Each thread processes kUnroll VecT elements (128 bits / 16 bytes each) per loop iteration - // via a grid-stride loop. The grid is sized as a small multiple of the SM count to keep all - // SMs busy with long-lived blocks, while the loop + unroll provides memory-level parallelism. - constexpr uint64_t kBytesPerThread = sizeof(VecT); - static_assert(kBytesPerThread == 16, "Vector type must be 128-bit aligned for current PTX"); - - // Number of vector elements to process - uint64_t n = args->size / kBytesPerThread; - - // Use a fixed grid: numSMs * kGridMultiplier blocks. - // This keeps blocks long-lived (many loop iterations) and minimizes scheduling overhead. - constexpr int kGridMultiplier = 4; - num_thread_blocks = static_cast(args->gpu_device_prop.multiProcessorCount) * kGridMultiplier; - - args->sub.times_in_ms.resize(static_cast(Kernel::kCount)); + const uint64_t count = args->size / sizeof(T); + T *output = args->sub.gpu_buf_ptrs[2].get(); + const T *first = args->sub.gpu_buf_ptrs[0].get(); + const T *second = args->sub.gpu_buf_ptrs[1].get(); + const int max_grid_x = args->gpu_device_prop.maxGridSize[0]; if (SetGpu(args->gpu_id)) { return -1; } + if (args->check_data) { + cuda_err = cudaMemsetAsync(output, 0xff, args->size, args->sub.stream); + if (cuda_err != cudaSuccess) { + std::cerr << "RunStreamKernel::cudaMemsetAsync error: " << cudaGetErrorString(cuda_err) << std::endl; + return -1; + } + } // Launch jobs and collect running time for (uint64_t i = 0; i < args->num_loops + args->num_warm_up; i++) { @@ -488,36 +497,33 @@ int GpuStream::RunStreamKernel(std::unique_ptr> &args, Kernel kerne switch (kernel) { case Kernel::kCopy: - CopyKernel<<sub.stream>>>( - reinterpret_cast *>(args->sub.gpu_buf_ptrs[2].get()), - reinterpret_cast *>(args->sub.gpu_buf_ptrs[0].get()), n); + cuda_err = stream_kernels::Launch( + output, first, second, count, config, args->sub.stream, max_grid_x); args->sub.kernel_name = "COPY"; break; case Kernel::kScale: - ScaleKernel<<sub.stream>>>( - reinterpret_cast *>(args->sub.gpu_buf_ptrs[2].get()), - reinterpret_cast *>(args->sub.gpu_buf_ptrs[0].get()), static_cast(scalar), n); + cuda_err = stream_kernels::Launch( + output, first, second, count, config, args->sub.stream, max_grid_x); args->sub.kernel_name = "SCALE"; break; case Kernel::kAdd: - AddKernel<<sub.stream>>>( - reinterpret_cast *>(args->sub.gpu_buf_ptrs[2].get()), - reinterpret_cast *>(args->sub.gpu_buf_ptrs[0].get()), - reinterpret_cast *>(args->sub.gpu_buf_ptrs[1].get()), n); - size_factor = 3; + cuda_err = stream_kernels::Launch( + output, first, second, count, config, args->sub.stream, max_grid_x); args->sub.kernel_name = "ADD"; break; case Kernel::kTriad: - TriadKernel<<sub.stream>>>( - reinterpret_cast *>(args->sub.gpu_buf_ptrs[2].get()), - reinterpret_cast *>(args->sub.gpu_buf_ptrs[0].get()), - reinterpret_cast *>(args->sub.gpu_buf_ptrs[1].get()), static_cast(scalar), n); - size_factor = 3; + cuda_err = stream_kernels::Launch( + output, first, second, count, config, args->sub.stream, max_grid_x); args->sub.kernel_name = "TRIAD"; break; default: std::cerr << "RunStreamKernel::Invalid kernel: " << std::endl; - break; + return -1; + } + if (cuda_err != cudaSuccess) { + std::cerr << "RunStreamKernel::launch " << args->sub.kernel_name + << " error: " << cudaGetErrorString(cuda_err) << std::endl; + return -1; } // Record end event at the end of iterations @@ -545,7 +551,11 @@ int GpuStream::RunStreamKernel(std::unique_ptr> &args, Kernel kerne return -1; } - args->sub.times_in_ms[static_cast(kernel)].push_back(time_in_ms / size_factor); + if (!std::isfinite(time_in_ms) || time_in_ms <= 0) { + std::cerr << "RunStreamKernel::Invalid CUDA event duration: " << time_in_ms << std::endl; + return -1; + } + *elapsed_ms = time_in_ms; return 0; } @@ -619,47 +629,73 @@ int GpuStream::RunStream(std::unique_ptr> &args, const std::string return -1; } - // benchmark over the kThreadsPerBlock array - for (const int num_threads_in_block : kThreadsPerBlock) { - // run the stream benchmark over the stream kernels - for (int i = 0; i < static_cast(Kernel::kCount); ++i) { - Kernel kernel = static_cast(i); - ret = RunStreamKernel(args, kernel, num_threads_in_block); - if (ret != 0) { - Destroy(args); - return ret; + struct BestResult { + double bandwidth = 0; + LaunchConfig config; + }; + std::array(Kernel::kCount)> best{}; + for (const Kernel kernel : opts_.operations) { + const auto index = static_cast(kernel); + const std::string tag = "STREAM_" + KernelToString(static_cast(kernel)) + "_" + data_type; + for (const int block : kThreadsPerBlock) { + if (opts_.block_size != 0 && opts_.block_size != block) { + continue; + } + if (block > args->gpu_device_prop.maxThreadsPerBlock) { + std::cerr << "Skipping unsupported block size " << block << " for " << tag << std::endl; + continue; } - if (args->check_data) { - ret = CheckBuf(args, i); + for (const int unroll : kUnrollFactors) { + if (opts_.unroll != 0 && opts_.unroll != unroll) { + continue; + } + const uint64_t tiles = (args->size / 16) / (block * unroll); + if (tiles > static_cast(args->gpu_device_prop.maxGridSize[0])) { + std::cerr << "Skipping grid exceeding the device limit for " << tag << std::endl; + continue; + } + const LaunchConfig config{block, unroll}; + float elapsed_ms = 0; + ret = RunStreamKernel(args, kernel, config, &elapsed_ms); + if (ret == 0 && args->check_data) { + ret = CheckBuf(args, static_cast(kernel)); + } if (ret != 0) { Destroy(args); return ret; } + const double bandwidth = static_cast(args->size) * args->num_loops * + kBufferBwMultipliers[index] / elapsed_ms / 1e6; + if (!std::isfinite(bandwidth) || bandwidth <= 0) { + std::cerr << "Invalid bandwidth for " << tag << std::endl; + Destroy(args); + return -1; + } + if (bandwidth > best[index].bandwidth) { + best[index] = {bandwidth, config}; + } } } - } - - // output formatted results to stdout - // Tags are of format: - // STREAM__datatype_buffer__block_ - for (size_t i = 0; i < args->sub.times_in_ms.size(); i++) { - std::string tag = "STREAM_" + KernelToString(i) + "_" + data_type + "_buffer_" + std::to_string(args->size); - for (size_t j = 0; j < args->sub.times_in_ms[i].size(); j++) { - // Calculate and display bandwidth - double bw = static_cast(args->size) * args->num_loops / args->sub.times_in_ms[i][j] / 1e6; - std::cout << tag << "_block_" << kThreadsPerBlock[j] << "\t" << bw << "\t"; - - if (peak_bw < 0) { // cannot get peak_bw -> prints -1 for efficiency - std::cout << "-1" << std::endl; - } else { - std::cout << std::fixed << std::setprecision(2) << bw / peak_bw * 100 << std::endl; - } + if (best[index].bandwidth == 0) { + std::cerr << "No supported launch configuration for " << tag << std::endl; + Destroy(args); + return -1; } } - // cleanup buffer and streams for the curr arg - Destroy(args); - return ret; + const uint64_t size = args->size; + ret = Destroy(args); + if (ret != 0) { + return ret; + } + for (const Kernel kernel : opts_.operations) { + const auto &winner = best[static_cast(kernel)]; + const std::string tag = "STREAM_" + KernelToString(static_cast(kernel)) + "_" + data_type; + PrintConfiguration("GPU_STREAM_CONFIG", tag, size, winner.config); + std::cout << "\n" << tag << "\t" << std::defaultfloat << std::setprecision(9) << winner.bandwidth << "\t" + << (peak_bw > 0 ? winner.bandwidth / peak_bw * 100 : -1) << std::endl; + } + return 0; } /** @@ -713,19 +749,10 @@ int GpuStream::Run() { std::cerr << "Run::No GPU available" << std::endl; return -1; } - - // Run on CUDA device 0 (the visible GPU assigned by CUDA_VISIBLE_DEVICES). - if (opts_.data_type == "float") { - ret = CreateBenchArgs(); - } else if (opts_.data_type == "double") { - ret = CreateBenchArgs(); - } else { + if (opts_.data_type != "float" && opts_.data_type != "double" && opts_.data_type != "both") { std::cerr << "Run::Invalid data_type: " << opts_.data_type << std::endl; return -1; } - if (ret != 0) { - return ret; - } // Pin the thread to the GPU's NUMA node for optimal host↔device bandwidth. // Query GPU 0's preferred CPU NUMA node via NVML; fall back to the process's @@ -772,8 +799,14 @@ int GpuStream::Run() { return -1; } - // Run the benchmark for the configured data - std::visit( + const std::vector data_types = + opts_.data_type == "both" ? std::vector{"float", "double"} : std::vector{opts_.data_type}; + for (const auto &data_type : data_types) { + ret = data_type == "float" ? CreateBenchArgs() : CreateBenchArgs(); + if (ret != 0) { + return ret; + } + std::visit( [&](auto &curr_args) { // Get memory clock rate once for both bandwidth computation and display float memory_clock_mhz = GetMemoryClockRate(curr_args->gpu_id, curr_args->gpu_device_prop); @@ -804,7 +837,11 @@ int GpuStream::Run() { std::cerr << "Run::RunStream error: " << ret << std::endl; } }, - bench_args_); + bench_args_); + if (ret != 0) { + return ret; + } + } return ret; } \ No newline at end of file diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.hpp b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.hpp index 65502a243..34138092f 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.hpp +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.hpp @@ -51,7 +51,7 @@ class GpuStream { template int Destroy(std::unique_ptr> &); // Benchmark functions - template int RunStreamKernel(std::unique_ptr> &, Kernel, int); + template int RunStreamKernel(std::unique_ptr> &, Kernel, const LaunchConfig &, float *); float GetActualMemoryClockRate(int gpu_id); template int RunStream(std::unique_ptr> &, const std::string &data_type, float peak_bw); diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.cu b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.cu index e40237b83..68e329b23 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.cu +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.cu @@ -1,33 +1,5 @@ // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. -/** - * @file gpu_stream_kernels.cu - * @brief CUDA kernel compilation unit for GPU stream benchmark. - * - * All template kernel implementations (CopyKernel, ScaleKernel, AddKernel, TriadKernel) - * are defined in gpu_stream_kernels.hpp rather than here. This is required because: - * - * 1. **C++ Template Instantiation Model**: Templates are not compiled until they are - * instantiated with concrete types. The compiler needs to see the full template - * definition (not just declaration) at the point of instantiation. - * - * 2. **Separate Compilation Units**: When gpu_stream.cu calls `CopyKernel<<<...>>>`, - * nvcc needs the full kernel implementation visible in that translation unit. - * If implementations were only in this .cu file, gpu_stream.cu would only see - * declarations, causing "undefined reference" linker errors. - * - * 3. **CUDA-Specific Consideration**: Unlike regular C++ where explicit template - * instantiation in a .cpp file can work, CUDA kernel launches require the kernel - * code to be visible to nvcc when compiling the caller. This is because nvcc - * generates device code at compile time, not link time. - * - * 4. **Header Guards for Mixed Compilation**: The header uses `#ifdef __CUDACC__` to - * protect CUDA-specific code (blockIdx, threadIdx, __global__, etc.) from g++ - * when the header is indirectly included by .cpp files (e.g., via gpu_stream.hpp). - * - * This file remains as the compilation unit that ensures the header is processed - * by nvcc, and can host any future non-template helper functions if needed. - */ - -#include "gpu_stream_kernels.hpp" \ No newline at end of file +// Template kernels and launch helpers must be visible to the launching translation unit. +#include "gpu_stream_kernels.hpp" diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp index 348d33a87..4138b21cd 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp @@ -5,21 +5,12 @@ #include #include +#include +#include #include #include "gpu_stream_utils.hpp" -#ifndef NON_HIP -#define NON_HIP (!defined(__HIP_PLATFORM_HCC__) && !defined(__HCC__) && !defined(__HIPCC__)) -#endif - -/** - * @brief Type trait mapping scalar types to their 128-bit aligned vector types. - * - * @details For optimal memory bandwidth, we use 128-bit (16 byte) vector loads/stores: - * - double -> double2 (2 x 64-bit = 128-bit) - * - float -> float4 (4 x 32-bit = 128-bit) - */ template struct VectorType; template <> struct VectorType { using type = double2; @@ -27,313 +18,162 @@ template <> struct VectorType { template <> struct VectorType { using type = float4; }; - template using VecT = typename VectorType::type; -// Number of vector elements each thread processes per unrolled loop iteration. -// This enables the compiler to pipeline multiple outstanding memory requests per thread, -// which is critical for saturating HBM bandwidth on modern GPUs. -constexpr int kUnroll = 4; - -// Kernel declarations (visible to all compilers for function pointer usage) -template -__global__ void CopyKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src, uint64_t n); -template -__global__ void ScaleKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src, const T scalar, uint64_t n); -template -__global__ void AddKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src_a, - const VecT *__restrict__ src_b, uint64_t n); -template -__global__ void TriadKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src_a, - const VecT *__restrict__ src_b, const T scalar, uint64_t n); - -// Implementation section - only compiled by nvcc #ifdef __CUDACC__ - -// Compiler memory barrier: prevents nvcc from reordering memory operations across this point. -// Ensures all loads above are issued before any stores below, forcing the register allocator -// to keep all loaded values live simultaneously (= multiple outstanding memory requests). -#define STREAM_BARRIER() asm volatile("" ::: "memory") - -// L2 cache-hinted load: uses createpolicy + ld.global.L2::cache_hint (PTX 7.8+, sm_80+) -// evict_last tells L2 to keep this data as long as possible, improving streaming BW by ~1.2%. -// Falls back to plain load on HIP/ROCm or if compiled for < sm_80. -inline __device__ void StreamLoadD2(double2 &v, const double2 *p) { -#if NON_HIP && (__CUDA_ARCH__ >= 800) - uint64_t policy; - asm("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(policy)); - asm("ld.global.L2::cache_hint.v2.f64 {%0,%1}, [%2], %3;" : "=d"(v.x), "=d"(v.y) : "l"(p), "l"(policy)); -#else - v = *p; -#endif -} - -inline __device__ void StreamLoadF4(float4 &v, const float4 *p) { -#if NON_HIP && (__CUDA_ARCH__ >= 800) - uint64_t policy; - asm("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(policy)); - asm("ld.global.L2::cache_hint.v4.f32 {%0,%1,%2,%3}, [%4], %5;" - : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) - : "l"(p), "l"(policy)); -#else - v = *p; -#endif -} - -template inline __device__ void StreamLoad(VecT &v, const VecT *p) { - if constexpr (std::is_same::value) { - StreamLoadD2(v, p); - } else if constexpr (std::is_same::value) { - StreamLoadF4(v, p); +namespace stream_kernels { +using stream_config::Kernel; +using stream_config::LaunchConfig; + +template __device__ __forceinline__ T Transform(T a, T b) { + if constexpr (OP == Kernel::kCopy) { + return a; + } else if constexpr (OP == Kernel::kScale) { + return static_cast(stream_config::scalar) * a; + } else if constexpr (OP == Kernel::kAdd) { + return a + b; + } else { + static_assert(OP == Kernel::kTriad, "Unsupported STREAM operation"); + return b + static_cast(stream_config::scalar) * a; } } -/** - * @brief Performs COPY using a grid-stride loop with manual 4x unrolling. b = a - * - * @details Uses L2::evict_last cache hint on loads for ~1% better streaming BW. - * Uses a compiler barrier between loads and stores to prevent nvcc from serializing. - */ -template -__global__ __launch_bounds__(1024, 1) void CopyKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src, - uint64_t n) { - uint64_t tid = blockIdx.x * blockDim.x + threadIdx.x; - uint64_t stride = (uint64_t)gridDim.x * blockDim.x; - uint64_t stride2 = stride * 2; - uint64_t stride3 = stride * 3; - uint64_t chunk = stride * 4; - uint64_t bulk_end = (n / chunk) * chunk; - - for (uint64_t base = tid; base < bulk_end; base += chunk) { - VecT v0, v1, v2, v3; - StreamLoad(v0, src + base); - StreamLoad(v1, src + base + stride); - StreamLoad(v2, src + base + stride2); - StreamLoad(v3, src + base + stride3); - STREAM_BARRIER(); - tgt[base] = v0; - tgt[base + stride] = v1; - tgt[base + stride2] = v2; - tgt[base + stride3] = v3; - } - - for (uint64_t idx = bulk_end + tid; idx < n; idx += stride) { - tgt[idx] = src[idx]; +template __device__ __forceinline__ VecT TransformPacket(VecT a, VecT b) { + VecT result; + result.x = Transform(a.x, b.x); + result.y = Transform(a.y, b.y); + if constexpr (std::is_same::value) { + result.z = Transform(a.z, b.z); + result.w = Transform(a.w, b.w); } + return result; } -/** - * @brief Performs SCALE with manual 4x unrolling. b = x * a - */ -template -__global__ __launch_bounds__(1024, 1) void ScaleKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src, - const T scalar, uint64_t n) { - uint64_t tid = blockIdx.x * blockDim.x + threadIdx.x; - uint64_t stride = (uint64_t)gridDim.x * blockDim.x; - uint64_t stride2 = stride * 2; - uint64_t stride3 = stride * 3; - uint64_t chunk = stride * 4; - uint64_t bulk_end = (n / chunk) * chunk; - - for (uint64_t base = tid; base < bulk_end; base += chunk) { - VecT v0, v1, v2, v3; - StreamLoad(v0, src + base); - StreamLoad(v1, src + base + stride); - StreamLoad(v2, src + base + stride2); - StreamLoad(v3, src + base + stride3); - STREAM_BARRIER(); - if constexpr (std::is_same::value) { - v0.x *= scalar; - v0.y *= scalar; - v1.x *= scalar; - v1.y *= scalar; - v2.x *= scalar; - v2.y *= scalar; - v3.x *= scalar; - v3.y *= scalar; - } else if constexpr (std::is_same::value) { - v0.x *= scalar; - v0.y *= scalar; - v0.z *= scalar; - v0.w *= scalar; - v1.x *= scalar; - v1.y *= scalar; - v1.z *= scalar; - v1.w *= scalar; - v2.x *= scalar; - v2.y *= scalar; - v2.z *= scalar; - v2.w *= scalar; - v3.x *= scalar; - v3.y *= scalar; - v3.z *= scalar; - v3.w *= scalar; +// Bounds checks and scalar remainders stay out of the complete-tile kernel. +template +__global__ __launch_bounds__(BLOCK) void BulkKernel(VecT *__restrict__ output, const VecT *__restrict__ a, + const VecT *__restrict__ b) { + const Index base = static_cast(blockIdx.x) * (BLOCK * UNROLL) + threadIdx.x; + VecT first[UNROLL]; + VecT second[UNROLL]; +#pragma unroll + for (int u = 0; u < UNROLL; ++u) { + first[u] = a[base + u * BLOCK]; + if constexpr (OP == Kernel::kAdd || OP == Kernel::kTriad) { + second[u] = b[base + u * BLOCK]; + } + } +#pragma unroll + for (int u = 0; u < UNROLL; ++u) { + if constexpr (OP == Kernel::kCopy) { + output[base + u * BLOCK] = first[u]; + } else if constexpr (OP == Kernel::kScale) { + output[base + u * BLOCK] = TransformPacket(first[u], VecT{}); + } else { + output[base + u * BLOCK] = TransformPacket(first[u], second[u]); } - tgt[base] = v0; - tgt[base + stride] = v1; - tgt[base + stride2] = v2; - tgt[base + stride3] = v3; } +} - for (uint64_t idx = bulk_end + tid; idx < n; idx += stride) { - VecT v = src[idx]; - if constexpr (std::is_same::value) { - v.x *= scalar; - v.y *= scalar; - } else if constexpr (std::is_same::value) { - v.x *= scalar; - v.y *= scalar; - v.z *= scalar; - v.w *= scalar; +template +__global__ void TailKernel(T *__restrict__ output, const T *__restrict__ a, const T *__restrict__ b, + uint64_t begin, uint64_t count) { + const uint64_t i = begin + static_cast(blockIdx.x) * blockDim.x + threadIdx.x; + if (i < count) { + T right = 0; + if constexpr (OP == Kernel::kAdd || OP == Kernel::kTriad) { + right = b[i]; } - tgt[idx] = v; + output[i] = Transform(a[i], right); } } -/** - * @brief Performs ADD with manual 4x unrolling. c = a + b - */ template -__global__ __launch_bounds__(1024, 1) void AddKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src_a, - const VecT *__restrict__ src_b, uint64_t n) { - uint64_t tid = blockIdx.x * blockDim.x + threadIdx.x; - uint64_t stride = (uint64_t)gridDim.x * blockDim.x; - uint64_t stride2 = stride * 2; - uint64_t stride3 = stride * 3; - uint64_t chunk = stride * 4; - uint64_t bulk_end = (n / chunk) * chunk; - - for (uint64_t base = tid; base < bulk_end; base += chunk) { - VecT a0, a1, a2, a3, b0, b1, b2, b3; - StreamLoad(a0, src_a + base); - StreamLoad(a1, src_a + base + stride); - StreamLoad(a2, src_a + base + stride2); - StreamLoad(a3, src_a + base + stride3); - StreamLoad(b0, src_b + base); - StreamLoad(b1, src_b + base + stride); - StreamLoad(b2, src_b + base + stride2); - StreamLoad(b3, src_b + base + stride3); - STREAM_BARRIER(); - if constexpr (std::is_same::value) { - a0.x += b0.x; - a0.y += b0.y; - a1.x += b1.x; - a1.y += b1.y; - a2.x += b2.x; - a2.y += b2.y; - a3.x += b3.x; - a3.y += b3.y; - } else if constexpr (std::is_same::value) { - a0.x += b0.x; - a0.y += b0.y; - a0.z += b0.z; - a0.w += b0.w; - a1.x += b1.x; - a1.y += b1.y; - a1.z += b1.z; - a1.w += b1.w; - a2.x += b2.x; - a2.y += b2.y; - a2.z += b2.z; - a2.w += b2.w; - a3.x += b3.x; - a3.y += b3.y; - a3.z += b3.z; - a3.w += b3.w; - } - tgt[base] = a0; - tgt[base + stride] = a1; - tgt[base + stride2] = a2; - tgt[base + stride3] = a3; +__global__ void InitializeData(T *a, T *b, uint64_t count) { + for (uint64_t i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; i < count; + i += static_cast(gridDim.x) * blockDim.x) { + a[i] = static_cast(i % stream_config::kUInt8Mod); + b[i] = a[i]; } +} - for (uint64_t idx = bulk_end + tid; idx < n; idx += stride) { - VecT a = src_a[idx]; - VecT b = src_b[idx]; - if constexpr (std::is_same::value) { - a.x += b.x; - a.y += b.y; - } else if constexpr (std::is_same::value) { - a.x += b.x; - a.y += b.y; - a.z += b.z; - a.w += b.w; +template +cudaError_t LaunchIndexed(T *output, const T *a, const T *b, uint64_t count, cudaStream_t stream, int max_grid_x) { + static_assert(sizeof(VecT) == 16 && alignof(VecT) == 16, "STREAM packets must be 128-bit aligned"); + static_assert(std::is_unsigned::value, "STREAM indices must be unsigned"); + static_assert(UNROLL > 0 && BLOCK > 0, "STREAM tiles must be nonempty"); + constexpr uint64_t lanes = sizeof(VecT) / sizeof(T); + constexpr uint64_t tile_elements = BLOCK * UNROLL * lanes; + const uint64_t blocks = count / tile_elements; + const uint64_t tail_begin = blocks * tile_elements; + if (count == 0 || count / lanes > std::numeric_limits::max()) { + return cudaErrorInvalidValue; + } + const uint64_t tail_blocks = (count - tail_begin + 255) / 256; + if (max_grid_x <= 0 || blocks > static_cast(max_grid_x) || + tail_blocks > static_cast(max_grid_x)) { + return cudaErrorInvalidConfiguration; + } + if (blocks != 0) { + BulkKernel<<(blocks), BLOCK, 0, stream>>>( + reinterpret_cast *>(output), reinterpret_cast *>(a), + reinterpret_cast *>(b)); + const cudaError_t error = cudaGetLastError(); + if (error != cudaSuccess) { + return error; } - tgt[idx] = a; } + if (tail_begin < count) { + TailKernel<<(tail_blocks), 256, 0, stream>>>(output, a, b, tail_begin, count); + return cudaGetLastError(); + } + return cudaSuccess; } -/** - * @brief Performs TRIAD with manual 4x unrolling. c = b + x * a - */ -template -__global__ __launch_bounds__(1024, 1) void TriadKernel(VecT *__restrict__ tgt, const VecT *__restrict__ src_a, - const VecT *__restrict__ src_b, const T scalar, uint64_t n) { - uint64_t tid = blockIdx.x * blockDim.x + threadIdx.x; - uint64_t stride = (uint64_t)gridDim.x * blockDim.x; - uint64_t stride2 = stride * 2; - uint64_t stride3 = stride * 3; - uint64_t chunk = stride * 4; - uint64_t bulk_end = (n / chunk) * chunk; - - for (uint64_t base = tid; base < bulk_end; base += chunk) { - VecT a0, a1, a2, a3, b0, b1, b2, b3; - StreamLoad(a0, src_a + base); - StreamLoad(a1, src_a + base + stride); - StreamLoad(a2, src_a + base + stride2); - StreamLoad(a3, src_a + base + stride3); - StreamLoad(b0, src_b + base); - StreamLoad(b1, src_b + base + stride); - StreamLoad(b2, src_b + base + stride2); - StreamLoad(b3, src_b + base + stride3); - STREAM_BARRIER(); - if constexpr (std::is_same::value) { - b0.x += a0.x * scalar; - b0.y += a0.y * scalar; - b1.x += a1.x * scalar; - b1.y += a1.y * scalar; - b2.x += a2.x * scalar; - b2.y += a2.y * scalar; - b3.x += a3.x * scalar; - b3.y += a3.y * scalar; - } else if constexpr (std::is_same::value) { - b0.x += a0.x * scalar; - b0.y += a0.y * scalar; - b0.z += a0.z * scalar; - b0.w += a0.w * scalar; - b1.x += a1.x * scalar; - b1.y += a1.y * scalar; - b1.z += a1.z * scalar; - b1.w += a1.w * scalar; - b2.x += a2.x * scalar; - b2.y += a2.y * scalar; - b2.z += a2.z * scalar; - b2.w += a2.w * scalar; - b3.x += a3.x * scalar; - b3.y += a3.y * scalar; - b3.z += a3.z * scalar; - b3.w += a3.w * scalar; - } - tgt[base] = b0; - tgt[base + stride] = b1; - tgt[base + stride2] = b2; - tgt[base + stride3] = b3; +template +cudaError_t LaunchUnroll(T *output, const T *a, const T *b, uint64_t count, cudaStream_t stream, int max_grid_x) { + if (count / (sizeof(VecT) / sizeof(T)) <= std::numeric_limits::max()) { + return LaunchIndexed(output, a, b, count, stream, max_grid_x); } + return LaunchIndexed(output, a, b, count, stream, max_grid_x); +} - for (uint64_t idx = bulk_end + tid; idx < n; idx += stride) { - VecT a = src_a[idx]; - VecT b = src_b[idx]; - if constexpr (std::is_same::value) { - b.x += a.x * scalar; - b.y += a.y * scalar; - } else if constexpr (std::is_same::value) { - b.x += a.x * scalar; - b.y += a.y * scalar; - b.z += a.z * scalar; - b.w += a.w * scalar; - } - tgt[idx] = b; +template +cudaError_t LaunchBlock(T *output, const T *a, const T *b, uint64_t count, cudaStream_t stream, int max_grid_x, + const LaunchConfig &config) { + switch (config.unroll) { + case 1: + return LaunchUnroll(output, a, b, count, stream, max_grid_x); + case 2: + return LaunchUnroll(output, a, b, count, stream, max_grid_x); + case 3: + return LaunchUnroll(output, a, b, count, stream, max_grid_x); + case 4: + return LaunchUnroll(output, a, b, count, stream, max_grid_x); + case 6: + return LaunchUnroll(output, a, b, count, stream, max_grid_x); + case 8: + return LaunchUnroll(output, a, b, count, stream, max_grid_x); + default: + return cudaErrorInvalidConfiguration; } } -#endif // __CUDACC__ \ No newline at end of file +template +cudaError_t Launch(T *output, const T *a, const T *b, uint64_t count, const LaunchConfig &config, + cudaStream_t stream, int max_grid_x) { + switch (config.block_size) { + case 128: + return LaunchBlock(output, a, b, count, stream, max_grid_x, config); + case 256: + return LaunchBlock(output, a, b, count, stream, max_grid_x, config); + case 512: + return LaunchBlock(output, a, b, count, stream, max_grid_x, config); + case 1024: + return LaunchBlock(output, a, b, count, stream, max_grid_x, config); + default: + return cudaErrorInvalidConfiguration; + } +} +} // namespace stream_kernels +#endif diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp index 668a1f0a1..53f5cda88 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp @@ -1,166 +1,127 @@ - // Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #include "gpu_stream_utils.hpp" +#include +#include +#include +#include + +namespace { +bool ParseUnsigned(const char *text, uint64_t *value) { + const char *end = text + std::strlen(text); + const auto parsed = std::from_chars(text, end, *value); + return parsed.ec == std::errc{} && parsed.ptr == end; +} + +template bool ParseChoice(const char *text, const std::array &allowed, int *value) { + uint64_t parsed = 0; + if (!ParseUnsigned(text, &parsed) || parsed > static_cast(std::numeric_limits::max())) { + return false; + } + if (std::find(allowed.begin(), allowed.end(), static_cast(parsed)) == allowed.end()) { + return false; + } + *value = static_cast(parsed); + return true; +} +} // namespace + namespace stream_config { -/** - * @brief Converts a kernel index to its corresponding string representation. - * - * @details This function takes an integer representing a kernel index and returns the corresponding - * string representation of the kernel. The mapping between kernel indices and their string representations - * should be defined within the function. - * - * @param[in] kernel_idx The index of the kernel to be converted to a string. - * - * @return std::string The string representation of the kernel. - */ std::string KernelToString(int kernel_idx) { - switch (kernel_idx) { - case static_cast(Kernel::kCopy): - return "COPY"; - case static_cast(Kernel::kScale): - return "SCALE"; - case static_cast(Kernel::kAdd): - return "ADD"; - case static_cast(Kernel::kTriad): - return "TRIAD"; - default: - return "UNKNOWN"; - } + const std::array names = {"COPY", "SCALE", "ADD", "TRIAD"}; + return kernel_idx >= 0 && kernel_idx < static_cast(names.size()) ? names[kernel_idx] : "UNKNOWN"; } -/** - * @brief Print the usage of this program. - * - * @details Thus function prints the usage of this program. - * - * @return void. - * */ void PrintUsage() { - std::cout << "Usage: gpu_stream " - << "--size " - << "--num_warm_up " - << "--num_loops " - << "[--data_type ] " - << "[--check_data]" << std::endl; + std::cout << "Usage: gpu_stream [--size ] [--num_warm_up ] [--num_loops ]\n" + << " [--data_type ] [--check_data]\n" + << " [--operation ] [--block_size ] [--unroll ]\n"; } -/** - * @brief Print the user provided inputs info. - * - * @details Thus function prints the parsed user provided inputs of this program.. - * - * @param[in] opts The Opts struct that stores the parsed values. - * - * @return void - * */ void PrintInputInfo(Opts &opts) { - std::cout << "STREAM Benchmark" << std::endl; - std::cout << "Buffer size(bytes): " << opts.size << std::endl; - std::cout << "Number of warm up runs: " << opts.num_warm_up << std::endl; - std::cout << "Number of loops: " << opts.num_loops << std::endl; - std::cout << "Data type: " << opts.data_type << std::endl; - std::cout << "Check data: " << (opts.check_data ? "Yes" : "No") << std::endl; + std::cout << "STREAM Benchmark\nBuffer size(bytes): " << opts.size + << "\nNumber of warm up runs: " << opts.num_warm_up << "\nNumber of loops: " << opts.num_loops + << "\nData type: " << opts.data_type << "\nCheck data: " << (opts.check_data ? "Yes" : "No") << std::endl; } -/** - * @brief Parse the command line options. - * - * @details Thus function parses the command line options and stores the values in the Opts struct. - * - * @param[in] argc The number of command line options. - * @param[in] argv The command line options. - * @param[out] opts The Opts struct to store the parsed values. - * - * @return int The status code. - * */ int ParseOpts(int argc, char **argv, Opts *opts) { - enum class OptIdx { kSize, kNumWarmUp, kNumLoops, kEnableCheckData, kDataType }; - const struct option options[] = {{"size", required_argument, nullptr, static_cast(OptIdx::kSize)}, - {"num_warm_up", required_argument, nullptr, static_cast(OptIdx::kNumWarmUp)}, - {"num_loops", required_argument, nullptr, static_cast(OptIdx::kNumLoops)}, - {"check_data", no_argument, nullptr, static_cast(OptIdx::kEnableCheckData)}, - {"data_type", required_argument, nullptr, static_cast(OptIdx::kDataType)}}; - int getopt_ret = 0; - int opt_idx = 0; - bool size_specified = false; - bool num_warm_up_specified = false; - bool num_loops_specified = false; - - bool parse_err = false; - while (true) { - getopt_ret = getopt_long(argc, argv, "", options, &opt_idx); - if (getopt_ret == -1) { - if (!size_specified || !num_warm_up_specified || !num_loops_specified) { - parse_err = true; - } - break; - } else if (getopt_ret == '?') { - parse_err = true; - break; - } - switch (opt_idx) { - case static_cast(OptIdx::kSize): - if (1 != sscanf(optarg, "%lu", &(opts->size))) { - std::cerr << "Invalid size: " << optarg << std::endl; - parse_err = true; - } else { - size_specified = true; - } + enum OptIdx { kSize, kWarmup, kLoops, kCheck, kType, kBlock, kUnroll, kOperation }; + const option options[] = { + {"size", required_argument, nullptr, kSize}, + {"num_warm_up", required_argument, nullptr, kWarmup}, + {"num_loops", required_argument, nullptr, kLoops}, + {"check_data", no_argument, nullptr, kCheck}, + {"data_type", required_argument, nullptr, kType}, + {"block_size", required_argument, nullptr, kBlock}, + {"unroll", required_argument, nullptr, kUnroll}, + {"operation", required_argument, nullptr, kOperation}, + {nullptr, 0, nullptr, 0}, + }; + int option_index = 0; + int token = 0; + while ((token = getopt_long(argc, argv, "", options, &option_index)) != -1) { + bool valid = true; + switch (token) { + case kSize: + valid = ParseUnsigned(optarg, &opts->size); break; - case static_cast(OptIdx::kNumWarmUp): - if (1 != sscanf(optarg, "%lu", &(opts->num_warm_up))) { - std::cerr << "Invalid num_warm_up: " << optarg << std::endl; - parse_err = true; - } else { - num_warm_up_specified = true; - } + case kWarmup: + valid = ParseUnsigned(optarg, &opts->num_warm_up); break; - case static_cast(OptIdx::kNumLoops): - if (1 != sscanf(optarg, "%lu", &(opts->num_loops))) { - std::cerr << "Invalid num_loops: " << optarg << std::endl; - parse_err = true; - } else { - num_loops_specified = true; - } + case kLoops: + valid = ParseUnsigned(optarg, &opts->num_loops); break; - case static_cast(OptIdx::kEnableCheckData): + case kCheck: opts->check_data = true; break; - case static_cast(OptIdx::kDataType): + case kType: opts->data_type = optarg; - if (opts->data_type != "float" && opts->data_type != "double") { - std::cerr << "Invalid data_type: " << optarg << ". Must be 'float' or 'double'." << std::endl; - parse_err = true; + valid = opts->data_type == "float" || opts->data_type == "double" || opts->data_type == "both"; + break; + case kBlock: + valid = ParseChoice(optarg, kThreadsPerBlock, &opts->block_size); + break; + case kUnroll: + valid = ParseChoice(optarg, kUnrollFactors, &opts->unroll); + break; + case kOperation: { + const std::array names = {"copy", "scale", "add", "triad"}; + const auto found = std::find_if(names.begin(), names.end(), + [&](const char *name) { return std::strcmp(name, optarg) == 0; }); + valid = found != names.end() || std::strcmp(optarg, "all") == 0; + if (found != names.end()) { + opts->operations = {static_cast(found - names.begin())}; + } else if (valid) { + opts->operations = {Kernel::kCopy, Kernel::kScale, Kernel::kAdd, Kernel::kTriad}; } break; + } default: - parse_err = true; + PrintUsage(); + return -1; } - if (parse_err) { - break; + if (!valid) { + std::cerr << "Invalid value for --" << options[option_index].name << ": " << optarg << std::endl; + return -1; } } - if (parse_err) { - PrintUsage(); + const uint64_t element_size = opts->data_type == "float" ? sizeof(float) : sizeof(double); + if (optind != argc || opts->size == 0 || opts->size % element_size != 0) { + std::cerr << "Size must be a positive multiple of " << element_size << " bytes; positional arguments are invalid" + << std::endl; + return -1; + } + if (opts->num_loops == 0 || opts->num_warm_up > std::numeric_limits::max() - opts->num_loops) { + std::cerr << "num_loops must be positive and num_warm_up + num_loops must not overflow" << std::endl; return -1; } return 0; } - } // namespace stream_config unsigned long long getCurrentTimestampInMicroseconds() { - // Get the current time point - auto now = std::chrono::system_clock::now(); - - // Convert to time since epoch - auto duration = now.time_since_epoch(); - - // Convert to microseconds - auto microseconds = std::chrono::duration_cast(duration).count(); - - return static_cast(microseconds); + const auto duration = std::chrono::system_clock::now().time_since_epoch(); + return static_cast(std::chrono::duration_cast(duration).count()); } diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp index 20f6a5654..04c329ef8 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp @@ -29,8 +29,9 @@ struct GpuBufferDeleter { unsigned long long getCurrentTimestampInMicroseconds(); namespace stream_config { -constexpr std::array kThreadsPerBlock = {128, 256, 512, 1024}; // Threads per block -constexpr uint64_t kDefaultBufferSizeInBytes = 4294967296; // Default buffer size 4GB +constexpr std::array kThreadsPerBlock = {128, 256, 512, 1024}; +constexpr std::array kUnrollFactors = {1, 2, 3, 4, 6, 8}; +constexpr uint64_t kDefaultBufferSizeInBytes = 8589934592; // 8 GiB per array constexpr int kNumBuffers = 3; // Number of buffers for triad, add kernel constexpr int kNumValidationBuffers = 4; // Number of validation buffers, one for each kernel constexpr int kUInt8Mod = 256; // Modulo for unsigned long data type @@ -46,6 +47,11 @@ enum class Kernel { kCount // Add a count to keep track of the number of enums. Helpful for iterating over enums. }; +struct LaunchConfig { + int block_size = 0; + int unroll = 0; +}; + // Arguments for each sub benchmark run. template struct SubBenchArgs { // Unique pointer for GPU buffers @@ -72,9 +78,6 @@ template struct SubBenchArgs { // CUDA event to record end time. cudaEvent_t end_event = nullptr; - // CUDA event to record end time. - std::vector> times_in_ms; - // Stream Kernel name. std::string kernel_name; }; @@ -92,7 +95,7 @@ template struct BenchArgs { uint64_t size = kDefaultBufferSizeInBytes; // Number of warm up rounds to run. - uint64_t num_warm_up = 0; + uint64_t num_warm_up = 10; // Number of loops to run. uint64_t num_loops = 1; @@ -110,16 +113,18 @@ struct Opts { uint64_t size = kDefaultBufferSizeInBytes; // Number of warm up rounds to run. - uint64_t num_warm_up = 0; + uint64_t num_warm_up = 10; // Number of loops to run. - uint64_t num_loops = 0; + uint64_t num_loops = 40; // Whether check data after copy. bool check_data = false; - // Data type for the benchmark ("float" or "double"). - std::string data_type = "double"; + std::string data_type = "both"; + int block_size = 0; + int unroll = 0; + std::vector operations{Kernel::kCopy, Kernel::kScale, Kernel::kAdd, Kernel::kTriad}; }; std::string KernelToString(int); // Function to convert enum to string diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json b/superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json new file mode 100644 index 000000000..34a84678d --- /dev/null +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json @@ -0,0 +1,41 @@ +{ + "h100": { + "buffer_size": 4294967296, + "kernels": { + "STREAM_COPY_float": {"block_size": 512, "unroll": 1}, + "STREAM_SCALE_float": {"block_size": 512, "unroll": 1}, + "STREAM_ADD_float": {"block_size": 128, "unroll": 1}, + "STREAM_TRIAD_float": {"block_size": 1024, "unroll": 1}, + "STREAM_COPY_double": {"block_size": 128, "unroll": 1}, + "STREAM_SCALE_double": {"block_size": 128, "unroll": 1}, + "STREAM_ADD_double": {"block_size": 128, "unroll": 1}, + "STREAM_TRIAD_double": {"block_size": 128, "unroll": 1} + } + }, + "gb300": { + "buffer_size": 8589934592, + "kernels": { + "STREAM_COPY_float": {"block_size": 1024, "unroll": 2}, + "STREAM_SCALE_float": {"block_size": 1024, "unroll": 2}, + "STREAM_ADD_float": {"block_size": 512, "unroll": 1}, + "STREAM_TRIAD_float": {"block_size": 512, "unroll": 1}, + "STREAM_COPY_double": {"block_size": 1024, "unroll": 2}, + "STREAM_SCALE_double": {"block_size": 1024, "unroll": 2}, + "STREAM_ADD_double": {"block_size": 512, "unroll": 1}, + "STREAM_TRIAD_double": {"block_size": 512, "unroll": 1} + } + }, + "vr": { + "buffer_size": 4294967296, + "kernels": { + "STREAM_COPY_float": {"block_size": 1024, "unroll": 4}, + "STREAM_SCALE_float": {"block_size": 1024, "unroll": 8}, + "STREAM_ADD_float": {"block_size": 1024, "unroll": 4}, + "STREAM_TRIAD_float": {"block_size": 1024, "unroll": 4}, + "STREAM_COPY_double": {"block_size": 1024, "unroll": 4}, + "STREAM_SCALE_double": {"block_size": 1024, "unroll": 4}, + "STREAM_ADD_double": {"block_size": 1024, "unroll": 4}, + "STREAM_TRIAD_double": {"block_size": 1024, "unroll": 4} + } + } +} diff --git a/tests/benchmarks/micro_benchmarks/test_gpu_stream.py b/tests/benchmarks/micro_benchmarks/test_gpu_stream.py index d9d836a92..3308b0fab 100644 --- a/tests/benchmarks/micro_benchmarks/test_gpu_stream.py +++ b/tests/benchmarks/micro_benchmarks/test_gpu_stream.py @@ -1,162 +1,217 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -"""Tests for gpu_stream benchmark.""" +"""Tests for the small GPU STREAM preset/fallback interface.""" -import numbers +import json +from pathlib import Path import unittest +from unittest import mock from tests.helper import decorator from tests.helper.testcase import BenchmarkTestCase -from superbench.benchmarks import BenchmarkRegistry, BenchmarkType, ReturnCode, Platform +from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode +from superbench.benchmarks.micro_benchmarks import gpu_stream +@decorator.cuda_test class GpuStreamBenchmarkTest(BenchmarkTestCase, unittest.TestCase): - """Test class for gpu_stream benchmark.""" + """Test explicit presets, native commands, and canonical result parsing.""" + @classmethod def setUpClass(cls): - """Hook method for setting up class fixture before running tests in the class.""" + """Create the existing mock binary environment.""" super().setUpClass() cls.createMockEnvs(cls) cls.createMockFiles(cls, ['bin/gpu_stream']) - def _test_gpu_stream_command_generation(self, platform, data_type='double'): - """Test gpu-stream benchmark command generation.""" - benchmark_name = 'gpu-stream' - (benchmark_class, - predefine_params) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(benchmark_name, platform) - assert (benchmark_class) - - num_warm_up = 5 - num_loops = 10 - size = 25769803776 - - parameters = '--num_warm_up %d --num_loops %d --size %d --data_type %s ' \ - '--check_data' % \ - (num_warm_up, num_loops, size, data_type) - benchmark = benchmark_class(benchmark_name, parameters=parameters) - - # Check basic information - assert (benchmark) - ret = benchmark._preprocess() - assert (ret is True) - assert (benchmark.return_code == ReturnCode.SUCCESS) - assert (benchmark.name == benchmark_name) - assert (benchmark.type == BenchmarkType.MICRO) - - # Check parameters specified in BenchmarkContext. - assert (benchmark._args.size == size) - assert (benchmark._args.num_warm_up == num_warm_up) - assert (benchmark._args.num_loops == num_loops) - assert (benchmark._args.check_data) - assert (benchmark._args.data_type == data_type) - - # Check command - assert (1 == len(benchmark._commands)) - assert (benchmark._commands[0].startswith(benchmark._GpuStreamBenchmark__bin_path)) - assert ('--size %d' % size in benchmark._commands[0]) - assert ('--num_warm_up %d' % num_warm_up in benchmark._commands[0]) - assert ('--num_loops %d' % num_loops in benchmark._commands[0]) - assert ('--data_type %s' % data_type in benchmark._commands[0]) - assert ('--check_data' in benchmark._commands[0]) - - @decorator.cuda_test - def test_gpu_stream_command_generation_cuda(self): - """Test gpu-stream benchmark command generation, CUDA case.""" - self._test_gpu_stream_command_generation(Platform.CUDA) - - @decorator.cuda_test - def test_gpu_stream_command_generation_cuda_float(self): - """Test gpu-stream benchmark command generation with float, CUDA case.""" - self._test_gpu_stream_command_generation(Platform.CUDA, data_type='float') - - @decorator.load_data('tests/data/gpu_stream.log') - def _test_gpu_stream_result_parsing(self, platform, test_raw_output): - """Test gpu-stream benchmark result parsing.""" - benchmark_name = 'gpu-stream' - (benchmark_class, - predefine_params) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(benchmark_name, platform) - assert (benchmark_class) - benchmark = benchmark_class(benchmark_name, parameters='') - assert (benchmark) - ret = benchmark._preprocess() - assert (ret is True) - assert (benchmark.return_code == ReturnCode.SUCCESS) - assert (benchmark.name == 'gpu-stream') - assert (benchmark.type == BenchmarkType.MICRO) - - # Positive case - valid raw output. - assert (benchmark._process_raw_result(0, test_raw_output)) - assert (benchmark.return_code == ReturnCode.SUCCESS) - - assert (1 == len(benchmark.raw_data)) - # print(test_raw_output.splitlines()) - test_raw_output_dict = { - x.split()[0]: [float(x.split()[1]), float(x.split()[2])] - for x in test_raw_output.strip().splitlines() if x.startswith('STREAM_') - } - assert (len(test_raw_output_dict) * 2 + benchmark.default_metric_count == len(benchmark.result)) - for output_key in benchmark.result: - if output_key == 'return_code': - assert (benchmark.result[output_key] == [0]) - else: - assert (len(benchmark.result[output_key]) == 1) - assert (isinstance(benchmark.result[output_key][0], numbers.Number)) - if output_key.endswith('_bw'): - assert (output_key[:-3] in test_raw_output_dict) - assert (test_raw_output_dict[output_key[:-3]][0] == benchmark.result[output_key][0]) - else: - assert (output_key.endswith('_ratio')) - assert (output_key[:-6] in test_raw_output_dict) - assert (test_raw_output_dict[output_key[:-6]][1] == benchmark.result[output_key][0]) - - # Negative case - invalid raw output. - assert (benchmark._process_raw_result(1, 'Invalid raw output') is False) - assert (benchmark.return_code == ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) - - @decorator.cuda_test - def test_gpu_stream_result_parsing_cuda(self): - """Test gpu-stream benchmark result parsing, CUDA case.""" - self._test_gpu_stream_result_parsing(Platform.CUDA) - - @decorator.load_data('tests/data/gpu_stream_float.log') - def _test_gpu_stream_result_parsing_float(self, platform, test_raw_output): - """Test gpu-stream benchmark result parsing for float data type.""" - benchmark_name = 'gpu-stream' - (benchmark_class, - predefine_params) = BenchmarkRegistry._BenchmarkRegistry__select_benchmark(benchmark_name, platform) - assert (benchmark_class) - benchmark = benchmark_class(benchmark_name, parameters='--data_type float') - assert (benchmark) - ret = benchmark._preprocess() - assert (ret is True) - assert (benchmark.return_code == ReturnCode.SUCCESS) - - # Positive case - valid raw output with float tags. - assert (benchmark._process_raw_result(0, test_raw_output)) - assert (benchmark.return_code == ReturnCode.SUCCESS) - - assert (1 == len(benchmark.raw_data)) - test_raw_output_dict = { - x.split()[0]: [float(x.split()[1]), float(x.split()[2])] - for x in test_raw_output.strip().splitlines() if x.startswith('STREAM_') - } - assert (len(test_raw_output_dict) * 2 + benchmark.default_metric_count == len(benchmark.result)) - for output_key in benchmark.result: - if output_key == 'return_code': - assert (benchmark.result[output_key] == [0]) - else: - assert (len(benchmark.result[output_key]) == 1) - assert (isinstance(benchmark.result[output_key][0], numbers.Number)) - if output_key.endswith('_bw'): - assert (output_key[:-3] in test_raw_output_dict) - assert (test_raw_output_dict[output_key[:-3]][0] == benchmark.result[output_key][0]) - else: - assert (output_key.endswith('_ratio')) - assert (output_key[:-6] in test_raw_output_dict) - assert (test_raw_output_dict[output_key[:-6]][1] == benchmark.result[output_key][0]) - - @decorator.cuda_test - def test_gpu_stream_result_parsing_cuda_float(self): - """Test gpu-stream benchmark result parsing for float, CUDA case.""" - self._test_gpu_stream_result_parsing_float(Platform.CUDA) + def benchmark(self, parameters='', gpu_name=None): + """Create a benchmark without querying hardware.""" + if gpu_name is not None: + parameters += ' --gpu_name {}'.format(gpu_name) + benchmark_class, _ = BenchmarkRegistry._BenchmarkRegistry__select_benchmark('gpu-stream', Platform.CUDA) + benchmark = benchmark_class('gpu-stream', parameters=parameters) + self.assertTrue(benchmark._preprocess()) + return benchmark + + @staticmethod + def output(tags, bandwidth=100): + """Build synthetic canonical results, not recorded hardware measurements.""" + return '\n'.join(['STREAM Benchmark', 'GPU_STREAM_CONFIG ignored raw launch details'] + + ['{}\t{}\t25'.format(tag, bandwidth) for tag in sorted(tags)]) + + def test_unknown_chip_with_explicit_size_uses_native_sweep(self): + """Unknown chips sweep at the requested size without tuning-mode flags.""" + benchmark = self.benchmark('--size 1048576 --num_warm_up 5 --num_loops 10 --check_data') + self.assertEqual(len(benchmark._commands), 1) + command = benchmark._commands[0] + for value in ['--size 1048576', '--num_warm_up 5', '--num_loops 10', '--data_type both', '--check_data']: + self.assertIn(value, command) + self.assertNotIn('--block_size', command) + self.assertNotIn('--mode', command) + self.assertEqual(len(benchmark._command_targets[0]), 8) + + def test_unknown_chip_falls_back_to_fixed_sweep(self): + """Future chip names do not inherit another chip's preset.""" + benchmark = self.benchmark(gpu_name='future_gpu') + self.assertEqual(len(benchmark._commands), 1) + self.assertIn('--size 8589934592', benchmark._commands[0]) + self.assertNotIn('--block_size', benchmark._commands[0]) + + def test_omitted_gpu_name_autotunes_without_loading_presets(self): + """The normal YAML without a GPU name explicitly takes the sweep path.""" + with mock.patch.object(gpu_stream.json, 'load', side_effect=AssertionError('unexpected preset read')): + benchmark = self.benchmark() + self.assertEqual(len(benchmark._commands), 1) + self.assertNotIn('--block_size', benchmark._commands[0]) + + def test_fixed_sweep_excludes_64_threads(self): + """Keep the reduced four-block by six-unroll fallback space.""" + self.assertEqual(gpu_stream._BLOCKS, [128, 256, 512, 1024]) + self.assertEqual(len(gpu_stream._BLOCKS) * len(gpu_stream._UNROLLS), 24) + + def test_named_chip_uses_only_config_parameters(self): + """A chip-name entry produces one configured command per workload.""" + benchmark = self.benchmark(gpu_name='h100') + self.assertEqual(len(benchmark._commands), 8) + for command in benchmark._commands: + self.assertIn('--size 4294967296', command) + self.assertIn('--block_size', command) + self.assertIn('--unroll', command) + self.assertNotIn('--grid', command) + self.assertNotIn('--device_info', command) + + def test_explicit_size_keeps_chip_launch_presets(self): + """A YAML size override changes every buffer without disabling presets.""" + benchmark = self.benchmark('--size 1048576', gpu_name='h100') + self.assertEqual(len(benchmark._commands), 8) + self.assertTrue(all('--size 1048576' in command and '--block_size' in command + and '--unroll' in command for command in benchmark._commands)) + + def test_legacy_fp64_parameters_remain_valid(self): + """Preserve the supplied fp64 configuration and use its explicit buffer size.""" + benchmark = self.benchmark( + '--num_warm_up 10 --num_loops 40 --size 4294967296 --data_type double', gpu_name='vr' + ) + self.assertEqual(len(benchmark._commands), 4) + for command in benchmark._commands: + for value in ['--size 4294967296', '--num_warm_up 10', '--num_loops 40', + '--data_type double', '--block_size', '--unroll']: + self.assertIn(value, command) + + def test_explicit_vr_key_is_supported(self): + """VR selection is a user-provided key, not a driver-name heuristic.""" + benchmark = self.benchmark(gpu_name='vr') + self.assertEqual(len(benchmark._commands), 8) + self.assertTrue(all('--block_size' in command for command in benchmark._commands)) + + def test_all_named_gpu_defaults(self): + """Resolve the three supported JSON keys without any device-name lookup.""" + for gpu_name, size in [('h100', 4294967296), ('gb300', 8589934592), ('vr', 4294967296)]: + with self.subTest(gpu_name=gpu_name): + benchmark = self.benchmark(gpu_name=gpu_name) + self.assertEqual(len(benchmark._commands), 8) + self.assertTrue(all('--size {}'.format(size) in command for command in benchmark._commands)) + + def test_partial_chip_config_sweeps_missing_operations(self): + """A new profile can be contributed incrementally.""" + profiles = {'example_gpu': {'buffer_size': 1048576, + 'kernels': {'STREAM_COPY_double': {'block_size': 128, 'unroll': 2}}}} + with mock.patch.object(gpu_stream.json, 'load', return_value=profiles): + benchmark = self.benchmark('--data_type double', gpu_name='example_gpu') + self.assertEqual(len(benchmark._commands), 4) + self.assertEqual(sum('--block_size' in command for command in benchmark._commands), 1) + self.assertTrue(all('--size 1048576' in command for command in benchmark._commands)) + + def test_profile_file_contains_no_measurement_or_validation_data(self): + """The public data file contains chip names and launch parameters only.""" + profiles = json.loads(Path(gpu_stream.__file__).with_name('gpu_stream_profiles.json').read_text()) + self.assertTrue(profiles) + self.assertTrue({'h100', 'gb300', 'vr'}.issubset(profiles)) + for chip, profile in profiles.items(): + self.assertIsInstance(chip, str) + self.assertEqual(set(profile), {'buffer_size', 'kernels'}) + self.assertIs(type(profile['buffer_size']), int) + for tag, config in profile['kernels'].items(): + self.assertEqual(set(config), {'block_size', 'unroll'}) + gpu_stream.GpuStreamBenchmark._check_config(tag, config) + + def test_bad_profile_is_an_error_not_a_fallback(self): + """Invalid matched configuration must not silently become a successful sweep.""" + for config in [ + {'block_size': True, 'unroll': 2}, + {'block_size': 64, 'unroll': 2}, + {'block_size': 96, 'unroll': 2}, + {'block_size': 128, 'unroll': 5}, + {'block_size': 128, 'unroll': 2, 'bandwidth_gbps': 123}, + ]: + with self.subTest(config=config): + benchmark_class, _ = BenchmarkRegistry._BenchmarkRegistry__select_benchmark('gpu-stream', Platform.CUDA) + benchmark = benchmark_class('gpu-stream', parameters='--gpu_name example_gpu') + with mock.patch.object(gpu_stream.json, 'load', + return_value={'example_gpu': {'buffer_size': 1048576, + 'kernels': {'STREAM_COPY_double': config}}}): + self.assertFalse(benchmark._preprocess()) + self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) + self.assertEqual(benchmark._commands, []) + + def test_invalid_chip_buffer_size_is_reported(self): + """A shared default must support both scalar widths.""" + for size in [0, 3, True, 2**64]: + benchmark_class, _ = BenchmarkRegistry._BenchmarkRegistry__select_benchmark('gpu-stream', Platform.CUDA) + benchmark = benchmark_class('gpu-stream', parameters='--gpu_name example_gpu') + with mock.patch.object(gpu_stream.json, 'load', + return_value={'example_gpu': {'buffer_size': size, 'kernels': {}}}): + self.assertFalse(benchmark._preprocess()) + self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) + + def test_gpu_name_is_case_insensitive(self): + """Match supplied names against the lowercase JSON keys.""" + benchmark = self.benchmark(gpu_name='H100') + self.assertEqual(benchmark._args.gpu_name, 'h100') + self.assertEqual(len(benchmark._commands), 8) + + def test_empty_gpu_name_is_rejected(self): + """Do not silently treat an empty explicit name as a preset.""" + benchmark_class, _ = BenchmarkRegistry._BenchmarkRegistry__select_benchmark('gpu-stream', Platform.CUDA) + benchmark = benchmark_class('gpu-stream', parameters='--gpu_name \"\"') + self.assertFalse(benchmark._preprocess()) + self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) + + def test_canonical_results_and_repetitions(self): + """Publish one fresh value per workload per framework repetition.""" + benchmark = self.benchmark('--size 1048576') + tags = benchmark._command_targets[0] + self.assertTrue(benchmark._process_raw_result(0, self.output(tags, 200))) + self.assertTrue(benchmark._process_raw_result(0, self.output(tags, 100))) + self.assertEqual(benchmark.result['STREAM_ADD_double_bw'], [200, 100]) + self.assertEqual(len(benchmark.result), benchmark.default_metric_count + 16) + self.assertTrue(all('_buffer_' not in key and '_block_' not in key for key in benchmark.result)) + + def test_single_float_and_scalar_tail_arguments(self): + """Keep the original single-datatype use case and scalar-aligned sizes.""" + benchmark = self.benchmark('--size 68 --data_type float') + self.assertIn('--data_type float', benchmark._commands[0]) + self.assertEqual(len(benchmark._command_targets[0]), 4) + + def test_invalid_result_never_returns_bandwidth(self): + """Reject missing, duplicate, malformed, and nonfinite canonical rows.""" + for transform in [ + lambda output: '', + lambda output: output + '\nSTREAM_COPY_double 300 25', + lambda output: output.replace('\t100\t25', '\tnan\t25'), + lambda output: output.replace('\t100\t25', '\tinf\t25'), + lambda output: output.replace('\t100\t25', '\t-1\t25'), + ]: + benchmark = self.benchmark('--size 1048576 --data_type double') + self.assertFalse(benchmark._process_raw_result(0, transform(self.output(benchmark._command_targets[0])))) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) + self.assertNotIn('STREAM_COPY_double_bw', benchmark.result) + + def test_invalid_size_and_loop_counts(self): + """Retain the normal native input constraints.""" + benchmark_class, _ = BenchmarkRegistry._BenchmarkRegistry__select_benchmark('gpu-stream', Platform.CUDA) + for parameters in ['--size 0', '--size 12', '--num_loops 0', '--num_warm_up -1']: + benchmark = benchmark_class('gpu-stream', parameters=parameters) + self.assertFalse(benchmark._preprocess()) + self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) From 933aa7ef52bd055cd68d11da77e454e72d40c445 Mon Sep 17 00:00:00 2001 From: Wenqing Lan Date: Thu, 5 Nov 2026 22:59:56 +0000 Subject: [PATCH 3/5] replace preset with yaml config option Co-authored-by: dpower4 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- MANIFEST.in | 1 - .../benchmarks/micro-benchmarks.md | 34 ++- examples/benchmarks/gpu_stream.py | 5 +- .../benchmarks/micro_benchmarks/gpu_stream.py | 79 ++--- .../micro_benchmarks/gpu_stream/gpu_stream.cu | 21 +- .../gpu_stream/gpu_stream_utils.cpp | 4 +- .../gpu_stream/gpu_stream_utils.hpp | 2 +- .../micro_benchmarks/gpu_stream_profiles.json | 41 --- .../micro_benchmarks/test_gpu_stream.py | 283 +++++++----------- tests/data/gpu_stream.log | 27 +- tests/data/gpu_stream_float.log | 27 +- 11 files changed, 195 insertions(+), 329 deletions(-) delete mode 100644 superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json diff --git a/MANIFEST.in b/MANIFEST.in index 4ebe62113..34d9d0272 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -1,4 +1,3 @@ include LICENSE README.md recursive-include superbench *.py *.j2 *.yaml -include superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json global-exclude *.py[cod] __pycache__ diff --git a/docs/user-tutorial/benchmarks/micro-benchmarks.md b/docs/user-tutorial/benchmarks/micro-benchmarks.md index 539d3e6a2..7ff3f769b 100644 --- a/docs/user-tutorial/benchmarks/micro-benchmarks.md +++ b/docs/user-tutorial/benchmarks/micro-benchmarks.md @@ -441,18 +441,42 @@ For measurements of peer-to-peer communication performance between AMD GPUs, GPU #### Introduction -Measures Copy, Scale, Add, and Triad bandwidth for float and double. Set `gpu_name: h100`, `gb300`, or `vr` to select [gpu_stream_profiles.json](../../../superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json), with one buffer size per GPU and block/unroll settings per workload. GPU names are not detected. +Measures Copy, Scale, Add, and Triad memory bandwidth for one `data_type` (`float` or `double`, default `double`). Use a separate benchmark entry for each data type. -Omit `gpu_name` to autotune; unrecognized names and missing presets also use the fixed block/unroll sweep. `size` is bytes per array and overrides the preset buffer without disabling launch presets. If omitted, the GPU default is used (8 GiB without a profile). Both datatypes are selected unless `data_type` is specified. +By default, each operation sweeps block sizes (128, 256, 512, 1024) and unroll factors (1, 2, 3, 4, 6, 8) and reports the best result. `kernel_configs` sets `block_size` and `unroll` per operation as inline JSON; unlisted operations still sweep. `size` is bytes per array (default 8 GiB). `check_data` validates output outside timing and needs 6x `size` in host memory, so use small size like 1048576. -`check_data` checks output outside timing and needs 6x buffer size in host memory. Use small buffers for validation. +Native sweep: + +```yaml +gpu-stream:fp64: + <<: *default_local_mode + parameters: + data_type: double +``` + +Fixed launch configuration: + +```yaml +gpu-stream:fp64: + <<: *default_local_mode + parameters: + data_type: double + size: 4294967296 + kernel_configs: >- + '{ + "STREAM_COPY_double": {"block_size": 256, "unroll": 2}, + "STREAM_SCALE_double": {"block_size": 256, "unroll": 2}, + "STREAM_ADD_double": {"block_size": 256, "unroll": 2}, + "STREAM_TRIAD_double": {"block_size": 256, "unroll": 2} + }' +``` #### Metrics | Metric Name | Unit | Description | |-------------|------|-------------| -| STREAM\_(COPY\|SCALE\|ADD\|TRIAD)\_(double\|float)\_bw | GB/s | Fresh preset bandwidth or the highest measured bandwidth from the fixed sweep. | -| STREAM\_(COPY\|SCALE\|ADD\|TRIAD)\_(double\|float)\_ratio | % | Efficiency from the same winning measurement; -1 if theoretical peak is unavailable. | +| STREAM\_(COPY\|SCALE\|ADD\|TRIAD)\_(double\|float)\_bw | GB/s | Bandwidth with the configured launch, or the best bandwidth from the sweep. | +| STREAM\_(COPY\|SCALE\|ADD\|TRIAD)\_(double\|float)\_ratio | % | Bandwidth as a percentage of theoretical peak; -1 if peak is unavailable. | For example: `gpu-stream:fp64/STREAM_ADD_double_bw`. Selected launch parameters stay in raw output. diff --git a/examples/benchmarks/gpu_stream.py b/examples/benchmarks/gpu_stream.py index c7a4faba1..7af708431 100644 --- a/examples/benchmarks/gpu_stream.py +++ b/examples/benchmarks/gpu_stream.py @@ -6,7 +6,8 @@ Commands to run: python3 examples/benchmarks/gpu_stream.py -Omit gpu_name to autotune; add --gpu_name h100, gb300, or vr to use a preset. +Omit kernel_configs to autotune; supply --kernel_configs with a quoted JSON +mapping of workload tags to block_size/unroll overrides to skip tuning. """ from superbench.benchmarks import BenchmarkRegistry, Platform @@ -14,7 +15,7 @@ if __name__ == '__main__': context = BenchmarkRegistry.create_benchmark_context( - 'gpu-stream', platform=Platform.CUDA, parameters='--num_warm_up 10 --num_loops 40 --data_type both' + 'gpu-stream', platform=Platform.CUDA, parameters='--num_warm_up 10 --num_loops 40 --data_type double' ) # To enable data checking, please add '--check_data'. diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream.py b/superbench/benchmarks/micro_benchmarks/gpu_stream.py index 41ca78eae..5f21333d0 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream.py +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream.py @@ -1,12 +1,11 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT license. -"""GPU STREAM bandwidth with chip presets and a fixed fallback sweep.""" +"""GPU STREAM bandwidth with inline launch overrides and a fixed fallback sweep.""" import json import math import os -from pathlib import Path import re import shlex @@ -34,55 +33,43 @@ def __init__(self, name, parameters=''): def add_parser_arguments(self): """Retain the normal benchmark arguments; search dimensions are fixed.""" super().add_parser_arguments() - self._parser.add_argument('--gpu_name', type=str.lower, default=None, - help='GPU preset key (h100, gb300, vr). Omit to autotune.') - self._parser.add_argument('--size', type=int, default=None, - help='Bytes per array; overrides the chip default without changing launch presets.') + self._parser.add_argument('--kernel_configs', type=str, default=None, + help='JSON mapping of workload tags to block_size/unroll. Omit to autotune.') + self._parser.add_argument('--size', type=int, default=_DEFAULT_SIZE, + help='Bytes per array, independent of launch overrides (default: 8 GiB).') self._parser.add_argument('--num_warm_up', type=int, default=20) self._parser.add_argument('--num_loops', type=int, default=100) - self._parser.add_argument('--data_type', choices=['float', 'double', 'both'], default='both') + self._parser.add_argument('--data_type', choices=['float', 'double'], default='double', + help='Element type; use one benchmark entry per data type.') self._parser.add_argument('--check_data', action='store_true', - help='Validate output. Requires 6x buffer size in host memory; use small sizes.') + help='Validate output. Requires 6x buffer size in host memory; use small sizes.') @staticmethod def _check_config(tag, config): - """Check only the parameters needed to launch a preset.""" + """Check only the parameters needed to launch a workload.""" match = _TAG.fullmatch(tag) if match is None or not isinstance(config, dict): - raise ValueError('Invalid chip configuration key: {}'.format(tag)) + raise ValueError('Invalid workload configuration key: {}'.format(tag)) if set(config) != {'block_size', 'unroll'} or any(type(value) is not int for value in config.values()): raise ValueError('{} needs integer block_size and unroll'.format(tag)) if config['block_size'] not in _BLOCKS or config['unroll'] not in _UNROLLS: raise ValueError('Unsupported block size/unroll for {}'.format(tag)) - def _gpu_config(self): - """Select only the GPU name supplied by the user.""" - gpu_name = self._args.gpu_name - if gpu_name is None: + def _kernel_configs(self): + """Load explicit workload overrides for the selected data type only.""" + if self._args.kernel_configs is None: return {} - if not gpu_name.strip(): - raise ValueError('gpu_name must not be empty') - with Path(__file__).with_name('gpu_stream_profiles.json').open(encoding='utf-8') as stream: - profiles = json.load(stream) - if not isinstance(profiles, dict) or any(not isinstance(value, dict) for value in profiles.values()): - raise ValueError('Expected a chip-name to configuration mapping') - if gpu_name not in profiles: - logger.warning('No GPU STREAM preset for {}; using the fixed sweep.'.format(gpu_name)) - return {} - profile = profiles[gpu_name] - if set(profile) != {'buffer_size', 'kernels'} or not isinstance(profile['kernels'], dict): - raise ValueError('Each chip needs one buffer_size and a kernels mapping') - size = profile['buffer_size'] - if type(size) is not int or not 0 < size < 2**64 or size % 8: - raise ValueError('Chip buffer_size must be a positive multiple of 8 bytes') - configs = profile['kernels'] + configs = json.loads(self._args.kernel_configs) + if not isinstance(configs, dict): + raise ValueError('Expected a workload-tag to configuration mapping') for tag, config in configs.items(): self._check_config(tag, config) - logger.info('GPU STREAM {}: {}.'.format(gpu_name, 'preset' if configs else 'fallback sweep')) - return profile + if not tag.endswith('_' + self._args.data_type): + raise ValueError('{} does not match data_type {}'.format(tag, self._args.data_type)) + return configs def _command(self, dtype, operation, size, config=None): - """Use singleton native parameters for presets, or the native fixed sweep.""" + """Use singleton native parameters for overrides, or the native fixed sweep.""" parts = [ shlex.quote(self.__bin_path), '--size', str(size), '--data_type', dtype, '--operation', operation, '--num_warm_up', str(self._args.num_warm_up), '--num_loops', str(self._args.num_loops), @@ -94,7 +81,7 @@ def _command(self, dtype, operation, size, config=None): return ' '.join(parts) def _preprocess(self): - """Resolve size once, independently of chip launch presets.""" + """Resolve size once, independently of workload launch overrides.""" if not super()._preprocess(): return False self.__bin_path = os.path.join(self._args.bin_dir, self._bin_name) @@ -104,25 +91,21 @@ def _preprocess(self): self._args.num_warm_up + self._args.num_loops >= 2**64): raise ValueError('Invalid warm-up/loop counts') width = 4 if self._args.data_type == 'float' else 8 - if self._args.size is not None and (not 0 < self._args.size < 2**64 or self._args.size % width): + if not 0 < self._args.size < 2**64 or self._args.size % width: raise ValueError('Size must be a positive multiple of {} bytes'.format(width)) - profile = self._gpu_config() - configs = profile.get('kernels', {}) - size = self._args.size if self._args.size is not None else profile.get('buffer_size', _DEFAULT_SIZE) - dtypes = ['float', 'double'] if self._args.data_type == 'both' else [self._args.data_type] + configs = self._kernel_configs() + size, dtype = self._args.size, self._args.data_type commands, targets = [], [] if not configs: - commands.append(self._command(self._args.data_type, 'all', size)) - targets.append({'STREAM_{}_{}'.format(op.upper(), dtype) for dtype in dtypes for op in _OPERATIONS}) + commands.append(self._command(dtype, 'all', size)) + targets.append({'STREAM_{}_{}'.format(op.upper(), dtype) for op in _OPERATIONS}) else: - for dtype in dtypes: - for operation in _OPERATIONS: - tag = 'STREAM_{}_{}'.format(operation.upper(), dtype) - config = configs.get(tag) - commands.append(self._command(dtype, operation, size, config)) - targets.append({tag}) + for operation in _OPERATIONS: + tag = 'STREAM_{}_{}'.format(operation.upper(), dtype) + commands.append(self._command(dtype, operation, size, configs.get(tag))) + targets.append({tag}) self._commands, self._command_targets = commands, targets - except (OSError, ValueError) as error: + except ValueError as error: self._result.set_return_code(ReturnCode.INVALID_ARGUMENT) logger.error('Invalid GPU STREAM configuration: {}.'.format(error)) return False diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu index b4734173d..ff1000ef8 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu @@ -749,7 +749,7 @@ int GpuStream::Run() { std::cerr << "Run::No GPU available" << std::endl; return -1; } - if (opts_.data_type != "float" && opts_.data_type != "double" && opts_.data_type != "both") { + if (opts_.data_type != "float" && opts_.data_type != "double") { std::cerr << "Run::Invalid data_type: " << opts_.data_type << std::endl; return -1; } @@ -799,14 +799,11 @@ int GpuStream::Run() { return -1; } - const std::vector data_types = - opts_.data_type == "both" ? std::vector{"float", "double"} : std::vector{opts_.data_type}; - for (const auto &data_type : data_types) { - ret = data_type == "float" ? CreateBenchArgs() : CreateBenchArgs(); - if (ret != 0) { - return ret; - } - std::visit( + ret = opts_.data_type == "float" ? CreateBenchArgs() : CreateBenchArgs(); + if (ret != 0) { + return ret; + } + std::visit( [&](auto &curr_args) { // Get memory clock rate once for both bandwidth computation and display float memory_clock_mhz = GetMemoryClockRate(curr_args->gpu_id, curr_args->gpu_device_prop); @@ -837,11 +834,7 @@ int GpuStream::Run() { std::cerr << "Run::RunStream error: " << ret << std::endl; } }, - bench_args_); - if (ret != 0) { - return ret; - } - } + bench_args_); return ret; } \ No newline at end of file diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp index 53f5cda88..b6f70b946 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp @@ -36,7 +36,7 @@ std::string KernelToString(int kernel_idx) { void PrintUsage() { std::cout << "Usage: gpu_stream [--size ] [--num_warm_up ] [--num_loops ]\n" - << " [--data_type ] [--check_data]\n" + << " [--data_type ] [--check_data]\n" << " [--operation ] [--block_size ] [--unroll ]\n"; } @@ -78,7 +78,7 @@ int ParseOpts(int argc, char **argv, Opts *opts) { break; case kType: opts->data_type = optarg; - valid = opts->data_type == "float" || opts->data_type == "double" || opts->data_type == "both"; + valid = opts->data_type == "float" || opts->data_type == "double"; break; case kBlock: valid = ParseChoice(optarg, kThreadsPerBlock, &opts->block_size); diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp index 04c329ef8..eb37776b8 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp @@ -121,7 +121,7 @@ struct Opts { // Whether check data after copy. bool check_data = false; - std::string data_type = "both"; + std::string data_type = "double"; int block_size = 0; int unroll = 0; std::vector operations{Kernel::kCopy, Kernel::kScale, Kernel::kAdd, Kernel::kTriad}; diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json b/superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json deleted file mode 100644 index 34a84678d..000000000 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream_profiles.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "h100": { - "buffer_size": 4294967296, - "kernels": { - "STREAM_COPY_float": {"block_size": 512, "unroll": 1}, - "STREAM_SCALE_float": {"block_size": 512, "unroll": 1}, - "STREAM_ADD_float": {"block_size": 128, "unroll": 1}, - "STREAM_TRIAD_float": {"block_size": 1024, "unroll": 1}, - "STREAM_COPY_double": {"block_size": 128, "unroll": 1}, - "STREAM_SCALE_double": {"block_size": 128, "unroll": 1}, - "STREAM_ADD_double": {"block_size": 128, "unroll": 1}, - "STREAM_TRIAD_double": {"block_size": 128, "unroll": 1} - } - }, - "gb300": { - "buffer_size": 8589934592, - "kernels": { - "STREAM_COPY_float": {"block_size": 1024, "unroll": 2}, - "STREAM_SCALE_float": {"block_size": 1024, "unroll": 2}, - "STREAM_ADD_float": {"block_size": 512, "unroll": 1}, - "STREAM_TRIAD_float": {"block_size": 512, "unroll": 1}, - "STREAM_COPY_double": {"block_size": 1024, "unroll": 2}, - "STREAM_SCALE_double": {"block_size": 1024, "unroll": 2}, - "STREAM_ADD_double": {"block_size": 512, "unroll": 1}, - "STREAM_TRIAD_double": {"block_size": 512, "unroll": 1} - } - }, - "vr": { - "buffer_size": 4294967296, - "kernels": { - "STREAM_COPY_float": {"block_size": 1024, "unroll": 4}, - "STREAM_SCALE_float": {"block_size": 1024, "unroll": 8}, - "STREAM_ADD_float": {"block_size": 1024, "unroll": 4}, - "STREAM_TRIAD_float": {"block_size": 1024, "unroll": 4}, - "STREAM_COPY_double": {"block_size": 1024, "unroll": 4}, - "STREAM_SCALE_double": {"block_size": 1024, "unroll": 4}, - "STREAM_ADD_double": {"block_size": 1024, "unroll": 4}, - "STREAM_TRIAD_double": {"block_size": 1024, "unroll": 4} - } - } -} diff --git a/tests/benchmarks/micro_benchmarks/test_gpu_stream.py b/tests/benchmarks/micro_benchmarks/test_gpu_stream.py index 3308b0fab..c5fb7f683 100644 --- a/tests/benchmarks/micro_benchmarks/test_gpu_stream.py +++ b/tests/benchmarks/micro_benchmarks/test_gpu_stream.py @@ -1,217 +1,138 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -"""Tests for the small GPU STREAM preset/fallback interface.""" +"""Tests for gpu-stream benchmark.""" import json from pathlib import Path +import shlex import unittest -from unittest import mock + +from omegaconf import OmegaConf from tests.helper import decorator from tests.helper.testcase import BenchmarkTestCase from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode -from superbench.benchmarks.micro_benchmarks import gpu_stream +from superbench.executor import SuperBenchExecutor + +_TAGS = ['STREAM_COPY_double', 'STREAM_SCALE_double', 'STREAM_ADD_double', 'STREAM_TRIAD_double'] @decorator.cuda_test class GpuStreamBenchmarkTest(BenchmarkTestCase, unittest.TestCase): - """Test explicit presets, native commands, and canonical result parsing.""" - + """Test command generation and result parsing with synthetic data.""" @classmethod def setUpClass(cls): - """Create the existing mock binary environment.""" + """Create mock binary environment.""" super().setUpClass() cls.createMockEnvs(cls) cls.createMockFiles(cls, ['bin/gpu_stream']) - def benchmark(self, parameters='', gpu_name=None): - """Create a benchmark without querying hardware.""" - if gpu_name is not None: - parameters += ' --gpu_name {}'.format(gpu_name) + def create(self, parameters='', configs=None): + """Create a benchmark and run preprocess.""" + if configs is not None: + parameters += ' --kernel_configs {}'.format(shlex.quote(json.dumps(configs))) benchmark_class, _ = BenchmarkRegistry._BenchmarkRegistry__select_benchmark('gpu-stream', Platform.CUDA) benchmark = benchmark_class('gpu-stream', parameters=parameters) - self.assertTrue(benchmark._preprocess()) - return benchmark + return benchmark, benchmark._preprocess() @staticmethod def output(tags, bandwidth=100): - """Build synthetic canonical results, not recorded hardware measurements.""" - return '\n'.join(['STREAM Benchmark', 'GPU_STREAM_CONFIG ignored raw launch details'] + - ['{}\t{}\t25'.format(tag, bandwidth) for tag in sorted(tags)]) + """Build synthetic native output.""" + return '\n'.join(['STREAM Benchmark'] + ['{}\t{}\t25'.format(tag, bandwidth) for tag in sorted(tags)]) - def test_unknown_chip_with_explicit_size_uses_native_sweep(self): - """Unknown chips sweep at the requested size without tuning-mode flags.""" - benchmark = self.benchmark('--size 1048576 --num_warm_up 5 --num_loops 10 --check_data') + def test_native_sweep(self): + """Without kernel_configs, one native command sweeps all operations.""" + benchmark, ret = self.create('--size 1048576 --num_warm_up 5 --num_loops 10 --check_data') + self.assertTrue(ret) self.assertEqual(len(benchmark._commands), 1) - command = benchmark._commands[0] - for value in ['--size 1048576', '--num_warm_up 5', '--num_loops 10', '--data_type both', '--check_data']: - self.assertIn(value, command) - self.assertNotIn('--block_size', command) - self.assertNotIn('--mode', command) - self.assertEqual(len(benchmark._command_targets[0]), 8) - - def test_unknown_chip_falls_back_to_fixed_sweep(self): - """Future chip names do not inherit another chip's preset.""" - benchmark = self.benchmark(gpu_name='future_gpu') - self.assertEqual(len(benchmark._commands), 1) - self.assertIn('--size 8589934592', benchmark._commands[0]) + for value in ['--size 1048576', '--data_type double', '--operation all', '--num_warm_up 5', + '--num_loops 10', '--check_data']: + self.assertIn(value, benchmark._commands[0]) self.assertNotIn('--block_size', benchmark._commands[0]) - - def test_omitted_gpu_name_autotunes_without_loading_presets(self): - """The normal YAML without a GPU name explicitly takes the sweep path.""" - with mock.patch.object(gpu_stream.json, 'load', side_effect=AssertionError('unexpected preset read')): - benchmark = self.benchmark() - self.assertEqual(len(benchmark._commands), 1) - self.assertNotIn('--block_size', benchmark._commands[0]) - - def test_fixed_sweep_excludes_64_threads(self): - """Keep the reduced four-block by six-unroll fallback space.""" - self.assertEqual(gpu_stream._BLOCKS, [128, 256, 512, 1024]) - self.assertEqual(len(gpu_stream._BLOCKS) * len(gpu_stream._UNROLLS), 24) - - def test_named_chip_uses_only_config_parameters(self): - """A chip-name entry produces one configured command per workload.""" - benchmark = self.benchmark(gpu_name='h100') - self.assertEqual(len(benchmark._commands), 8) - for command in benchmark._commands: - self.assertIn('--size 4294967296', command) - self.assertIn('--block_size', command) - self.assertIn('--unroll', command) - self.assertNotIn('--grid', command) - self.assertNotIn('--device_info', command) - - def test_explicit_size_keeps_chip_launch_presets(self): - """A YAML size override changes every buffer without disabling presets.""" - benchmark = self.benchmark('--size 1048576', gpu_name='h100') - self.assertEqual(len(benchmark._commands), 8) - self.assertTrue(all('--size 1048576' in command and '--block_size' in command - and '--unroll' in command for command in benchmark._commands)) - - def test_legacy_fp64_parameters_remain_valid(self): - """Preserve the supplied fp64 configuration and use its explicit buffer size.""" - benchmark = self.benchmark( - '--num_warm_up 10 --num_loops 40 --size 4294967296 --data_type double', gpu_name='vr' + self.assertEqual(benchmark._command_targets, [set(_TAGS)]) + + def test_kernel_configs(self): + """Listed workloads use their launch config; unlisted workloads sweep.""" + configs = {'STREAM_COPY_double': {'block_size': 256, 'unroll': 2}, + 'STREAM_TRIAD_double': {'block_size': 512, 'unroll': 4}} + benchmark, ret = self.create('--size 1048576', configs) + self.assertTrue(ret) + self.assertEqual(benchmark._command_targets, [{tag} for tag in _TAGS]) + for command, tag in zip(benchmark._commands, _TAGS): + self.assertIn('--size 1048576', command) + self.assertIn('--operation {}'.format(tag.split('_')[1].lower()), command) + if tag in configs: + self.assertIn('--block_size {block_size} --unroll {unroll}'.format(**configs[tag]), command) + else: + self.assertNotIn('--block_size', command) + + def test_kernel_configs_from_yaml(self): + """Inline JSON in YAML survives executor argument conversion.""" + config = OmegaConf.create( + """ +parameters: + data_type: double + kernel_configs: >- + '{ + "STREAM_COPY_double": {"block_size": 256, "unroll": 2}, + "STREAM_SCALE_double": {"block_size": 256, "unroll": 2}, + "STREAM_ADD_double": {"block_size": 256, "unroll": 2}, + "STREAM_TRIAD_double": {"block_size": 256, "unroll": 2} + }' +""" ) + executor = SuperBenchExecutor.__new__(SuperBenchExecutor) + benchmark, ret = self.create(executor._SuperBenchExecutor__get_arguments(config.parameters)) + self.assertTrue(ret) self.assertEqual(len(benchmark._commands), 4) - for command in benchmark._commands: - for value in ['--size 4294967296', '--num_warm_up 10', '--num_loops 40', - '--data_type double', '--block_size', '--unroll']: - self.assertIn(value, command) - - def test_explicit_vr_key_is_supported(self): - """VR selection is a user-provided key, not a driver-name heuristic.""" - benchmark = self.benchmark(gpu_name='vr') - self.assertEqual(len(benchmark._commands), 8) - self.assertTrue(all('--block_size' in command for command in benchmark._commands)) - - def test_all_named_gpu_defaults(self): - """Resolve the three supported JSON keys without any device-name lookup.""" - for gpu_name, size in [('h100', 4294967296), ('gb300', 8589934592), ('vr', 4294967296)]: - with self.subTest(gpu_name=gpu_name): - benchmark = self.benchmark(gpu_name=gpu_name) - self.assertEqual(len(benchmark._commands), 8) - self.assertTrue(all('--size {}'.format(size) in command for command in benchmark._commands)) - - def test_partial_chip_config_sweeps_missing_operations(self): - """A new profile can be contributed incrementally.""" - profiles = {'example_gpu': {'buffer_size': 1048576, - 'kernels': {'STREAM_COPY_double': {'block_size': 128, 'unroll': 2}}}} - with mock.patch.object(gpu_stream.json, 'load', return_value=profiles): - benchmark = self.benchmark('--data_type double', gpu_name='example_gpu') - self.assertEqual(len(benchmark._commands), 4) - self.assertEqual(sum('--block_size' in command for command in benchmark._commands), 1) - self.assertTrue(all('--size 1048576' in command for command in benchmark._commands)) - - def test_profile_file_contains_no_measurement_or_validation_data(self): - """The public data file contains chip names and launch parameters only.""" - profiles = json.loads(Path(gpu_stream.__file__).with_name('gpu_stream_profiles.json').read_text()) - self.assertTrue(profiles) - self.assertTrue({'h100', 'gb300', 'vr'}.issubset(profiles)) - for chip, profile in profiles.items(): - self.assertIsInstance(chip, str) - self.assertEqual(set(profile), {'buffer_size', 'kernels'}) - self.assertIs(type(profile['buffer_size']), int) - for tag, config in profile['kernels'].items(): - self.assertEqual(set(config), {'block_size', 'unroll'}) - gpu_stream.GpuStreamBenchmark._check_config(tag, config) - - def test_bad_profile_is_an_error_not_a_fallback(self): - """Invalid matched configuration must not silently become a successful sweep.""" - for config in [ - {'block_size': True, 'unroll': 2}, - {'block_size': 64, 'unroll': 2}, - {'block_size': 96, 'unroll': 2}, - {'block_size': 128, 'unroll': 5}, - {'block_size': 128, 'unroll': 2, 'bandwidth_gbps': 123}, + self.assertTrue(all('--block_size 256 --unroll 2' in command for command in benchmark._commands)) + + def test_invalid_arguments(self): + """Invalid sizes, loops, and kernel_configs are rejected.""" + cases = ['--size 0', '--size 12', '--num_loops 0', '--num_warm_up -1'] + for value in [ + '{', '[]', '{"STREAM_COPY_half": {"block_size": 256, "unroll": 2}}', + '{"STREAM_COPY_float": {"block_size": 256, "unroll": 2}}', + '{"STREAM_COPY_double": {"block_size": 256}}', + '{"STREAM_COPY_double": {"block_size": 64, "unroll": 2}}', + '{"STREAM_COPY_double": {"block_size": 256, "unroll": 5}}', + '{"STREAM_COPY_double": {"block_size": true, "unroll": 2}}', ]: - with self.subTest(config=config): - benchmark_class, _ = BenchmarkRegistry._BenchmarkRegistry__select_benchmark('gpu-stream', Platform.CUDA) - benchmark = benchmark_class('gpu-stream', parameters='--gpu_name example_gpu') - with mock.patch.object(gpu_stream.json, 'load', - return_value={'example_gpu': {'buffer_size': 1048576, - 'kernels': {'STREAM_COPY_double': config}}}): - self.assertFalse(benchmark._preprocess()) + cases.append('--kernel_configs {}'.format(shlex.quote(value))) + for parameters in cases: + with self.subTest(parameters=parameters): + benchmark, ret = self.create(parameters) + self.assertFalse(ret) self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) self.assertEqual(benchmark._commands, []) - def test_invalid_chip_buffer_size_is_reported(self): - """A shared default must support both scalar widths.""" - for size in [0, 3, True, 2**64]: - benchmark_class, _ = BenchmarkRegistry._BenchmarkRegistry__select_benchmark('gpu-stream', Platform.CUDA) - benchmark = benchmark_class('gpu-stream', parameters='--gpu_name example_gpu') - with mock.patch.object(gpu_stream.json, 'load', - return_value={'example_gpu': {'buffer_size': size, 'kernels': {}}}): - self.assertFalse(benchmark._preprocess()) - self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) - - def test_gpu_name_is_case_insensitive(self): - """Match supplied names against the lowercase JSON keys.""" - benchmark = self.benchmark(gpu_name='H100') - self.assertEqual(benchmark._args.gpu_name, 'h100') - self.assertEqual(len(benchmark._commands), 8) - - def test_empty_gpu_name_is_rejected(self): - """Do not silently treat an empty explicit name as a preset.""" - benchmark_class, _ = BenchmarkRegistry._BenchmarkRegistry__select_benchmark('gpu-stream', Platform.CUDA) - benchmark = benchmark_class('gpu-stream', parameters='--gpu_name \"\"') - self.assertFalse(benchmark._preprocess()) - self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) - - def test_canonical_results_and_repetitions(self): - """Publish one fresh value per workload per framework repetition.""" - benchmark = self.benchmark('--size 1048576') - tags = benchmark._command_targets[0] - self.assertTrue(benchmark._process_raw_result(0, self.output(tags, 200))) - self.assertTrue(benchmark._process_raw_result(0, self.output(tags, 100))) - self.assertEqual(benchmark.result['STREAM_ADD_double_bw'], [200, 100]) - self.assertEqual(len(benchmark.result), benchmark.default_metric_count + 16) - self.assertTrue(all('_buffer_' not in key and '_block_' not in key for key in benchmark.result)) - - def test_single_float_and_scalar_tail_arguments(self): - """Keep the original single-datatype use case and scalar-aligned sizes.""" - benchmark = self.benchmark('--size 68 --data_type float') - self.assertIn('--data_type float', benchmark._commands[0]) - self.assertEqual(len(benchmark._command_targets[0]), 4) - - def test_invalid_result_never_returns_bandwidth(self): - """Reject missing, duplicate, malformed, and nonfinite canonical rows.""" - for transform in [ - lambda output: '', - lambda output: output + '\nSTREAM_COPY_double 300 25', - lambda output: output.replace('\t100\t25', '\tnan\t25'), - lambda output: output.replace('\t100\t25', '\tinf\t25'), - lambda output: output.replace('\t100\t25', '\t-1\t25'), + def test_result_parsing(self): + """Metrics come from canonical rows; launch details stay in raw output.""" + for dtype, filename in [('float', 'gpu_stream_float.log'), ('double', 'gpu_stream.log')]: + with self.subTest(dtype=dtype): + benchmark, ret = self.create('--data_type {}'.format(dtype)) + self.assertTrue(ret) + output = (Path(__file__).parents[2] / 'data' / filename).read_text() + self.assertTrue(benchmark._process_raw_result(0, output)) + rows = [line.split() for line in output.splitlines() if line.startswith('STREAM_')] + self.assertEqual(len(rows), 4) + for tag, bandwidth, ratio in rows: + self.assertEqual(benchmark.result[tag + '_bw'], [float(bandwidth)]) + self.assertEqual(benchmark.result[tag + '_ratio'], [float(ratio)]) + self.assertEqual(len(benchmark.result), benchmark.default_metric_count + 8) + + def test_invalid_result(self): + """Missing, duplicate, and non-finite rows fail parsing.""" + valid = self.output(_TAGS) + for output in [ + '', + valid + '\nSTREAM_COPY_double\t300\t25', + valid.replace('\t100\t25', '\tnan\t25'), + valid.replace('\t100\t25', '\t-1\t25'), ]: - benchmark = self.benchmark('--size 1048576 --data_type double') - self.assertFalse(benchmark._process_raw_result(0, transform(self.output(benchmark._command_targets[0])))) - self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) - self.assertNotIn('STREAM_COPY_double_bw', benchmark.result) - - def test_invalid_size_and_loop_counts(self): - """Retain the normal native input constraints.""" - benchmark_class, _ = BenchmarkRegistry._BenchmarkRegistry__select_benchmark('gpu-stream', Platform.CUDA) - for parameters in ['--size 0', '--size 12', '--num_loops 0', '--num_warm_up -1']: - benchmark = benchmark_class('gpu-stream', parameters=parameters) - self.assertFalse(benchmark._preprocess()) - self.assertEqual(benchmark.return_code, ReturnCode.INVALID_ARGUMENT) + with self.subTest(output=output): + benchmark, _ = self.create() + self.assertFalse(benchmark._process_raw_result(0, output)) + self.assertEqual(benchmark.return_code, ReturnCode.MICROBENCHMARK_RESULT_PARSING_FAILURE) + self.assertNotIn('STREAM_COPY_double_bw', benchmark.result) diff --git a/tests/data/gpu_stream.log b/tests/data/gpu_stream.log index a3dcf2b01..1b93131f9 100644 --- a/tests/data/gpu_stream.log +++ b/tests/data/gpu_stream.log @@ -1,24 +1,17 @@ STREAM Benchmark +Synthetic fixture; not hardware measurements. Buffer size(bytes): 4294967296 Number of warm up runs: 10 Number of loops: 40 Data type: double Check data: No -Device 0: "NVIDIA Graphics Device" 152 SMs(10.0) Memory: 4000MHz x 8192-bit = 8192 GB/s PEAK ECC is ON -STREAM_COPY_double_buffer_4294967296_block_128 6711.67 81.93 -STREAM_COPY_double_buffer_4294967296_block_256 6549.50 79.95 -STREAM_COPY_double_buffer_4294967296_block_512 6195.43 75.63 -STREAM_COPY_double_buffer_4294967296_block_1024 5721.52 69.84 -STREAM_SCALE_double_buffer_4294967296_block_128 6680.42 81.55 -STREAM_SCALE_double_buffer_4294967296_block_256 6515.51 79.54 -STREAM_SCALE_double_buffer_4294967296_block_512 6106.69 74.54 -STREAM_SCALE_double_buffer_4294967296_block_1024 5626.68 68.69 -STREAM_ADD_double_buffer_4294967296_block_128 7379.25 90.08 -STREAM_ADD_double_buffer_4294967296_block_256 7407.27 90.42 -STREAM_ADD_double_buffer_4294967296_block_512 7309.59 89.23 -STREAM_ADD_double_buffer_4294967296_block_1024 6788.64 82.87 -STREAM_TRIAD_double_buffer_4294967296_block_128 7378.19 90.07 -STREAM_TRIAD_double_buffer_4294967296_block_256 7414.01 90.50 -STREAM_TRIAD_double_buffer_4294967296_block_512 7295.50 89.06 -STREAM_TRIAD_double_buffer_4294967296_block_1024 6730.42 82.16 \ No newline at end of file +Device 0: "Synthetic test GPU" +GPU_STREAM_CONFIG STREAM_COPY_double 4294967296 256 2 524288 +STREAM_COPY_double 80 20 +GPU_STREAM_CONFIG STREAM_SCALE_double 4294967296 256 2 524288 +STREAM_SCALE_double 100 25 +GPU_STREAM_CONFIG STREAM_ADD_double 4294967296 256 2 524288 +STREAM_ADD_double 120 30 +GPU_STREAM_CONFIG STREAM_TRIAD_double 4294967296 256 2 524288 +STREAM_TRIAD_double 140 35 \ No newline at end of file diff --git a/tests/data/gpu_stream_float.log b/tests/data/gpu_stream_float.log index d1ab3ad1e..5aef4a1cc 100644 --- a/tests/data/gpu_stream_float.log +++ b/tests/data/gpu_stream_float.log @@ -1,24 +1,17 @@ STREAM Benchmark +Synthetic fixture; not hardware measurements. Buffer size(bytes): 4294967296 Number of warm up runs: 10 Number of loops: 40 Data type: float Check data: No -Device 0: "NVIDIA Graphics Device" 152 SMs(10.0) Memory: 4000MHz x 8192-bit = 8192 GB/s PEAK ECC is ON -STREAM_COPY_float_buffer_4294967296_block_128 6823.45 83.30 -STREAM_COPY_float_buffer_4294967296_block_256 6650.12 81.18 -STREAM_COPY_float_buffer_4294967296_block_512 6301.88 76.93 -STREAM_COPY_float_buffer_4294967296_block_1024 5812.34 70.95 -STREAM_SCALE_float_buffer_4294967296_block_128 6790.11 82.89 -STREAM_SCALE_float_buffer_4294967296_block_256 6620.33 80.81 -STREAM_SCALE_float_buffer_4294967296_block_512 6210.45 75.81 -STREAM_SCALE_float_buffer_4294967296_block_1024 5718.90 69.81 -STREAM_ADD_float_buffer_4294967296_block_128 7490.22 91.43 -STREAM_ADD_float_buffer_4294967296_block_256 7512.10 91.70 -STREAM_ADD_float_buffer_4294967296_block_512 7405.67 90.40 -STREAM_ADD_float_buffer_4294967296_block_1024 6890.33 84.11 -STREAM_TRIAD_float_buffer_4294967296_block_128 7485.55 91.38 -STREAM_TRIAD_float_buffer_4294967296_block_256 7520.88 91.81 -STREAM_TRIAD_float_buffer_4294967296_block_512 7390.12 90.21 -STREAM_TRIAD_float_buffer_4294967296_block_1024 6825.11 83.32 +Device 0: "Synthetic test GPU" +GPU_STREAM_CONFIG STREAM_COPY_float 4294967296 256 2 524288 +STREAM_COPY_float 100 25 +GPU_STREAM_CONFIG STREAM_SCALE_float 4294967296 256 2 524288 +STREAM_SCALE_float 120 30 +GPU_STREAM_CONFIG STREAM_ADD_float 4294967296 256 2 524288 +STREAM_ADD_float 140 35 +GPU_STREAM_CONFIG STREAM_TRIAD_float 4294967296 256 2 524288 +STREAM_TRIAD_float 160 40 From 8a30c3ed95432002b25cd6f3d53985b47aca6ad9 Mon Sep 17 00:00:00 2001 From: Wenqing Lan Date: Thu, 5 Nov 2026 23:24:38 +0000 Subject: [PATCH 4/5] refine logs --- .../benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu | 5 +++-- tests/data/gpu_stream.log | 8 ++++---- tests/data/gpu_stream_float.log | 8 ++++---- 3 files changed, 11 insertions(+), 10 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu index ff1000ef8..5ca41f5e5 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu @@ -15,9 +15,10 @@ #include namespace { +// grid_size counts blocks of the main kernel; each thread moves `unroll` 16-byte vectors. void PrintConfiguration(const char *record, const std::string &tag, uint64_t size, const LaunchConfig &config) { - std::cout << record << "\t" << tag << "\t" << size << "\t" << config.block_size << "\t" << config.unroll - << "\t" << (size / 16) / (config.block_size * config.unroll); + std::cout << record << "\t" << tag << "\tsize=" << size << "\tblock_size=" << config.block_size + << "\tunroll=" << config.unroll << "\tgrid_size=" << (size / 16) / (config.block_size * config.unroll); } } // namespace diff --git a/tests/data/gpu_stream.log b/tests/data/gpu_stream.log index 1b93131f9..28e380ec9 100644 --- a/tests/data/gpu_stream.log +++ b/tests/data/gpu_stream.log @@ -7,11 +7,11 @@ Data type: double Check data: No Device 0: "Synthetic test GPU" -GPU_STREAM_CONFIG STREAM_COPY_double 4294967296 256 2 524288 +GPU_STREAM_CONFIG STREAM_COPY_double size=4294967296 block_size=256 unroll=2 grid_size=524288 STREAM_COPY_double 80 20 -GPU_STREAM_CONFIG STREAM_SCALE_double 4294967296 256 2 524288 +GPU_STREAM_CONFIG STREAM_SCALE_double size=4294967296 block_size=256 unroll=2 grid_size=524288 STREAM_SCALE_double 100 25 -GPU_STREAM_CONFIG STREAM_ADD_double 4294967296 256 2 524288 +GPU_STREAM_CONFIG STREAM_ADD_double size=4294967296 block_size=256 unroll=2 grid_size=524288 STREAM_ADD_double 120 30 -GPU_STREAM_CONFIG STREAM_TRIAD_double 4294967296 256 2 524288 +GPU_STREAM_CONFIG STREAM_TRIAD_double size=4294967296 block_size=256 unroll=2 grid_size=524288 STREAM_TRIAD_double 140 35 \ No newline at end of file diff --git a/tests/data/gpu_stream_float.log b/tests/data/gpu_stream_float.log index 5aef4a1cc..76058e7bd 100644 --- a/tests/data/gpu_stream_float.log +++ b/tests/data/gpu_stream_float.log @@ -7,11 +7,11 @@ Data type: float Check data: No Device 0: "Synthetic test GPU" -GPU_STREAM_CONFIG STREAM_COPY_float 4294967296 256 2 524288 +GPU_STREAM_CONFIG STREAM_COPY_float size=4294967296 block_size=256 unroll=2 grid_size=524288 STREAM_COPY_float 100 25 -GPU_STREAM_CONFIG STREAM_SCALE_float 4294967296 256 2 524288 +GPU_STREAM_CONFIG STREAM_SCALE_float size=4294967296 block_size=256 unroll=2 grid_size=524288 STREAM_SCALE_float 120 30 -GPU_STREAM_CONFIG STREAM_ADD_float 4294967296 256 2 524288 +GPU_STREAM_CONFIG STREAM_ADD_float size=4294967296 block_size=256 unroll=2 grid_size=524288 STREAM_ADD_float 140 35 -GPU_STREAM_CONFIG STREAM_TRIAD_float 4294967296 256 2 524288 +GPU_STREAM_CONFIG STREAM_TRIAD_float size=4294967296 block_size=256 unroll=2 grid_size=524288 STREAM_TRIAD_float 160 40 From 2798e3f925daccccb4301d6251a19c5b4164a9af Mon Sep 17 00:00:00 2001 From: Wenqing Lan Date: Mon, 9 Nov 2026 23:20:01 +0000 Subject: [PATCH 5/5] fix lint --- .../benchmarks/micro_benchmarks/gpu_stream.py | 58 ++++++++++++++----- .../micro_benchmarks/gpu_stream/gpu_stream.cu | 23 ++++---- .../gpu_stream/gpu_stream_kernels.hpp | 25 ++++---- .../gpu_stream/gpu_stream_utils.cpp | 4 +- .../gpu_stream/gpu_stream_utils.hpp | 4 +- .../micro_benchmarks/test_gpu_stream.py | 22 +++++-- 6 files changed, 85 insertions(+), 51 deletions(-) diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream.py b/superbench/benchmarks/micro_benchmarks/gpu_stream.py index 5f21333d0..1f137d670 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream.py +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream.py @@ -13,7 +13,6 @@ from superbench.benchmarks import BenchmarkRegistry, Platform, ReturnCode from superbench.benchmarks.micro_benchmarks import MicroBenchmarkWithInvoke - _OPERATIONS = ['copy', 'scale', 'add', 'triad'] _BLOCKS = [128, 256, 512, 1024] _UNROLLS = [1, 2, 3, 4, 6, 8] @@ -23,7 +22,6 @@ class GpuStreamBenchmark(MicroBenchmarkWithInvoke): """Report one bandwidth per operation and datatype.""" - def __init__(self, name, parameters=''): """Initialize the native benchmark.""" super().__init__(name, parameters) @@ -33,16 +31,31 @@ def __init__(self, name, parameters=''): def add_parser_arguments(self): """Retain the normal benchmark arguments; search dimensions are fixed.""" super().add_parser_arguments() - self._parser.add_argument('--kernel_configs', type=str, default=None, - help='JSON mapping of workload tags to block_size/unroll. Omit to autotune.') - self._parser.add_argument('--size', type=int, default=_DEFAULT_SIZE, - help='Bytes per array, independent of launch overrides (default: 8 GiB).') + self._parser.add_argument( + '--kernel_configs', + type=str, + default=None, + help='JSON mapping of workload tags to block_size/unroll. Omit to autotune.' + ) + self._parser.add_argument( + '--size', + type=int, + default=_DEFAULT_SIZE, + help='Bytes per array, independent of launch overrides (default: 8 GiB).' + ) self._parser.add_argument('--num_warm_up', type=int, default=20) self._parser.add_argument('--num_loops', type=int, default=100) - self._parser.add_argument('--data_type', choices=['float', 'double'], default='double', - help='Element type; use one benchmark entry per data type.') - self._parser.add_argument('--check_data', action='store_true', - help='Validate output. Requires 6x buffer size in host memory; use small sizes.') + self._parser.add_argument( + '--data_type', + choices=['float', 'double'], + default='double', + help='Element type; use one benchmark entry per data type.' + ) + self._parser.add_argument( + '--check_data', + action='store_true', + help='Validate output. Requires 6x buffer size in host memory; use small sizes.' + ) @staticmethod def _check_config(tag, config): @@ -71,8 +84,17 @@ def _kernel_configs(self): def _command(self, dtype, operation, size, config=None): """Use singleton native parameters for overrides, or the native fixed sweep.""" parts = [ - shlex.quote(self.__bin_path), '--size', str(size), '--data_type', dtype, '--operation', operation, - '--num_warm_up', str(self._args.num_warm_up), '--num_loops', str(self._args.num_loops), + shlex.quote(self.__bin_path), + '--size', + str(size), + '--data_type', + dtype, + '--operation', + operation, + '--num_warm_up', + str(self._args.num_warm_up), + '--num_loops', + str(self._args.num_loops), ] if config: parts.extend(['--block_size', str(config['block_size']), '--unroll', str(config['unroll'])]) @@ -87,8 +109,10 @@ def _preprocess(self): self.__bin_path = os.path.join(self._args.bin_dir, self._bin_name) self._commands, self._command_targets = [], [] try: - if (self._args.num_warm_up < 0 or self._args.num_loops <= 0 or - self._args.num_warm_up + self._args.num_loops >= 2**64): + if ( + self._args.num_warm_up < 0 or self._args.num_loops <= 0 + or self._args.num_warm_up + self._args.num_loops >= 2**64 + ): raise ValueError('Invalid warm-up/loop counts') width = 4 if self._args.data_type == 'float' else 8 if not 0 < self._args.size < 2**64 or self._args.size % width: @@ -126,8 +150,10 @@ def _process_raw_result(self, cmd_idx, raw_output): raise ValueError('Invalid or duplicate canonical result') tag, bandwidth, ratio = fields bandwidth, ratio = float(bandwidth), float(ratio) - if (not math.isfinite(bandwidth) or bandwidth <= 0 or not math.isfinite(ratio) or - (ratio < 0 and ratio != -1)): + if ( + not math.isfinite(bandwidth) or bandwidth <= 0 or not math.isfinite(ratio) + or (ratio < 0 and ratio != -1) + ): raise ValueError('Invalid bandwidth/efficiency for {}'.format(tag)) results[tag] = bandwidth, ratio if set(results) != self._command_targets[cmd_idx]: diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu index 5ca41f5e5..d81c3e1ad 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream.cu @@ -498,23 +498,23 @@ int GpuStream::RunStreamKernel(std::unique_ptr> &args, Kernel kerne switch (kernel) { case Kernel::kCopy: - cuda_err = stream_kernels::Launch( - output, first, second, count, config, args->sub.stream, max_grid_x); + cuda_err = stream_kernels::Launch(output, first, second, count, config, args->sub.stream, + max_grid_x); args->sub.kernel_name = "COPY"; break; case Kernel::kScale: - cuda_err = stream_kernels::Launch( - output, first, second, count, config, args->sub.stream, max_grid_x); + cuda_err = stream_kernels::Launch(output, first, second, count, config, args->sub.stream, + max_grid_x); args->sub.kernel_name = "SCALE"; break; case Kernel::kAdd: - cuda_err = stream_kernels::Launch( - output, first, second, count, config, args->sub.stream, max_grid_x); + cuda_err = stream_kernels::Launch(output, first, second, count, config, args->sub.stream, + max_grid_x); args->sub.kernel_name = "ADD"; break; case Kernel::kTriad: - cuda_err = stream_kernels::Launch( - output, first, second, count, config, args->sub.stream, max_grid_x); + cuda_err = stream_kernels::Launch(output, first, second, count, config, args->sub.stream, + max_grid_x); args->sub.kernel_name = "TRIAD"; break; default: @@ -665,8 +665,8 @@ int GpuStream::RunStream(std::unique_ptr> &args, const std::string Destroy(args); return ret; } - const double bandwidth = static_cast(args->size) * args->num_loops * - kBufferBwMultipliers[index] / elapsed_ms / 1e6; + const double bandwidth = + static_cast(args->size) * args->num_loops * kBufferBwMultipliers[index] / elapsed_ms / 1e6; if (!std::isfinite(bandwidth) || bandwidth <= 0) { std::cerr << "Invalid bandwidth for " << tag << std::endl; Destroy(args); @@ -693,7 +693,8 @@ int GpuStream::RunStream(std::unique_ptr> &args, const std::string const auto &winner = best[static_cast(kernel)]; const std::string tag = "STREAM_" + KernelToString(static_cast(kernel)) + "_" + data_type; PrintConfiguration("GPU_STREAM_CONFIG", tag, size, winner.config); - std::cout << "\n" << tag << "\t" << std::defaultfloat << std::setprecision(9) << winner.bandwidth << "\t" + std::cout << "\n" + << tag << "\t" << std::defaultfloat << std::setprecision(9) << winner.bandwidth << "\t" << (peak_bw > 0 ? winner.bandwidth / peak_bw * 100 : -1) << std::endl; } return 0; diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp index 4138b21cd..fdec61ff1 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_kernels.hpp @@ -3,21 +3,17 @@ #pragma once +#include #include #include -#include #include #include #include "gpu_stream_utils.hpp" template struct VectorType; -template <> struct VectorType { - using type = double2; -}; -template <> struct VectorType { - using type = float4; -}; +template <> struct VectorType { using type = double2; }; +template <> struct VectorType { using type = float4; }; template using VecT = typename VectorType::type; #ifdef __CUDACC__ @@ -52,7 +48,7 @@ template __device__ __forceinline__ VecT TransformPac // Bounds checks and scalar remainders stay out of the complete-tile kernel. template __global__ __launch_bounds__(BLOCK) void BulkKernel(VecT *__restrict__ output, const VecT *__restrict__ a, - const VecT *__restrict__ b) { + const VecT *__restrict__ b) { const Index base = static_cast(blockIdx.x) * (BLOCK * UNROLL) + threadIdx.x; VecT first[UNROLL]; VecT second[UNROLL]; @@ -76,8 +72,8 @@ __global__ __launch_bounds__(BLOCK) void BulkKernel(VecT *__restrict__ output } template -__global__ void TailKernel(T *__restrict__ output, const T *__restrict__ a, const T *__restrict__ b, - uint64_t begin, uint64_t count) { +__global__ void TailKernel(T *__restrict__ output, const T *__restrict__ a, const T *__restrict__ b, uint64_t begin, + uint64_t count) { const uint64_t i = begin + static_cast(blockIdx.x) * blockDim.x + threadIdx.x; if (i < count) { T right = 0; @@ -88,8 +84,7 @@ __global__ void TailKernel(T *__restrict__ output, const T *__restrict__ a, cons } } -template -__global__ void InitializeData(T *a, T *b, uint64_t count) { +template __global__ void InitializeData(T *a, T *b, uint64_t count) { for (uint64_t i = static_cast(blockIdx.x) * blockDim.x + threadIdx.x; i < count; i += static_cast(gridDim.x) * blockDim.x) { a[i] = static_cast(i % stream_config::kUInt8Mod); @@ -140,7 +135,7 @@ cudaError_t LaunchUnroll(T *output, const T *a, const T *b, uint64_t count, cuda template cudaError_t LaunchBlock(T *output, const T *a, const T *b, uint64_t count, cudaStream_t stream, int max_grid_x, - const LaunchConfig &config) { + const LaunchConfig &config) { switch (config.unroll) { case 1: return LaunchUnroll(output, a, b, count, stream, max_grid_x); @@ -160,8 +155,8 @@ cudaError_t LaunchBlock(T *output, const T *a, const T *b, uint64_t count, cudaS } template -cudaError_t Launch(T *output, const T *a, const T *b, uint64_t count, const LaunchConfig &config, - cudaStream_t stream, int max_grid_x) { +cudaError_t Launch(T *output, const T *a, const T *b, uint64_t count, const LaunchConfig &config, cudaStream_t stream, + int max_grid_x) { switch (config.block_size) { case 128: return LaunchBlock(output, a, b, count, stream, max_grid_x, config); diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp index b6f70b946..a6a71de5e 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.cpp @@ -109,8 +109,8 @@ int ParseOpts(int argc, char **argv, Opts *opts) { } const uint64_t element_size = opts->data_type == "float" ? sizeof(float) : sizeof(double); if (optind != argc || opts->size == 0 || opts->size % element_size != 0) { - std::cerr << "Size must be a positive multiple of " << element_size << " bytes; positional arguments are invalid" - << std::endl; + std::cerr << "Size must be a positive multiple of " << element_size + << " bytes; positional arguments are invalid" << std::endl; return -1; } if (opts->num_loops == 0 || opts->num_warm_up > std::numeric_limits::max() - opts->num_loops) { diff --git a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp index eb37776b8..3ab713d45 100644 --- a/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp +++ b/superbench/benchmarks/micro_benchmarks/gpu_stream/gpu_stream_utils.hpp @@ -31,8 +31,8 @@ unsigned long long getCurrentTimestampInMicroseconds(); namespace stream_config { constexpr std::array kThreadsPerBlock = {128, 256, 512, 1024}; constexpr std::array kUnrollFactors = {1, 2, 3, 4, 6, 8}; -constexpr uint64_t kDefaultBufferSizeInBytes = 8589934592; // 8 GiB per array -constexpr int kNumBuffers = 3; // Number of buffers for triad, add kernel +constexpr uint64_t kDefaultBufferSizeInBytes = 8589934592; // 8 GiB per array +constexpr int kNumBuffers = 3; // Number of buffers for triad, add kernel constexpr int kNumValidationBuffers = 4; // Number of validation buffers, one for each kernel constexpr int kUInt8Mod = 256; // Modulo for unsigned long data type constexpr std::array kBufferBwMultipliers = {2, 2, 3, 3}; // Buffer multiplier for triad, add kernel diff --git a/tests/benchmarks/micro_benchmarks/test_gpu_stream.py b/tests/benchmarks/micro_benchmarks/test_gpu_stream.py index c5fb7f683..006899d36 100644 --- a/tests/benchmarks/micro_benchmarks/test_gpu_stream.py +++ b/tests/benchmarks/micro_benchmarks/test_gpu_stream.py @@ -46,16 +46,26 @@ def test_native_sweep(self): benchmark, ret = self.create('--size 1048576 --num_warm_up 5 --num_loops 10 --check_data') self.assertTrue(ret) self.assertEqual(len(benchmark._commands), 1) - for value in ['--size 1048576', '--data_type double', '--operation all', '--num_warm_up 5', - '--num_loops 10', '--check_data']: + for value in [ + '--size 1048576', '--data_type double', '--operation all', '--num_warm_up 5', '--num_loops 10', + '--check_data' + ]: self.assertIn(value, benchmark._commands[0]) self.assertNotIn('--block_size', benchmark._commands[0]) self.assertEqual(benchmark._command_targets, [set(_TAGS)]) def test_kernel_configs(self): """Listed workloads use their launch config; unlisted workloads sweep.""" - configs = {'STREAM_COPY_double': {'block_size': 256, 'unroll': 2}, - 'STREAM_TRIAD_double': {'block_size': 512, 'unroll': 4}} + configs = { + 'STREAM_COPY_double': { + 'block_size': 256, + 'unroll': 2 + }, + 'STREAM_TRIAD_double': { + 'block_size': 512, + 'unroll': 4 + } + } benchmark, ret = self.create('--size 1048576', configs) self.assertTrue(ret) self.assertEqual(benchmark._command_targets, [{tag} for tag in _TAGS]) @@ -92,7 +102,9 @@ def test_invalid_arguments(self): """Invalid sizes, loops, and kernel_configs are rejected.""" cases = ['--size 0', '--size 12', '--num_loops 0', '--num_warm_up -1'] for value in [ - '{', '[]', '{"STREAM_COPY_half": {"block_size": 256, "unroll": 2}}', + '{', + '[]', + '{"STREAM_COPY_half": {"block_size": 256, "unroll": 2}}', '{"STREAM_COPY_float": {"block_size": 256, "unroll": 2}}', '{"STREAM_COPY_double": {"block_size": 256}}', '{"STREAM_COPY_double": {"block_size": 64, "unroll": 2}}',