// boundary.cu: what one kernel boundary costs, in five launch modes. // For content/standalone/04-gpu-for-inference/04-decode-megakernels (written 2026-10-29, run 2026-10-30 in GX10 session B; // built and run by run.sh in this folder; results/). // // A "chain" is N dependent phases that together read W bytes from DRAM (W/N each), like the // N kernels of one decode layer reading that layer's weights. The same chain runs as: // stream N kernels launched from the CPU, one after another, on one stream // graph the same N kernels captured once in a CUDA graph and replayed // pdl_wait graph + programmatic dependent launch; each kernel waits for its predecessor first // pdl_load graph + PDL; each kernel reads its own slice first, then waits (what the fused paths do) // persistent one cooperative kernel; the N phases are separated by grid.sync() // Every mode uses the same grid (all SMs, the persistent kernel's occupancy), so the only difference is // what happens between phases. Per-boundary cost = slope of chain time against N at fixed W. // // Sweep: W = 0, 4, 32, 256 MiB per chain, read from a 1 GiB ring whose window moves every chain (so even 4 MiB // comes from DRAM, not the 24 MiB L2); N = 1..256; plus W = 0 on a 1-block grid (pure launch path). Each point: // 5 warm-up chains, then the median of 7 trials of 200 / 50 / 10 chains (by W), timed with CUDA events. // // nvcc -O3 -std=c++17 -arch=sm_121 -lineinfo boundary.cu -o boundary // ./boundary > boundary.csv # full sweep // ./boundary --only graph 33554432 16 > one.csv # one point (for nsys) #include #include #include #include #include #include #include #include namespace cg = cooperative_groups; #define CHECK(call) \ do { \ cudaError_t err_ = (call); \ if (err_ != cudaSuccess) { \ std::fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, \ cudaGetErrorString(err_)); \ std::exit(1); \ } \ } while (0) constexpr int kBlock = 256; constexpr size_t kRingBytes = size_t(1) << 30; // 1 GiB, far above the L2 (24 MiB on GB10) struct Args { const uint4* ring; // the "weights": a 1 GiB ring read 16 bytes at a time size_t ring_vec; // ring size in uint4 size_t slice_vec; // uint4 per phase (W / N / 16) int n; // phases per chain float* act; // act[k + 1] = act[k] + 1: the data dependency between phases unsigned* sink; // written only if an impossible value appears, so loads stay live unsigned long long* iter; // chain counter: moves the read window so every chain reads DRAM, not L2 }; // Reads this phase's slice with the whole grid. Returns an XOR of everything read. __device__ __forceinline__ unsigned read_slice(const Args& a, int k) { if (a.slice_vec == 0) return 0u; const unsigned long long it = *reinterpret_cast(a.iter); const size_t span = a.slice_vec * size_t(a.n); const size_t base = (size_t(it) * span + size_t(k) * a.slice_vec) % (a.ring_vec - a.slice_vec); unsigned acc = 0u; for (size_t i = size_t(blockIdx.x) * blockDim.x + threadIdx.x; i < a.slice_vec; i += size_t(gridDim.x) * blockDim.x) { const uint4 v = __ldcg(a.ring + base + i); // L2 only, like a streaming weight read acc ^= v.x ^ v.y ^ v.z ^ v.w; } return acc; } // One thread passes the dependency on; the last phase also advances the chain counter. // (Other blocks of the last phase may already see the new counter: they then read another // fresh window, which changes nothing for the timing.) __device__ __forceinline__ void hand_on(const Args& a, int k, unsigned acc) { if (acc == 0xdeadbeefu) a.sink[blockIdx.x] = acc; if (blockIdx.x == 0 && threadIdx.x == 0) { a.act[k + 1] = a.act[k] + 1.0f; if (k == a.n - 1) atomicAdd(a.iter, 1ull); } } // Modes stream and graph: an ordinary kernel. Stream order is the dependency. __global__ void phase_plain(Args a, int k) { const unsigned acc = read_slice(a, k); hand_on(a, k, acc); } // Mode pdl_wait: wait for the predecessor before anything else (hides only the launch). __global__ void phase_pdl_wait(Args a, int k) { cudaGridDependencySynchronize(); const unsigned acc = read_slice(a, k); cudaTriggerProgrammaticLaunchCompletion(); hand_on(a, k, acc); } // Mode pdl_load: read this phase's weights first (they do not depend on the predecessor), // let the next kernel launch, then wait for the predecessor's output before using it. __global__ void phase_pdl_load(Args a, int k) { const unsigned acc = read_slice(a, k); cudaTriggerProgrammaticLaunchCompletion(); cudaGridDependencySynchronize(); hand_on(a, k, acc); } // Mode persistent: one launch, phases separated by a grid-wide barrier. __global__ void chain_persistent(Args a) { cg::grid_group grid = cg::this_grid(); for (int k = 0; k < a.n; ++k) { const unsigned acc = read_slice(a, k); hand_on(a, k, acc); grid.sync(); } } enum class Mode { Stream, Graph, PdlWait, PdlLoad, Persistent }; static const char* kNames[] = {"stream", "graph", "pdl_wait", "pdl_load", "persistent"}; struct Bench { cudaStream_t s; int grid; Args a; }; static void launch_chain_stream(Bench& b, Mode m) { for (int k = 0; k < b.a.n; ++k) { if (m == Mode::Stream || m == Mode::Graph) { phase_plain<<>>(b.a, k); } else { cudaLaunchConfig_t cfg = {}; cfg.gridDim = dim3(b.grid); cfg.blockDim = dim3(kBlock); cfg.stream = b.s; cudaLaunchAttribute attr[1]; attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; attr[0].val.programmaticStreamSerializationAllowed = 1; cfg.attrs = attr; cfg.numAttrs = 1; if (m == Mode::PdlWait) CHECK(cudaLaunchKernelEx(&cfg, phase_pdl_wait, b.a, k)); else CHECK(cudaLaunchKernelEx(&cfg, phase_pdl_load, b.a, k)); } } } static void launch_persistent(Bench& b) { void* params[] = {&b.a}; CHECK(cudaLaunchCooperativeKernel((void*)chain_persistent, dim3(b.grid), dim3(kBlock), params, 0, b.s)); } // Microseconds per chain: median of 7 trials of `reps` chains each, timed with CUDA events. static double time_chain(Bench& b, Mode m, int reps) { cudaGraphExec_t exec = nullptr; if (m == Mode::Graph || m == Mode::PdlWait || m == Mode::PdlLoad) { cudaGraph_t graph; CHECK(cudaStreamBeginCapture(b.s, cudaStreamCaptureModeGlobal)); launch_chain_stream(b, m); CHECK(cudaStreamEndCapture(b.s, &graph)); CHECK(cudaGraphInstantiate(&exec, graph, 0)); CHECK(cudaGraphDestroy(graph)); } auto one = [&]() { if (exec) CHECK(cudaGraphLaunch(exec, b.s)); else if (m == Mode::Persistent) launch_persistent(b); else launch_chain_stream(b, m); }; for (int w = 0; w < 5; ++w) one(); // warm-up CHECK(cudaStreamSynchronize(b.s)); cudaEvent_t t0, t1; CHECK(cudaEventCreate(&t0)); CHECK(cudaEventCreate(&t1)); std::vector trials; for (int t = 0; t < 7; ++t) { CHECK(cudaEventRecord(t0, b.s)); for (int r = 0; r < reps; ++r) one(); CHECK(cudaEventRecord(t1, b.s)); CHECK(cudaEventSynchronize(t1)); float ms = 0; CHECK(cudaEventElapsedTime(&ms, t0, t1)); trials.push_back(1000.0 * ms / reps); } CHECK(cudaGetLastError()); if (exec) CHECK(cudaGraphExecDestroy(exec)); CHECK(cudaEventDestroy(t0)); CHECK(cudaEventDestroy(t1)); std::sort(trials.begin(), trials.end()); return trials[trials.size() / 2]; } int main(int argc, char** argv) { int dev = 0; CHECK(cudaSetDevice(dev)); cudaDeviceProp prop; CHECK(cudaGetDeviceProperties(&prop, dev)); int coop = 0; CHECK(cudaDeviceGetAttribute(&coop, cudaDevAttrCooperativeLaunch, dev)); if (!coop) { std::fprintf(stderr, "no cooperative launch on this device\n"); return 1; } // One grid for every mode: as many blocks as can be co-resident (the persistent kernel's limit). int per_sm = 0; CHECK(cudaOccupancyMaxActiveBlocksPerMultiprocessor(&per_sm, chain_persistent, kBlock, 0)); const int full_grid = prop.multiProcessorCount * per_sm; Bench b; CHECK(cudaStreamCreateWithFlags(&b.s, cudaStreamNonBlocking)); uint4* ring; CHECK(cudaMalloc(&ring, kRingBytes)); CHECK(cudaMemset(ring, 1, kRingBytes)); float* act; CHECK(cudaMalloc(&act, sizeof(float) * 1025)); CHECK(cudaMemset(act, 0, sizeof(float) * 1025)); unsigned* sink; CHECK(cudaMalloc(&sink, sizeof(unsigned) * full_grid)); unsigned long long* iter; CHECK(cudaMalloc(&iter, sizeof(unsigned long long))); CHECK(cudaMemset(iter, 0, sizeof(unsigned long long))); b.a = Args{ring, kRingBytes / 16, 0, 1, act, sink, iter}; std::printf("# %s, %d SMs, %d blocks x %d threads per grid, cc %d.%d\n", prop.name, prop.multiProcessorCount, full_grid, kBlock, prop.major, prop.minor); std::printf("mode,grid,W_bytes,N,us_per_chain,us_per_phase,GBps\n"); std::vector modes = {Mode::Stream, Mode::Graph, Mode::PdlWait, Mode::PdlLoad, Mode::Persistent}; std::vector sizes = {0, size_t(4) << 20, size_t(32) << 20, size_t(256) << 20}; std::vector ns = {1, 2, 4, 8, 16, 32, 64, 128, 256}; std::vector grids = {full_grid}; if (argc == 5 && std::strcmp(argv[1], "--only") == 0) { // one point, for nsys const std::string want = argv[2]; modes.clear(); for (int i = 0; i < 5; ++i) if (want == kNames[i]) modes.push_back(Mode(i)); if (modes.empty()) { std::fprintf(stderr, "unknown mode %s\n", argv[2]); return 1; } sizes = {size_t(std::atoll(argv[3]))}; ns = {std::atoi(argv[4])}; } else { grids.push_back(1); // pure launch path: one block, nothing to drain (W = 0 only) } for (int g : grids) { b.grid = g; for (size_t W : sizes) { if (g == 1 && W != 0) continue; for (int n : ns) { b.a.n = n; b.a.slice_vec = W / 16 / size_t(n); const int reps = W >= (size_t(256) << 20) ? 10 : W >= (size_t(32) << 20) ? 50 : 200; for (Mode m : modes) { const double us = time_chain(b, m, reps); const double gbps = W ? double(W) / (us * 1e-6) / 1e9 : 0.0; std::printf("%s,%d,%zu,%d,%.3f,%.3f,%.1f\n", kNames[int(m)], g, W, n, us, us / n, gbps); std::fflush(stdout); } } } } CHECK(cudaFree(ring)); CHECK(cudaFree(act)); CHECK(cudaFree(sink)); CHECK(cudaFree(iter)); return 0; }