Initial RPS CUDA implementation

This commit is contained in:
Skeleton bootstrap 2026-11-26 09:07:21 +03:00
commit 8d583036d0
33 changed files with 2968 additions and 0 deletions

271
server/gpu.cu Normal file
View file

@ -0,0 +1,271 @@
#include "config.hpp"
#include "gpu.hpp"
#include <algorithm>
#include <array>
#include <cmath>
#include <cstdio>
#include <cuda_runtime.h>
static void check(cudaError_t s) {
if (s != cudaSuccess)
throw std::runtime_error(cudaGetErrorString(s));
}
struct Buffer {
u32 *ptr = nullptr;
void alloc(size_t n) { check(cudaMalloc(&ptr, n)); }
~Buffer() { cudaFree(ptr); }
};
struct Event {
cudaEvent_t e;
Event() { check(cudaEventCreate(&e)); }
~Event() { cudaEventDestroy(e); }
void record() { check(cudaEventRecord(e)); }
void wait() { check(cudaEventSynchronize(e)); }
};
__device__ u32 mix(u32 v) {
v ^= v >> 16;
v *= 0x7FEB352Du;
v ^= v >> 15;
v *= 0x846CA68Bu;
return v ^ (v >> 16);
}
__global__ void init(u32 *a, u32 *b, u32 count, u64 seed) {
u32 i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= count)
return;
u32 l = seed, h = seed >> 32;
a[i] = mix(l ^ i ^ (h * 0x9E3779B9u) ^ 0xA341316Cu);
b[i] = mix(h ^ i ^ (l * 0x85EBCA6Bu) ^ 0xC8013EA4u);
}
template <unsigned LUT>
__device__ __forceinline__ u32 lop(u32 a, u32 b, u32 c) {
u32 v;
asm("lop3.b32 %0,%1,%2,%3,%4;" : "=r"(v) : "r"(a), "r"(b), "r"(c), "n"(LUT));
return v;
}
__device__ u32 left(u32 prev, u32 c) {
u32 v;
asm("shf.l.wrap.b32 %0,%1,%2,1;" : "=r"(v) : "r"(prev), "r"(c));
return v;
}
__device__ u32 right(u32 c, u32 next) {
u32 v;
asm("shf.r.wrap.b32 %0,%1,%2,1;" : "=r"(v) : "r"(c), "r"(next));
return v;
}
struct Masks {
u32 r = 0, p = 0, s = 0;
__device__ void add(u32 a, u32 b) {
r = lop<0xF4>(r, a, b);
p = lop<0xF2>(p, a, b);
s = lop<0xF8>(s, a, b);
}
};
template <int N, unsigned LA, unsigned LB>
__global__ void stepKernel(const u32 *low, const u32 *high, u32 *dstA,
u32 *dstB, u32 pitch, u32 height) {
u32 x = blockIdx.x * 32 + threadIdx.x, y = blockIdx.y * 8 + threadIdx.y;
u32 prev = x ? x - 1 : pitch - 1, next = x + 1 == pitch ? 0 : x + 1;
u32 i = y * pitch + x, a = low[i], b = high[i];
Masks m;
#pragma unroll
for (int dy = -1; dy <= 1; ++dy) {
u32 row = dy < 0 ? (y ? y - 1 : height - 1)
: dy > 0 ? (y + 1 == height ? 0 : y + 1)
: y;
u32 base = row * pitch, ca = low[base + x], cb = high[base + x];
if (dy)
m.add(ca, cb);
if (N == 8 || !dy) {
m.add(left(low[base + prev], ca), left(high[base + prev], cb));
m.add(right(ca, low[base + next]), right(cb, high[base + next]));
}
}
u32 w = lop<0xca>(a, lop<0xca>(b, m.r, m.p), m.s), e = lop<0x03>(a, b, w);
dstA[i] = lop<0xf8>(lop<0xd8>(a, b, w), e, lop<LA>(m.r, m.p, m.s));
dstB[i] = lop<0xf8>(lop<0x6c>(a, b, w), e, lop<LB>(m.r, m.p, m.s));
}
__global__ void aggregate(const u32 *low, const u32 *high, u32 *out, u32 pitch,
u32 rx, u32 ry, u32 aw, u32 count, u32 k) {
u32 i = blockIdx.x * blockDim.x + threadIdx.x;
if (i >= count)
return;
u32 x = rx + i % aw * k, y = ry + i / aw * k,
mask = ((1u << k) - 1) << (x % 32);
u32 r = 0, p = 0, s = 0;
for (u32 j = 0; j < k; ++j) {
u32 off = (y + j) * pitch + x / 32, a = low[off] & mask,
b = high[off] & mask;
r += __popc(a & ~b);
p += __popc(~a & b);
s += __popc(a & b);
}
u32 area = k * k, red = (230 * r + 70 * p + 80 * s + area / 2) / area;
u32 green = (70 * r + 150 * p + 210 * s + area / 2) / area,
blue = (70 * r + 230 * p + 120 * s + area / 2) / area;
out[i] = 0xff000000 | (red << 16) | (green << 8) | blue;
}
__global__ void compare(const u32 *a, const u32 *b, u32 n, u32 *flag) {
u32 i = blockIdx.x * blockDim.x + threadIdx.x;
if (i < n && a[i] != b[i])
atomicExch(flag, 1u);
}
using Kernel = void (*)(const u32 *, const u32 *, u32 *, u32 *, u32, u32);
template <int N> Kernel select(int p) {
static Kernel kernels[] = {
stepKernel<N, 0xf2, 0x0e>, stepKernel<N, 0xfa, 0x0e>,
stepKernel<N, 0x32, 0xce>, stepKernel<N, 0x32, 0xee>,
stepKernel<N, 0xfa, 0xae>, stepKernel<N, 0xba, 0xee>};
return kernels[p];
}
struct GPU::Impl {
Config c;
Kernel kernel;
Buffer low[2], high[2], imgs[3], flag;
unsigned char *host = nullptr;
Event begin, aggregated, copying, ready;
u64 aggNs = 0, copyNs = 0;
int src = 0, ref = 0, work = 1, flight = 2;
Impl(Config cfg, int p)
: c(cfg), kernel(c.n == 4 ? select<4>(p) : select<8>(p)) {}
~Impl() {
if (host)
cudaFreeHost(host);
}
};
GPU::GPU(const Config &c, int priority, bool snapshots)
: p(std::make_unique<Impl>(c, priority)) {
cudaDeviceProp prop;
check(cudaGetDeviceProperties(&prop, 0));
require(c.w / 1024 <= u32(prop.maxGridSize[0]) &&
c.h / 8 <= u32(prop.maxGridSize[1]),
"device grid limit");
u64 words = u64(c.w) * c.h / 32, bytes = words * 4;
size_t free, total;
check(cudaMemGetInfo(&free, &total));
require(bytes * 4 + (snapshots ? 3 * c.bytes() + 4 : 0) <= free,
"insufficient free VRAM");
for (int i = 0; i < 2; ++i) {
p->low[i].alloc(bytes);
p->high[i].alloc(bytes);
}
if (snapshots) {
for (auto &img : p->imgs)
img.alloc(c.bytes());
p->flag.alloc(4);
check(cudaHostAlloc(&p->host, c.bytes(), cudaHostAllocDefault));
}
init<<<(words + 255) / 256, 256>>>(p->low[0].ptr, p->high[0].ptr, words,
c.seed);
check(cudaGetLastError());
sync();
}
GPU::~GPU() = default;
void GPU::sync() { check(cudaDeviceSynchronize()); }
void GPU::step() {
auto &c = p->c;
int src = p->src, dst = 1 - src;
auto kernel = p->kernel;
kernel<<<dim3(c.w / 1024, c.h / 8), dim3(32, 8)>>>(
p->low[src].ptr, p->high[src].ptr, p->low[dst].ptr, p->high[dst].ptr,
c.w / 32, c.h);
check(cudaGetLastError());
p->src = dst;
}
bool GPU::snapshot(bool mandatory) {
auto &c = p->c;
auto out = p->imgs[p->work].ptr;
u32 n = c.aw() * c.ah(), blocks = (n + 255) / 256;
p->begin.record();
aggregate<<<blocks, 256>>>(p->low[p->src].ptr, p->high[p->src].ptr, out,
c.w / 32, c.x, c.y, c.aw(), n, c.k);
check(cudaGetLastError());
p->aggregated.record();
if (!mandatory) {
u32 flag;
check(cudaMemset(p->flag.ptr, 0, 4));
compare<<<blocks, 256>>>(out, p->imgs[p->ref].ptr, n, p->flag.ptr);
check(cudaGetLastError());
check(cudaMemcpy(&flag, p->flag.ptr, 4, cudaMemcpyDeviceToHost));
if (!flag)
return false;
}
p->copying.record();
check(cudaMemcpyAsync(p->host, out, c.bytes(), cudaMemcpyDeviceToHost));
p->ready.record();
p->ready.wait();
float elapsedMs;
check(cudaEventElapsedTime(&elapsedMs, p->begin.e, p->aggregated.e));
p->aggNs += std::llround(double(elapsedMs) * 1000000);
check(cudaEventElapsedTime(&elapsedMs, p->copying.e, p->ready.e));
p->copyNs += std::llround(double(elapsedMs) * 1000000);
std::swap(p->work, p->flight);
return true;
}
const unsigned char *GPU::pixels() const { return p->host; }
void GPU::ack() { std::swap(p->ref, p->flight); }
std::vector<unsigned char> GPU::unpack() {
auto &c = p->c;
size_t n = size_t(c.w) * c.h / 32;
std::vector<u32> a(n), b(n);
check(
cudaMemcpy(a.data(), p->low[p->src].ptr, n * 4, cudaMemcpyDeviceToHost));
check(
cudaMemcpy(b.data(), p->high[p->src].ptr, n * 4, cudaMemcpyDeviceToHost));
std::vector<unsigned char> cells(n * 32);
for (size_t i = 0; i < cells.size(); ++i)
cells[i] =
((a[i / 32] >> (i % 32)) & 1) | (((b[i / 32] >> (i % 32)) & 1) << 1);
return cells;
}
uint64_t GPU::aggregateNs() const { return p->aggNs; }
uint64_t GPU::downloadNs() const { return p->copyNs; }
void GPU::loadTestCells(const std::vector<unsigned char> &cells) {
require(cells.size() == size_t(p->c.w) * p->c.h, "fixture dimensions");
std::vector<u32> low(cells.size() / 32), high(low.size());
for (size_t i = 0; i < cells.size(); ++i) {
low[i / 32] |= u32(cells[i] & 1) << (i % 32);
high[i / 32] |= u32(cells[i] >> 1) << (i % 32);
}
check(cudaMemcpy(p->low[p->src].ptr, low.data(), low.size() * 4,
cudaMemcpyHostToDevice));
check(cudaMemcpy(p->high[p->src].ptr, high.data(), high.size() * 4,
cudaMemcpyHostToDevice));
}
void GPU::benchmark() {
int driver, rt;
cudaDeviceProp device;
check(cudaGetDeviceProperties(&device, 0));
check(cudaDriverGetVersion(&driver));
check(cudaRuntimeGetVersion(&rt));
auto &c = p->c;
printf("gpu=%s driver_api=%d runtime=%d width=%u height=%u neighbors=%u "
"seed=%llu steps=%u\n",
device.name, driver, rt, c.w, c.h, c.n, (unsigned long long)c.seed,
c.g);
for (int i = 0; i < 64; ++i)
step();
sync();
Event start, stop;
std::vector<u64> ns;
for (int rep = 0; rep < 10; ++rep) {
start.record();
for (u32 i = 0; i < c.g; ++i)
step();
stop.record();
stop.wait();
float ms;
check(cudaEventElapsedTime(&ms, start.e, stop.e));
ns.push_back(std::llround(double(ms) * 1000000));
printf("rep=%d total_ns=%llu\n", rep + 1, (unsigned long long)ns.back());
}
std::sort(ns.begin(), ns.end());
u64 median = (ns[4] + ns[5]) / 2;
const auto cellUpdates = __uint128_t(c.w) * c.h * c.g;
printf("min_ns=%llu median_ns=%llu p95_ns=%llu us_per_step=%llu "
"cells_per_sec=%llu milli_Gcells_per_sec=%llu\n",
(unsigned long long)ns.front(), (unsigned long long)median,
(unsigned long long)ns.back(),
(unsigned long long)(median / c.g / 1000),
(unsigned long long)(cellUpdates * 1000000000 / median),
(unsigned long long)(cellUpdates * 1000 / median));
}

23
server/gpu.hpp Normal file
View file

@ -0,0 +1,23 @@
#pragma once
#include <cstdint>
#include <memory>
#include <vector>
struct Config;
class GPU {
struct Impl;
std::unique_ptr<Impl> p;
public:
GPU(const Config &, int priority, bool snapshots = true);
~GPU();
void step();
void sync();
bool snapshot(bool mandatory);
const unsigned char *pixels() const;
void ack();
std::vector<unsigned char> unpack();
void benchmark();
uint64_t aggregateNs() const;
uint64_t downloadNs() const;
void loadTestCells(const std::vector<unsigned char> &cells);
};

174
server/main.cpp Normal file
View file

@ -0,0 +1,174 @@
#include "gpu.hpp"
#include "wire.hpp"
#include <csignal>
#include <future>
#include <iomanip>
#include <iostream>
#include <map>
#include <poll.h>
#include <thread>
using namespace std::chrono;
using Clock = steady_clock;
static void idle(SSL *tls) {
pollfd fd{SSL_get_fd(tls), POLLIN, 0};
int n = poll(&fd, 1, 0);
require(n >= 0 && !n && !SSL_pending(tls),
"unsolicited message or disconnect");
}
static void run(SSL *tls) {
auto bytes = receive(tls, {CONFIG}).second;
auto c = parse(std::string(bytes.begin(), bytes.end()));
int p = priority(c.seed);
std::cerr << "math-v1 init-v1 seed=" << c.seed << " priority=" << p
<< " config_sha256=";
for (auto b : digest(bytes))
std::cerr << std::hex << std::setw(2) << std::setfill('0') << unsigned(b);
std::cerr << std::dec << "\n";
std::cerr << std::string(bytes.begin(), bytes.end()) << "\n";
GPU gpu(c, p);
sendMsg(tls, ACCEPTED, bytes);
std::future<Clock::time_point> pending;
Clock::time_point sent;
u64 writeNs = 0;
u64 id = 0, emaNs = 0, emaBps = 0, period = 0;
auto retire = [&] {
auto end = pending.get();
gpu.ack();
u64 sample =
std::max<int64_t>(1, duration_cast<nanoseconds>(end - sent).count());
u64 bps = (c.bytes() + 32) * 1000000000ull / sample;
auto ema = [](u64 old, u64 current) {
return u64((__uint128_t(old) * 7 + current) / 8);
};
emaBps = id == 1 ? bps : ema(emaBps, bps);
emaNs = id == 1 ? sample : ema(emaNs, sample);
period = std::clamp<u64>(emaNs, 16666667, 500000000);
};
auto frame = [&](u32 gen) {
idle(tls);
if (!gpu.snapshot(gen == 0 || gen == c.g))
return;
Bytes pre;
put(pre, ++id, 8);
put(pre, gen, 8);
put(pre, c.aw(), 4);
put(pre, c.ah(), 4);
put(pre, c.k, 4);
put(pre, 1, 4);
sent = Clock::now();
pending = std::async(
std::launch::async, [&, pre = std::move(pre), expected = id] {
header(tls, FRAME, c.bytes() + 32);
sendBytes(tls, pre.data(), 32);
sendBytes(tls, gpu.pixels(), c.bytes());
writeNs += duration_cast<nanoseconds>(Clock::now() - sent).count();
auto ack = receive(tls, {ACK}).second;
require(get(ack.data(), 8) == expected, "wrong ACK id");
return Clock::now();
});
};
try {
frame(0);
auto start = Clock::now();
for (u32 gen = 1; gen <= c.g; ++gen) {
std::this_thread::sleep_until(
start + nanoseconds(u64(gen) * 1000000000 / c.rate));
gpu.step();
gpu.sync();
if (pending.valid() && (gen == c.g || pending.wait_for(seconds(0)) ==
std::future_status::ready))
retire();
if (!pending.valid()) {
idle(tls);
if (gen == c.g || Clock::now() >= sent + nanoseconds(period))
frame(gen);
}
}
retire();
idle(tls);
Bytes done;
put(done, c.g, 8);
put(done, 0, 4);
sendMsg(tls, FINISHED, done);
std::cerr << "finished generation=" << c.g << " frames=" << id
<< " aggregate_sent_ns=" << gpu.aggregateNs()
<< " d2h_ns=" << gpu.downloadNs() << " tls_send_ns=" << writeNs
<< " ack_ema_ns=" << emaNs << " ema_Bps=" << emaBps
<< " elapsed_ms="
<< duration_cast<milliseconds>(Clock::now() - start).count()
<< "\n";
} catch (...) {
if (pending.valid()) {
shutdown(SSL_get_fd(tls), SHUT_RDWR);
pending.wait();
}
throw;
}
}
int main(int argc, char **argv) try {
signal(SIGPIPE, SIG_IGN);
if (argc == 3 && std::string(argv[1]) == "--benchmark") {
auto c = parse(readConfig(argv[2]));
c.g = std::max(c.g, 1000u);
GPU gpu(c, priority(c.seed), false);
gpu.benchmark();
return 0;
}
std::map<std::string, std::string> opts;
for (int i = 1; i + 1 < argc; i += 2)
opts[argv[i]] = argv[i + 1];
require(opts.size() == 3 && argc == 7,
"use --listen 127.0.0.1:7443 --tls-cert file --tls-key file, or "
"--benchmark config.json");
auto ctx = context(false);
sslok(SSL_CTX_use_certificate_chain_file(ctx.get(),
opts.at("--tls-cert").c_str()),
"certificate");
sslok(SSL_CTX_use_PrivateKey_file(ctx.get(), opts.at("--tls-key").c_str(),
SSL_FILETYPE_PEM),
"private key");
sslok(SSL_CTX_check_private_key(ctx.get()), "key mismatch");
auto endpoint = opts.at("--listen");
auto colon = endpoint.rfind(':');
require(colon != endpoint.npos, "listen IPv4:port");
auto port = std::stoul(endpoint.substr(colon + 1));
require(port && port <= 65535, "port range");
sockaddr_in addr{};
addr.sin_family = AF_INET;
addr.sin_port = htons(port);
require(inet_pton(AF_INET, endpoint.substr(0, colon).c_str(),
&addr.sin_addr) == 1,
"listen address");
FD listener(socket(AF_INET, SOCK_STREAM, 0));
int on = 1;
setsockopt(listener.fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
require(bind(listener.fd, (sockaddr *)&addr, sizeof(addr)) == 0 &&
listen(listener.fd, 4) == 0,
"listen failed");
for (;;)
try {
FD peer(accept(listener.fd, nullptr, nullptr));
timeval timeout{120, 0};
for (int opt : {SO_RCVTIMEO, SO_SNDTIMEO})
setsockopt(peer.fd, SOL_SOCKET, opt, &timeout, sizeof(timeout));
auto tls = session(ctx.get(), peer.fd);
sslok(SSL_accept(tls.get()), "TLS accept");
try {
run(tls.get());
} catch (const std::exception &e) {
std::cerr << "session error: " << e.what() << "\n";
Bytes b;
put(b, 1, 4);
std::string msg = e.what();
msg.resize(std::min<size_t>(msg.size(), 4092));
b.insert(b.end(), msg.begin(), msg.end());
sendMsg(tls.get(), ERROR_MSG, b);
}
SSL_shutdown(tls.get());
} catch (const std::exception &e) {
std::cerr << e.what() << "\n";
}
} catch (const std::exception &e) {
std::cerr << e.what() << "\n";
return 1;
}