okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Olav Lindekleivgenerate: warm CUDA callbacks before host-core pinning (opt-in)c08fd9026

main
2.2 KiB67 linesraw
1// Linux/x86 CUDA reproducer for #1975. Run "lazy" and "warm" as separate processes.
2// See bench/results/2026-10-11-rtx-5090-callback-affinity/README.md for the build command.
3#include <cuda_runtime_api.h>
4#include <sched.h>
5#include <unistd.h>
6
7#include <algorithm>
8#include <atomic>
9#include <chrono>
10#include <cstdio>
11#include <cstdlib>
12#include <cstring>
13#include <vector>
14
15struct State {
16    std::atomic<bool> done{false};
17    cpu_set_t mask{};
18};
19
20static void callback(void* p) {
21    auto* s = (State*) p;
22    sched_getaffinity(0, sizeof s->mask, &s->mask);
23    s->done.store(true, std::memory_order_release);
24}
25
26static void check(cudaError_t e) {
27    if (e != cudaSuccess) {
28        std::fprintf(stderr, "%s\n", cudaGetErrorString(e));
29        std::exit(1);
30    }
31}
32
33int main(int argc, char** argv) {
34    const bool warm = argc > 1 && std::strcmp(argv[1], "warm") == 0;
35    cudaStream_t stream;
36    check(cudaStreamCreateWithFlags(&stream, cudaStreamNonBlocking));
37    State state;
38    if (warm) {
39        check(cudaLaunchHostFunc(stream, callback, &state));
40        check(cudaStreamSynchronize(stream));
41    }
42    cpu_set_t host;
43    CPU_ZERO(&host);
44    CPU_SET(0, &host);
45    if (sched_setaffinity(0, sizeof host, &host) != 0) {
46        std::perror("sched_setaffinity");
47        return 1;
48    }
49    std::vector<double> times;
50    for (int i = 0; i < 200; ++i) {
51        state.done.store(false, std::memory_order_release);
52        const auto start = std::chrono::steady_clock::now();
53        check(cudaLaunchHostFunc(stream, callback, &state));
54        while (!state.done.load(std::memory_order_acquire)) {
55            asm volatile("pause");
56            if (std::chrono::steady_clock::now() - start > std::chrono::seconds(5)) return 2;
57        }
58        times.push_back(std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now() - start).count());
59    }
60    std::sort(times.begin(), times.end());
61    std::printf("%s: callback affinity:", warm ? "before pin warm-up" : "after pin lazy creation");
62    for (int i = 0; i < CPU_SETSIZE; ++i)
63        if (CPU_ISSET(i, &state.mask)) std::printf(" %d", i);
64    std::printf("; median %.2f us, p95 %.2f us\n", times[100], times[190]);
65    check(cudaStreamSynchronize(stream));
66    check(cudaStreamDestroy(stream));
67}