#include "config.hpp" #include "gpu.hpp" #include #include #include #include #include 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 __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 __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(m.r, m.p, m.s)); dstB[i] = lop<0xf8>(lop<0x6c>(a, b, w), e, lop(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 Kernel select(int p) { static Kernel kernels[] = { stepKernel, stepKernel, stepKernel, stepKernel, stepKernel, stepKernel}; 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(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<<>>( 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<<>>(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<<>>(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 GPU::unpack() { auto &c = p->c; size_t n = size_t(c.w) * c.h / 32; std::vector 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 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 &cells) { require(cells.size() == size_t(p->c.w) * p->c.h, "fixture dimensions"); std::vector 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 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)); }