Initial release of slime chunk search blog examples

This commit is contained in:
Yaossg 2026-11-20 22:11:27 +08:00
commit 057215c3a2
47 changed files with 40361 additions and 0 deletions

24
examples/Makefile Normal file
View file

@ -0,0 +1,24 @@
CXX ?= g++
NVCC ?= nvcc
CUDA_ARCH ?= 86
CXXFLAGS ?= -O3 -std=c++17 -pthread -Wall -Wextra -Wpedantic
NVCCFLAGS ?= -O3 -std=c++17
CUDA_FLAGS = -gencode arch=compute_$(CUDA_ARCH),code=sm_$(CUDA_ARCH) -gencode arch=compute_$(CUDA_ARCH),code=compute_$(CUDA_ARCH)
HEADERS := $(wildcard *.hpp *.cuh ../include/slime/*.hpp)
TARGETS := bin/cpu_forward bin/cuda_steps bin/brute bin/reverse bin/reuse
.PHONY: all test-cpu test-gpu clean
all: $(TARGETS)
bin:
mkdir -p bin
bin/cpu_forward: cpu_forward.cpp common.hpp ../include/slime/solver_core.hpp Makefile | bin
$(CXX) $(CXXFLAGS) $< -o $@
bin/%: %.cu $(HEADERS) Makefile | bin
$(NVCC) $(NVCCFLAGS) $(CUDA_FLAGS) $< -o $@
test-cpu: bin/cpu_forward
python3 test_steps.py
test-gpu: all
python3 test_steps.py --gpu
python3 test_reverse.py
clean:
rm -rf bin

62
examples/README.md Normal file
View file

@ -0,0 +1,62 @@
# 博客示例
对应[《如何快速寻找史莱姆区块?》](https://yaossg.com/site/docs/slime)。先读正推,再读反推,最后看跨位置复用。
| 阅读顺序 | 文件 | 内容 |
| --- | --- | --- |
| 1 | `cpu_forward.cpp`、`common.hpp` | Java 判定、CPU 按种子枚举位置 |
| 2 | `cuda_seed.cuh` | 每个 CUDA 线程负责一个种子 |
| 3 | `cuda_position.cuh` | 按坐标并行,线程内遍历种子 |
| 4 | `cuda_outer_sum.cuh` | 相邻线程共享坐标轴项 |
| 5 | `reverse.cu`、`reverse_support.cuh`、`grouped.hpp` | 低 18 位筛根、公共项、成组筛选、高 13 位区间求解 |
| 6 | `reuse.cu` | 同坐标类复用根,跳过无根类的位置构造 |
`cuda_steps.cu` 统一运行第 2~4 步并核对完整命中列表。
`brute.cu` 是固定坐标枚举种子的吞吐基线。
## 正推
在仓库根目录执行:
```sh
make examples
./examples/bin/cpu_forward --seed 61692151016558 --seeds 2 --x0 51060 --z0 419115 --width 17 --height 19 -n 5 --repeats 1
./examples/bin/cuda_steps --seed 61692151016558 --seeds 2 --x0 51060 --z0 419115 --width 17 --height 19 -n 5 --repeats 1
```
`--modes 2,3,4` 选择 CUDA 版本;`--help` 查看参数。三版使用相同工作量并比较全部结果。
第 2 步的线程数由种子数决定,少量种子时并行度有限。
## 反推
```sh
./examples/bin/reverse 5
./examples/bin/brute --x 51069 --z 419124 -n 5 --count 17179869184
```
`reverse` 的参数是测量轮数(默认 21)。固定锚点 `(51069,419124)`、实心 5×5,
比较低位筛根后枚举剩余 30 位,以及区间求解、输出差、预计算、成组筛选逐步加入的五版。
每版先预热,之后轮换运行,核对全部 24 个种子。搜索计时包含预计算,不含筛根、分配和结果回传。
朴素剩余位枚举明显更慢;快速验证可用 `./examples/bin/reverse 1`。
`brute` 实际只扫描 `--count` 个种子;完整 48 位耗时须按吞吐外推,不能当作实际完整扫描。
## 坐标类复用
```sh
./examples/bin/reuse examples/data/mixed512.txt 5
./examples/bin/reuse examples/data/random4096.txt 5
```
输入每行是 `x z`,第二个参数为测量轮数。模式 1 是逐位置筛根,模式 2 按坐标类复用根,
模式 3 再跳过无根位置。三版均使用相同的成组筛选与区间求解,完整核对根任务和命中列表。
计时包含分类、筛根、任务展开、传输、搜索和结果回传,不含一次性初始化。
`mixed512.txt` 有 512 个类、每类 64 个位置;`random4096.txt` 是 4096 个不同类的散点,
用于展示没有类复用时的额外开销。结果取决于输入,不能把前者的加速比推广到所有位置分布。
## 正确性
正推测试使用独立 Python Java 算术判定,包含负坐标、溢出、部分 tile 和拒绝重抽。
反推测试比较五版完整结果,并独立验证种子;复用测试比较三版完整根列表与结果。
反推候选仍可能漏掉依赖拒绝重抽的解。

142
examples/brute.cu Normal file
View file

@ -0,0 +1,142 @@
#include "../include/slime/solver_core.hpp"
#include <cuda_runtime.h>
#include <algorithm>
#include <cstdint>
#include <cstdlib>
#include <iostream>
#include <string>
#include <vector>
namespace sr = slime;
namespace {
#define CUDA_CHECK(call) \
do { \
const cudaError_t error_ = (call); \
if (error_ != cudaSuccess) { \
std::cerr << #call << ": " << cudaGetErrorString(error_) << '\n'; \
std::exit(1); \
} \
} while (false)
struct Args {
int32_t x = 51069;
int32_t z = 419124;
int32_t size = 5;
uint64_t start = 0;
uint64_t count = 1ULL << 32;
int threads = 256;
int blocksPerSm = 16;
};
const char *value(int argc, char **argv, int &i) {
if (++i >= argc)
std::exit(2);
return argv[i];
}
Args parseArgs(int argc, char **argv) {
Args args;
for (int i = 1; i < argc; ++i) {
const std::string arg = argv[i];
if (arg == "--x")
args.x = std::stoi(value(argc, argv, i));
else if (arg == "--z")
args.z = std::stoi(value(argc, argv, i));
else if (arg == "-n")
args.size = std::stoi(value(argc, argv, i));
else if (arg == "--start")
args.start = std::stoull(value(argc, argv, i));
else if (arg == "--count")
args.count = std::stoull(value(argc, argv, i));
else if (arg == "--threads")
args.threads = std::stoi(value(argc, argv, i));
else if (arg == "--blocks-per-sm")
args.blocksPerSm = std::stoi(value(argc, argv, i));
else {
std::cerr << "Usage: brute [--x X --z Z -n N] "
"[--start N --count N --threads N --blocks-per-sm N]\n";
std::exit(arg == "--help" ? 0 : 2);
}
}
if (args.size <= 0 || int64_t(args.size) * args.size > sr::kMaxPatternCells ||
args.count == 0 || args.threads <= 0 || args.threads > 1024 || args.blocksPerSm <= 0 ||
int64_t(args.x) + args.size - 1 > INT32_MAX ||
int64_t(args.z) + args.size - 1 > INT32_MAX) {
std::exit(2);
}
return args;
}
__global__ void bruteForceKernel(uint64_t start, uint64_t count, const sr::CellTerm *cells,
int cellCount, unsigned long long *matches) {
const uint64_t stride = uint64_t(gridDim.x) * blockDim.x;
for (uint64_t offset = uint64_t(blockIdx.x) * blockDim.x + threadIdx.x; offset < count;
offset += stride) {
if (sr::verifyPattern((start + offset) & sr::kMask48, cells, cellCount)) {
atomicAdd(matches, 1ULL);
}
}
}
} // namespace
int main(int argc, char **argv) {
const Args args = parseArgs(argc, argv);
std::vector<sr::CellTerm> terms;
for (int32_t dz = 0; dz < args.size; ++dz) {
for (int32_t dx = 0; dx < args.size; ++dx) {
terms.push_back({sr::coordinateTerm(args.x + dx, args.z + dz), sr::kSlime});
}
}
int device = 0;
cudaDeviceProp properties{};
CUDA_CHECK(cudaGetDevice(&device));
CUDA_CHECK(cudaGetDeviceProperties(&properties, device));
const int blocks = properties.multiProcessorCount * args.blocksPerSm;
sr::CellTerm *deviceTerms = nullptr;
unsigned long long *deviceMatches = nullptr;
CUDA_CHECK(cudaMalloc(&deviceTerms, terms.size() * sizeof(sr::CellTerm)));
CUDA_CHECK(cudaMalloc(&deviceMatches, sizeof(unsigned long long)));
CUDA_CHECK(cudaMemcpy(deviceTerms, terms.data(), terms.size() * sizeof(sr::CellTerm),
cudaMemcpyHostToDevice));
CUDA_CHECK(cudaMemset(deviceMatches, 0, sizeof(unsigned long long)));
// Warm up the context and the exact same kernel before timing.
bruteForceKernel<<<blocks, args.threads>>>(args.start, 1U << 20, deviceTerms, int(terms.size()),
deviceMatches);
CUDA_CHECK(cudaDeviceSynchronize());
CUDA_CHECK(cudaMemset(deviceMatches, 0, sizeof(unsigned long long)));
cudaEvent_t begin;
cudaEvent_t end;
CUDA_CHECK(cudaEventCreate(&begin));
CUDA_CHECK(cudaEventCreate(&end));
CUDA_CHECK(cudaEventRecord(begin));
bruteForceKernel<<<blocks, args.threads>>>(args.start, args.count, deviceTerms,
int(terms.size()), deviceMatches);
CUDA_CHECK(cudaGetLastError());
CUDA_CHECK(cudaEventRecord(end));
CUDA_CHECK(cudaEventSynchronize(end));
float milliseconds = 0.0F;
unsigned long long matches = 0;
CUDA_CHECK(cudaEventElapsedTime(&milliseconds, begin, end));
CUDA_CHECK(cudaMemcpy(&matches, deviceMatches, sizeof(matches), cudaMemcpyDeviceToHost));
const double seconds = milliseconds / 1000.0;
const double seedsPerSecond = double(args.count) / seconds;
const double fullSeconds = double(1ULL << 48) / seedsPerSecond;
std::cout << "gpu=\"" << properties.name << "\" count=" << args.count << " matches=" << matches
<< " milliseconds=" << milliseconds << " seeds_per_second=" << seedsPerSecond
<< " projected_full48_seconds=" << fullSeconds << '\n';
cudaEventDestroy(begin);
cudaEventDestroy(end);
cudaFree(deviceTerms);
cudaFree(deviceMatches);
}

172
examples/common.hpp Normal file
View file

@ -0,0 +1,172 @@
#pragma once
#include "../include/slime/solver_core.hpp"
#include <algorithm>
#include <chrono>
#include <cstdint>
#include <iostream>
#include <limits>
#include <stdexcept>
#include <string>
#include <tuple>
#include <vector>
#ifdef __CUDACC__
#define HD __host__ __device__
#else
#define HD
#endif
namespace forward {
constexpr uint64_t A = 0x5DEECE66DULL;
constexpr uint64_t B = 11;
constexpr uint64_t MASK48 = (1ULL << 48) - 1;
constexpr uint64_t SLIME_XOR = 987234911;
constexpr uint32_t REJECTION_START = 2147483640U;
constexpr int MAX_N = 8;
// The shared implementation defines Java int wrapping and sign extension.
HD inline uint64_t xTerm(int32_t x) { return slime::coordinateXTerm(x); }
HD inline uint64_t zTerm(int32_t z) { return slime::coordinateZTerm(z); }
HD inline uint64_t term(int32_t x, int32_t z) { return slime::coordinateTerm(x, z); }
// Forward examples: the original two-XOR JavaRandom path, with defined arithmetic.
struct JavaRandom {
uint64_t state;
HD explicit JavaRandom(uint64_t input) : state((input ^ A) & MASK48) {}
HD uint32_t next31() {
state = (state * A + B) & MASK48;
return uint32_t(state >> 17);
}
HD bool slime() {
for (;;) {
const uint32_t q = next31();
if (q < REJECTION_START)
return q % 10 == 0;
}
}
};
HD inline bool original(uint64_t seed, uint64_t t) {
JavaRandom random((seed + t) ^ SLIME_XOR);
return random.slime();
}
HD inline bool solid(uint64_t seed, int32_t x, int32_t z, int n) {
for (int dx = 0; dx < n; ++dx) {
for (int dz = 0; dz < n; ++dz) {
const uint64_t t = term(x + dx, z + dz);
if (!original(seed, t))
return false;
}
}
return true;
}
struct Args {
uint64_t seed = 61692151016558ULL, seeds = 1;
int32_t x0 = 50941, z0 = 418996;
uint64_t width = 257, height = 257;
int n = 5, repeats = 5, cpuThreads = 16;
uint64_t capacity = 100000;
std::string modes = "all";
uint64_t positions() const { return width * height; }
uint64_t work() const { return seeds * positions(); }
};
inline uint64_t positive(const std::string &s) {
if (s.empty() || s[0] == '-')
throw std::runtime_error("expected unsigned integer");
size_t end = 0;
const uint64_t v = std::stoull(s, &end);
if (end != s.size())
throw std::runtime_error("invalid integer");
return v;
}
inline Args parse(int argc, char **argv) {
Args a;
for (int i = 1; i < argc; ++i) {
const std::string key = argv[i];
if (key == "--help") {
std::cout << "--seed N --seeds N --x0 X --z0 Z --width N --height N -n N "
"--repeats N --cpu-threads N --capacity N --modes all|2,3,4\n";
std::exit(0);
}
if (++i >= argc)
throw std::runtime_error("missing value: " + key);
const std::string v = argv[i];
if (key == "--seed")
a.seed = positive(v);
else if (key == "--seeds")
a.seeds = positive(v);
else if (key == "--x0")
a.x0 = std::stoi(v);
else if (key == "--z0")
a.z0 = std::stoi(v);
else if (key == "--width")
a.width = positive(v);
else if (key == "--height")
a.height = positive(v);
else if (key == "-n")
a.n = std::stoi(v);
else if (key == "--repeats")
a.repeats = std::stoi(v);
else if (key == "--cpu-threads")
a.cpuThreads = std::stoi(v);
else if (key == "--capacity")
a.capacity = positive(v);
else if (key == "--modes")
a.modes = v;
else
throw std::runtime_error("unknown option: " + key);
}
if (a.n < 1 || a.n > MAX_N || !a.seeds || !a.width || !a.height || a.repeats < 1 ||
a.cpuThreads < 1 || a.cpuThreads > 256 || !a.capacity || a.capacity > 10000000 ||
a.width > 10000000 || a.height > 10000000 || a.seeds > 10000000)
throw std::runtime_error("invalid range/size/count");
if (a.seeds - 1 > UINT64_MAX - a.seed || a.seeds > UINT64_MAX / a.positions())
throw std::runtime_error("seed/work range overflow");
// Include the expanded 16x16 tile's unused fringe so CUDA precomputation is safe.
if (int64_t(a.x0) + int64_t((a.width + 15) / 16 * 16) + a.n - 2 > INT32_MAX ||
int64_t(a.z0) + int64_t((a.height + 15) / 16 * 16) + a.n - 2 > INT32_MAX)
throw std::runtime_error("coordinate footprint/tile exceeds int32");
return a;
}
struct Hit {
uint64_t seed;
int32_t x, z;
bool operator<(const Hit &o) const { return std::tie(seed, x, z) < std::tie(o.seed, o.x, o.z); }
bool operator==(const Hit &o) const { return seed == o.seed && x == o.x && z == o.z; }
};
inline double ms(std::chrono::steady_clock::time_point t) {
return std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t).count();
}
inline double median(std::vector<double> v) {
std::sort(v.begin(), v.end());
return v.size() % 2 ? v[v.size() / 2] : (v[v.size() / 2 - 1] + v[v.size() / 2]) / 2;
}
inline void array(const std::vector<double> &v) {
std::cout << '[';
for (size_t i = 0; i < v.size(); ++i) {
if (i)
std::cout << ',';
std::cout << v[i];
}
std::cout << ']';
}
inline void results(const std::vector<Hit> &v) {
std::cout << '[';
for (size_t i = 0; i < v.size(); ++i) {
if (i)
std::cout << ',';
std::cout << '[' << v[i].seed << ',' << v[i].x << ',' << v[i].z << ']';
}
std::cout << ']';
}
inline void workload(const Args &a) {
std::cout << "\"seed_start\":" << a.seed << ",\"seeds\":" << a.seeds << ",\"x0\":" << a.x0
<< ",\"z0\":" << a.z0 << ",\"width\":" << a.width << ",\"height\":" << a.height
<< ",\"n\":" << a.n << ",\"candidate_count\":" << a.work();
}
} // namespace forward

68
examples/cpu_forward.cpp Normal file
View file

@ -0,0 +1,68 @@
#include "common.hpp"
#include <atomic>
#include <thread>
// Original seed -> x -> z -> cells nesting, counting every matching anchor.
std::vector<forward::Hit> scan(const forward::Args &a) {
std::atomic<uint64_t> next{0}, count{0};
std::atomic<bool> overflow{false};
std::vector<std::vector<forward::Hit>> local(a.cpuThreads);
std::vector<std::thread> workers;
for (int t = 0; t < a.cpuThreads; ++t)
workers.emplace_back([&, t] {
for (;;) {
const uint64_t s = next.fetch_add(1, std::memory_order_relaxed);
if (s >= a.seeds)
break;
for (uint64_t xi = 0; xi < a.width; ++xi)
for (uint64_t zi = 0; zi < a.height; ++zi) {
const int32_t x = int32_t(int64_t(a.x0) + xi),
z = int32_t(int64_t(a.z0) + zi);
if (forward::solid(a.seed + s, x, z, a.n)) {
if (count.fetch_add(1, std::memory_order_relaxed) < a.capacity)
local[t].push_back({a.seed + s, x, z});
else
overflow.store(true, std::memory_order_relaxed);
}
}
}
});
for (auto &w : workers)
w.join();
if (overflow.load())
throw std::runtime_error("hit buffer overflow; raise --capacity");
std::vector<forward::Hit> result;
for (const auto &v : local)
result.insert(result.end(), v.begin(), v.end());
return result;
}
int main(int argc, char **argv) {
try {
const auto a = forward::parse(argc, argv);
std::cout.precision(10);
auto expected = scan(a); // full-workload warmup
std::sort(expected.begin(), expected.end());
std::vector<double> times;
for (int r = 0; r < a.repeats; ++r) {
const auto begin = std::chrono::steady_clock::now();
auto hits = scan(a);
times.push_back(
forward::ms(begin)); // thread creation + scan + collection, excludes sort
std::sort(hits.begin(), hits.end());
if (hits != expected)
throw std::runtime_error("CPU repeats disagree");
}
std::cout << '{';
forward::workload(a);
std::cout << ",\"mode\":\"cpu_forward\",\"cpu_threads\":" << a.cpuThreads
<< ",\"samples_ms\":";
forward::array(times);
std::cout << ",\"median_ms\":" << forward::median(times) << ",\"hits\":";
forward::results(expected);
std::cout << "}\n";
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
return 1;
}
}

View file

@ -0,0 +1,66 @@
#pragma once
// Common rectangle path: use block coordinates directly, avoiding 64-bit tile divisions.
// One thread keeps its coordinate while scanning all seeds, as in the coordinate kernel.
__global__ void outerRectKernel(DeviceArgs a, forward::Hit *hits, unsigned long long *count) {
__shared__ uint64_t xs[16 + forward::MAX_N - 1], zs[16 + forward::MAX_N - 1];
const unsigned lane = threadIdx.y * 16 + threadIdx.x;
const uint64_t xb = uint64_t(blockIdx.x) * 16, zb = uint64_t(blockIdx.y) * 16;
if (lane < unsigned(16 + a.n - 1)) {
xs[lane] = forward::xTerm(int32_t(int64_t(a.x0) + int64_t(xb + lane)));
zs[lane] = forward::zTerm(int32_t(int64_t(a.z0) + int64_t(zb + lane)));
}
__syncthreads();
const uint64_t xi = xb + threadIdx.x, zi = zb + threadIdx.y;
if (xi >= a.width || zi >= a.height)
return;
for (uint64_t s = 0; s < a.seeds; ++s) {
bool ok = true;
for (int dx = 0; dx < a.n && ok; ++dx)
for (int dz = 0; dz < a.n; ++dz) {
if (!forward::original(a.seed + s, xs[threadIdx.x + dx] + zs[threadIdx.y + dz])) {
ok = false;
break;
}
}
if (ok)
emit(a, hits, count, a.seed + s, int32_t(int64_t(a.x0) + int64_t(xi)),
int32_t(int64_t(a.z0) + int64_t(zi)));
}
}
// One block handles a 16x16 anchor tile; each axis needs 16+n-1 terms.
// Fallback for unusually tall rectangles exceeding the grid.y limit.
__global__ void outerKernel(DeviceArgs a, forward::Hit *hits, unsigned long long *count) {
__shared__ uint64_t xs[16 + forward::MAX_N - 1], zs[16 + forward::MAX_N - 1];
const uint64_t tilesX = (a.width + 15) / 16, tilesZ = (a.height + 15) / 16;
const uint64_t total = tilesX * tilesZ;
const unsigned lane = threadIdx.y * 16 + threadIdx.x;
for (uint64_t tile = blockIdx.x; tile < total; tile += gridDim.x) {
const uint64_t tx = tile / tilesZ, tz = tile % tilesZ;
if (lane < unsigned(16 + a.n - 1)) {
xs[lane] = forward::xTerm(int32_t(int64_t(a.x0) + int64_t(tx * 16 + lane)));
zs[lane] = forward::zTerm(int32_t(int64_t(a.z0) + int64_t(tz * 16 + lane)));
}
__syncthreads();
const uint64_t xi = tx * 16 + threadIdx.x, zi = tz * 16 + threadIdx.y;
for (uint64_t s = 0; s < a.seeds; ++s) {
bool ok = xi < a.width && zi < a.height;
for (int dx = 0; dx < a.n && ok; ++dx)
for (int dz = 0; dz < a.n; ++dz) {
if (!forward::original(a.seed + s,
xs[threadIdx.x + dx] + zs[threadIdx.y + dz])) {
ok = false;
break;
}
}
if (ok)
emit(a, hits, count, a.seed + s, int32_t(int64_t(a.x0) + int64_t(xi)),
int32_t(int64_t(a.z0) + int64_t(zi)));
}
// No final barrier is needed for a block assigned only one tile.
// When a giant workload exceeds the grid limit, synchronize before reuse.
if (tile + gridDim.x < total)
__syncthreads();
}
}

View file

@ -0,0 +1,71 @@
#pragma once
// Coordinate mapping: one work item is a fixed (x,z). Its private axis terms are computed
// once, then reused for every seed. No host table or global coordinate table.
template <int N>
__device__ __forceinline__ bool solidAxes(uint64_t seed, const uint64_t (&xs)[N],
const uint64_t (&zs)[N]) {
#pragma unroll
for (int dx = 0; dx < N; ++dx) {
#pragma unroll
for (int dz = 0; dz < N; ++dz) {
const uint64_t t = xs[dx] + zs[dz];
if (!forward::original(seed, t))
return false;
}
}
return true;
}
template <int N>
__global__ void coordinateKernel(DeviceArgs a, forward::Hit *hits, unsigned long long *count) {
const uint64_t area = a.width * a.height;
const uint64_t stride = uint64_t(gridDim.x) * blockDim.x;
for (uint64_t p = uint64_t(blockIdx.x) * blockDim.x + threadIdx.x; p < area; p += stride) {
const int32_t x = int32_t(int64_t(a.x0) + int64_t(p / a.height));
const int32_t z = int32_t(int64_t(a.z0) + int64_t(p % a.height));
uint64_t xs[N], zs[N];
#pragma unroll
for (int i = 0; i < N; ++i) {
xs[i] = forward::xTerm(x + i);
zs[i] = forward::zTerm(z + i);
}
for (uint64_t s = 0; s < a.seeds; ++s)
if (solidAxes<N>(a.seed + s, xs, zs))
emit(a, hits, count, a.seed + s, x, z);
}
}
// Compile-time sizes let the compiler scalarize/unroll the private axis arrays.
// Dispatch once on the host, outside the kernel's timed seed loop.
void launchCoordinate(int blocks, int threads, DeviceArgs a, forward::Hit *hits,
unsigned long long *count) {
switch (a.n) {
case 1:
coordinateKernel<1><<<blocks, threads>>>(a, hits, count);
break;
case 2:
coordinateKernel<2><<<blocks, threads>>>(a, hits, count);
break;
case 3:
coordinateKernel<3><<<blocks, threads>>>(a, hits, count);
break;
case 4:
coordinateKernel<4><<<blocks, threads>>>(a, hits, count);
break;
case 5:
coordinateKernel<5><<<blocks, threads>>>(a, hits, count);
break;
case 6:
coordinateKernel<6><<<blocks, threads>>>(a, hits, count);
break;
case 7:
coordinateKernel<7><<<blocks, threads>>>(a, hits, count);
break;
case 8:
coordinateKernel<8><<<blocks, threads>>>(a, hits, count);
break;
default:
throw std::runtime_error("invalid pattern size");
}
}

15
examples/cuda_seed.cuh Normal file
View file

@ -0,0 +1,15 @@
#pragma once
// CUDA translation of CPU forward search: one work item is one seed, its positions are serial.
__global__ void seedKernel(DeviceArgs a, forward::Hit *hits, unsigned long long *count) {
const uint64_t stride = uint64_t(gridDim.x) * blockDim.x;
for (uint64_t s = uint64_t(blockIdx.x) * blockDim.x + threadIdx.x; s < a.seeds; s += stride) {
for (uint64_t xi = 0; xi < a.width; ++xi)
for (uint64_t zi = 0; zi < a.height; ++zi) {
const int32_t x = int32_t(int64_t(a.x0) + int64_t(xi));
const int32_t z = int32_t(int64_t(a.z0) + int64_t(zi));
if (forward::solid(a.seed + s, x, z, a.n))
emit(a, hits, count, a.seed + s, x, z);
}
}
}

173
examples/cuda_steps.cu Normal file
View file

@ -0,0 +1,173 @@
#include "common.hpp"
#include <cuda_runtime.h>
#include <map>
void check(cudaError_t err) {
if (err != cudaSuccess)
throw std::runtime_error(cudaGetErrorString(err));
}
// std::string in host Args must never be copied into a device kernel.
struct DeviceArgs {
uint64_t seed, seeds, width, height, capacity;
int32_t x0, z0;
int n;
};
__device__ void emit(DeviceArgs a, forward::Hit *hits, unsigned long long *count, uint64_t seed,
int32_t x, int32_t z) {
const auto slot = atomicAdd(count, 1ULL);
if (slot < a.capacity)
hits[slot] = {seed, x, z};
}
#include "cuda_seed.cuh"
#include "cuda_position.cuh"
#include "cuda_outer_sum.cuh"
struct Buffers {
forward::Hit *hits = nullptr;
unsigned long long *count = nullptr;
cudaEvent_t begin = nullptr, end = nullptr;
~Buffers() {
if (begin)
cudaEventDestroy(begin);
if (end)
cudaEventDestroy(end);
if (count)
cudaFree(count);
if (hits)
cudaFree(hits);
}
};
struct Run {
double kernelMs, scanMs;
std::vector<forward::Hit> hits;
};
Run run(int mode, const forward::Args &a, int maxBlocks, Buffers &b) {
const auto wall = std::chrono::steady_clock::now();
check(cudaMemset(b.count, 0, sizeof(unsigned long long)));
const DeviceArgs d{a.seed, a.seeds, a.width, a.height, a.capacity, a.x0, a.z0, a.n};
const int threads = 256;
const uint64_t work = mode == 2 ? a.seeds : a.positions();
const int blocks = int(std::min<uint64_t>((work + threads - 1) / threads, maxBlocks));
check(cudaEventRecord(b.begin));
switch (mode) {
case 2:
seedKernel<<<blocks, threads>>>(d, b.hits, b.count);
break;
case 3:
launchCoordinate(blocks, threads, d, b.hits, b.count);
break;
case 4: {
const uint64_t tiles = (a.width + 15) / 16 * ((a.height + 15) / 16);
if ((a.height + 15) / 16 <= 65535) {
const dim3 grid(unsigned((a.width + 15) / 16), unsigned((a.height + 15) / 16));
outerRectKernel<<<grid, dim3(16, 16)>>>(d, b.hits, b.count);
} else {
outerKernel<<<int(std::min<uint64_t>(tiles, 0x7FFFFFFFULL)), dim3(16, 16)>>>(d, b.hits,
b.count);
}
break;
}
default:
throw std::runtime_error("mode must be 2..4");
}
check(cudaGetLastError());
check(cudaEventRecord(b.end));
check(cudaEventSynchronize(b.end));
float kernel = 0;
check(cudaEventElapsedTime(&kernel, b.begin, b.end));
unsigned long long count = 0;
check(cudaMemcpy(&count, b.count, sizeof(count), cudaMemcpyDeviceToHost));
if (count > a.capacity)
throw std::runtime_error("hit buffer overflow; raise --capacity");
std::vector<forward::Hit> hits(count);
if (count)
check(
cudaMemcpy(hits.data(), b.hits, count * sizeof(forward::Hit), cudaMemcpyDeviceToHost));
const double wallMs = forward::ms(wall);
std::sort(hits.begin(), hits.end()); // equality checks are outside timed scan
return {kernel, wallMs, std::move(hits)};
}
int main(int argc, char **argv) {
try {
const auto start = std::chrono::steady_clock::now();
const auto a = forward::parse(argc, argv);
std::vector<int> modes;
if (a.modes == "all")
modes = {2, 3, 4};
else {
for (size_t p = 0; p < a.modes.size();) {
const size_t end = a.modes.find(',', p);
const std::string token =
a.modes.substr(p, end == std::string::npos ? end : end - p);
const auto m = forward::positive(token);
if (m < 2 || m > 4 || std::find(modes.begin(), modes.end(), int(m)) != modes.end())
throw std::runtime_error("invalid/duplicate CUDA mode");
modes.push_back(int(m));
if (end == std::string::npos)
break;
p = end + 1;
}
}
if (modes.empty())
throw std::runtime_error("empty mode list");
int device = 0;
cudaDeviceProp prop{};
check(cudaGetDevice(&device));
check(cudaGetDeviceProperties(&prop, device));
const int maxBlocks = prop.multiProcessorCount * 32;
Buffers b;
check(cudaMalloc(&b.hits, a.capacity * sizeof(forward::Hit)));
check(cudaMalloc(&b.count, sizeof(unsigned long long)));
check(cudaEventCreate(&b.begin));
check(cudaEventCreate(&b.end));
const double setup = forward::ms(start);
std::vector<forward::Hit> expected;
bool first = true;
for (int mode : modes) {
const auto r = run(mode, a, maxBlocks, b); // warm every kernel on actual workload
if (first) {
expected = r.hits;
first = false;
} else if (r.hits != expected)
throw std::runtime_error("CUDA warmups disagree");
}
std::map<int, std::vector<double>> kernel, wall;
for (int repeat = 0; repeat < a.repeats; ++repeat) {
for (size_t j = 0; j < modes.size(); ++j) {
const int mode =
modes[(j + repeat) % modes.size()]; // rotate order to reduce clock/order bias
auto r = run(mode, a, maxBlocks, b);
if (r.hits != expected)
throw std::runtime_error("CUDA modes/repeats disagree");
kernel[mode].push_back(r.kernelMs);
wall[mode].push_back(r.scanMs);
}
}
std::cout.precision(10);
std::cout << '{';
forward::workload(a);
std::cout << ",\"gpu\":\"" << prop.name << "\",\"setup_ms\":" << setup
<< ",\"comparison_equal\":true,\"rows\":[";
for (size_t i = 0; i < modes.size(); ++i) {
const int m = modes[i];
if (i)
std::cout << ',';
std::cout << "{\"mode\":" << m << ",\"kernel_samples_ms\":";
forward::array(kernel[m]);
std::cout << ",\"kernel_median_ms\":" << forward::median(kernel[m])
<< ",\"scan_samples_ms\":";
forward::array(wall[m]);
std::cout << ",\"scan_median_ms\":" << forward::median(wall[m]) << '}';
}
std::cout << "],\"hits\":";
forward::results(expected);
std::cout << "}\n";
} catch (const std::exception &e) {
std::cerr << e.what() << '\n';
return 1;
}
}

View file

@ -0,0 +1,33 @@
{
"anchor": [
51069,
419124
],
"roots": 84,
"seeds": [
10358701894766,
15959335054446,
18914276748398,
24514909908078,
27469851602030,
33070484761710,
36025426455662,
41626059615342,
44581001309294,
50181634468974,
53136576162926,
58737209322606,
61692151016558,
67292784176238,
70247725870190,
75848359029870,
78803300723822,
84403933883502,
87358875577454,
92959508737134,
95914450431086,
101515083590766,
104470025284718,
110070658444398
]
}

32768
examples/data/mixed512.txt Normal file

File diff suppressed because it is too large Load diff

4096
examples/data/random4096.txt Normal file

File diff suppressed because it is too large Load diff

45
examples/grouped.hpp Normal file
View file

@ -0,0 +1,45 @@
#pragma once
#include "../include/slime/upper_interval.hpp"
#if defined(__CUDACC__)
#define GROUP_HD __host__ __device__ __forceinline__
#else
#define GROUP_HD inline
#endif
namespace reverse_demo {
namespace sr = slime;
struct Prepared {
uint32_t h[25], b[25];
};
GROUP_HD void prepare(uint32_t root, const sr::CellTerm *cells, Prepared &out) {
for (int i = 0; i < 25; ++i) {
const uint64_t a = root + cells[i].term;
out.h[i] = uint32_t(a >> 18);
const uint64_t lo = (a ^ sr::kCombinedXor) & ((1U << 18) - 1);
out.b[i] = uint32_t((lo * sr::kJavaMultiplier + 11) >> 17);
}
}
GROUP_HD uint32_t preparedQ(const Prepared &p, int i, uint32_t m) {
const uint32_t u = (m + p.h[i]) ^ uint32_t(sr::kCombinedXor >> 18);
return (p.b[i] + 2U * uint32_t(sr::kJavaMultiplier) * u) & 0x7fffffffU;
}
// Bits 4..7 of kCombinedXor >> 18 are zero. For m=base+16*j,
// j in [0,16), m XOR C is affine. Each shifted input crosses at
// most one 256 boundary, so each output difference has at most two values.
// base bits 4..7 must be zero; cells[0].term must be zero (normalized anchor).
GROUP_HD uint32_t groupMask(const Prepared &p, uint32_t base, int count = 25) {
uint32_t mask = 65535;
const uint32_t q0 = preparedQ(p, 0, base), qend = preparedQ(p, 0, base + 240);
for (int i = 1; i < count && mask; ++i) {
const uint32_t n = (256 - ((base + p.h[i]) & 255) + 15) >> 4;
const uint32_t before = (1U << n) - 1;
const uint32_t r0 = ((preparedQ(p, i, base) - q0) & 0x7fffffffU) % 10;
const uint32_t r1 = ((preparedQ(p, i, base + 240) - qend) & 0x7fffffffU) % 10;
const uint32_t allowed =
((r0 == 0 || r0 == 8) ? before : 0U) | ((r1 == 0 || r1 == 8) ? (65535U ^ before) : 0U);
mask &= allowed;
}
return mask;
}
} // namespace reverse_demo
#undef GROUP_HD

233
examples/reuse.cu Normal file
View file

@ -0,0 +1,233 @@
#include "reverse_support.cuh"
#include <sstream>
__global__ void expandJobs(const uint32_t *positionClass, const uint32_t *offsets,
const uint32_t *classOffsets, const uint32_t *roots, uint32_t n,
Job *jobs) {
uint32_t p = blockIdx.x * blockDim.x + threadIdx.x;
if (p >= n)
return;
const uint32_t c = positionClass[p];
for (uint32_t i = classOffsets[c]; i < classOffsets[c + 1]; ++i)
jobs[offsets[p] + i - classOffsets[c]] = {p, roots[i]};
}
struct Extra {
Position *reps;
uint32_t *positionClass, *offsets, *classOffsets, *roots;
Extra(size_t n) {
CUDA(cudaMalloc(&reps, n * sizeof(Position)));
CUDA(cudaMalloc(&positionClass, n * sizeof(uint32_t)));
CUDA(cudaMalloc(&offsets, (n + 1) * sizeof(uint32_t)));
CUDA(cudaMalloc(&classOffsets, (n + 1) * sizeof(uint32_t)));
CUDA(cudaMalloc(&roots, JOB_CAPACITY * sizeof(uint32_t)));
}
~Extra() {
cudaFree(reps);
cudaFree(positionClass);
cudaFree(offsets);
cudaFree(classOffsets);
cudaFree(roots);
}
};
struct Run {
double hostMs, buildMs, rootMs, expandMs, searchMs;
uint32_t classes, jobs, activePositions;
std::vector<Match> matches;
std::vector<Job> rootList;
};
Run run(const std::vector<std::pair<int32_t, int32_t>> &coords, Device &d, Extra &extra, int mode) {
const auto start = Clock::now();
auto ms = [](auto t) {
return std::chrono::duration<double, std::milli>(Clock::now() - t).count();
};
std::vector<Position> positions;
positions.reserve(coords.size());
if (mode != 3)
for (auto [x, z] : coords)
positions.push_back(makePosition(x, z));
std::vector<Position> reps;
std::vector<uint32_t> pc;
if (mode >= 2) {
std::map<uint64_t, uint32_t> map;
for (auto [x, z] : coords) {
uint64_t key = (uint64_t(uint32_t(x) & 65535) << 17) | (uint32_t(z) & 131071);
auto [it, inserted] = map.emplace(key, uint32_t(reps.size()));
if (inserted)
reps.push_back(makePosition(x, z));
pc.push_back(it->second);
}
}
if (!positions.empty())
CUDA(cudaMemcpy(d.positions, positions.data(), positions.size() * sizeof(Position),
cudaMemcpyHostToDevice));
Run r{};
r.classes = mode >= 2 ? reps.size() : positions.size();
r.buildMs = ms(start);
const auto rootStart = Clock::now();
if (mode >= 2) {
CUDA(cudaMemcpy(extra.reps, reps.data(), reps.size() * sizeof(Position),
cudaMemcpyHostToDevice));
CUDA(cudaMemset(d.total, 0, sizeof(*d.total)));
rootKernel<<<unsigned(((uint64_t(reps.size()) << 18) + 255) / 256), 256>>>(
extra.reps, reps.size(), d.jobs, d.total);
} else
d.roots(positions.size());
uint64_t n = d.totalCount();
if (n > JOB_CAPACITY)
throw std::runtime_error("root capacity exceeded");
r.rootMs = ms(rootStart);
const auto expandStart = Clock::now();
std::vector<uint32_t> originalIndices;
if (mode >= 2) {
std::vector<Job> cj(n);
if (n)
CUDA(cudaMemcpy(cj.data(), d.jobs, n * sizeof(Job), cudaMemcpyDeviceToHost));
std::vector<std::vector<uint32_t>> lists(reps.size());
for (auto j : cj)
lists[j.position].push_back(j.root);
if (mode == 3) {
std::vector<uint32_t> compactClasses;
for (uint32_t i = 0; i < coords.size(); ++i)
if (!lists[pc[i]].empty()) {
auto [x, z] = coords[i];
positions.push_back(makePosition(x, z));
compactClasses.push_back(pc[i]);
originalIndices.push_back(i);
}
pc = std::move(compactClasses);
if (!positions.empty())
CUDA(cudaMemcpy(d.positions, positions.data(), positions.size() * sizeof(Position),
cudaMemcpyHostToDevice));
}
std::vector<uint32_t> roots, co{0}, offsets{0};
for (auto &list : lists) {
std::sort(list.begin(), list.end());
roots.insert(roots.end(), list.begin(), list.end());
co.push_back(roots.size());
}
uint64_t expanded = 0;
for (auto c : pc) {
expanded += lists[c].size();
if (expanded > JOB_CAPACITY)
throw std::runtime_error("expanded capacity exceeded; use smaller batch");
offsets.push_back(expanded);
}
n = expanded;
CUDA(cudaMemcpy(extra.positionClass, pc.data(), pc.size() * sizeof(uint32_t),
cudaMemcpyHostToDevice));
CUDA(cudaMemcpy(extra.offsets, offsets.data(), offsets.size() * sizeof(uint32_t),
cudaMemcpyHostToDevice));
CUDA(cudaMemcpy(extra.classOffsets, co.data(), co.size() * sizeof(uint32_t),
cudaMemcpyHostToDevice));
if (!roots.empty())
CUDA(cudaMemcpy(extra.roots, roots.data(), roots.size() * sizeof(uint32_t),
cudaMemcpyHostToDevice));
if (!positions.empty())
expandJobs<<<unsigned((positions.size() + 255) / 256), 256>>>(
extra.positionClass, extra.offsets, extra.classOffsets, extra.roots,
positions.size(), d.jobs);
CUDA(cudaGetLastError());
CUDA(cudaDeviceSynchronize());
}
r.expandMs = ms(expandStart);
r.jobs = n;
r.activePositions = positions.size();
const auto searchStart = Clock::now();
d.search(n, SearchStage::Grouped);
r.matches = d.results();
if (mode == 3)
for (auto &match : r.matches)
match.position = originalIndices[match.position];
r.searchMs = ms(searchStart);
r.hostMs = ms(start);
// Validation-only transfers/sorting are outside reported pipeline time.
r.rootList.resize(n);
if (n)
CUDA(cudaMemcpy(r.rootList.data(), d.jobs, n * sizeof(Job), cudaMemcpyDeviceToHost));
if (mode == 3)
for (auto &job : r.rootList)
job.position = originalIndices[job.position];
std::sort(r.rootList.begin(), r.rootList.end(), [](Job a, Job b) {
return std::tie(a.position, a.root) < std::tie(b.position, b.root);
});
return r;
}
int main(int argc, char **argv) {
try {
if (argc < 2)
throw std::runtime_error("usage: reuse positions.txt [repeats=5]");
const auto process = Clock::now();
std::ifstream in(argv[1]);
if (!in)
throw std::runtime_error("cannot open input");
std::vector<std::pair<int32_t, int32_t>> coords;
std::string line;
while (std::getline(in, line)) {
std::istringstream row(line);
row >> std::ws;
if (row.eof())
continue;
int64_t x, z;
std::string extra;
if (!(row >> x >> z) || (row >> extra))
throw std::runtime_error("expected x z on each input line");
if (x < INT32_MIN || z < INT32_MIN || x > INT32_MAX - 4LL || z > INT32_MAX - 4LL)
throw std::runtime_error("coordinates including 5x5 window must fit int32");
coords.emplace_back(int32_t(x), int32_t(z));
if (coords.size() > 65536)
throw std::runtime_error("expected 1..65536 coordinates");
}
if (in.bad())
throw std::runtime_error("failed reading coordinates");
if (coords.empty() || coords.size() > 65536)
throw std::runtime_error("expected 1..65536 coordinates");
int repeats = argc > 2 ? std::stoi(argv[2]) : 5;
if (repeats < 1)
throw std::runtime_error("invalid repeats");
Device d(std::vector<Position>(coords.size()));
Extra e(coords.size());
std::cout << std::setprecision(10);
std::cout << "{\"type\":\"setup\",\"host_ms\":"
<< std::chrono::duration<double, std::milli>(Clock::now() - process).count()
<< "}" << std::endl;
Run ref;
for (int round = -1; round < repeats; ++round)
for (int k = 0; k < 3; ++k) {
int mode = 1 + (round < 0 ? k : (round + k) % 3);
Run r = run(coords, d, e, mode);
if (round == -1 && mode == 1)
ref = r;
else {
if (r.matches != ref.matches || r.rootList.size() != ref.rootList.size())
throw std::runtime_error("pipeline mismatch");
for (size_t i = 0; i < r.rootList.size(); ++i)
if (r.rootList[i].position != ref.rootList[i].position ||
r.rootList[i].root != ref.rootList[i].root)
throw std::runtime_error("complete root list mismatch");
}
if (round >= 0)
std::cout << "{\"type\":\"pipeline\",\"mode\":" << mode
<< ",\"round\":" << round << ",\"positions\":" << coords.size()
<< ",\"classes\":" << r.classes
<< ",\"active_positions\":" << r.activePositions
<< ",\"jobs\":" << r.jobs << ",\"matches\":" << r.matches.size()
<< ",\"host_ms\":" << r.hostMs << ",\"build_ms\":" << r.buildMs
<< ",\"root_ms\":" << r.rootMs << ",\"expand_ms\":" << r.expandMs
<< ",\"search_ms\":" << r.searchMs << "}" << std::endl;
}
std::cout << "{\"type\":\"validation\",\"complete_roots_equal\":true,\"complete_matches_"
"equal\":true,\"matches\":[";
for (size_t i = 0; i < ref.matches.size(); ++i) {
if (i)
std::cout << ",";
auto m = ref.matches[i];
std::cout << "[" << m.seed << "," << coords[m.position].first << ","
<< coords[m.position].second << "]";
}
std::cout << "]}" << std::endl;
return 0;
} catch (const std::exception &e) {
std::cerr << e.what() << "\n";
return 1;
}
}

114
examples/reverse.cu Normal file
View file

@ -0,0 +1,114 @@
#include "reverse_support.cuh"
__device__ bool firstDrawPattern(uint64_t seed, const sr::CellTerm *cells) {
for (int i = 0; i < 25; ++i)
if ((sr::nextStateFromTerm(seed, cells[i].term) >> 17) % 10 != 0)
return false;
return sr::verifyPattern(seed, cells, 25);
}
// Low18 roots are already known; enumerate the remaining 30 bits.
__global__ void enumerateRemaining(const Position *positions, const Job *jobs, uint32_t count,
Match *out, unsigned long long *total) {
const uint64_t stride = uint64_t(gridDim.x) * blockDim.x;
for (uint64_t idx = uint64_t(blockIdx.x) * blockDim.x + threadIdx.x;
idx < (uint64_t(count) << 30); idx += stride) {
const Job job = jobs[idx >> 30];
const Position &p = positions[job.position];
const uint64_t seed = job.root + ((idx & ((1ULL << 30) - 1)) << 18);
if (firstDrawPattern(seed, p.cells)) {
Emitter emit{job.position, p.anchor, out, total};
emit(seed);
}
}
}
__global__ void intervalsWithoutFilter(const Position *positions, const Job *jobs, uint32_t count,
Match *out, unsigned long long *total) {
const uint64_t idx = uint64_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (idx >= (uint64_t(count) << 17))
return;
const Job job = jobs[idx >> 17];
const Position &p = positions[job.position];
const uint64_t low = job.root + ((idx & ((1U << 17) - 1)) << 18);
Emitter emit{job.position, p.anchor, out, total};
sr::solveIntervals(low, p.cells, 25, emit);
}
int main(int argc, char **argv) {
try {
const int repeats = argc > 1 ? std::stoi(argv[1]) : 21;
if (repeats < 1)
throw std::runtime_error("positive repeats required");
Device d({makePosition(51069, 419124)});
d.roots(1);
const uint64_t roots = d.totalCount();
if (roots != 84)
throw std::runtime_error("expected 84 roots");
d.search(roots, SearchStage::Grouped);
const auto expected = d.results();
if (expected.size() != 24)
throw std::runtime_error("expected 24 seeds");
const char *labels[] = {"low18_enumerate30", "intervals_only", "difference_intervals",
"precompute_intervals", "group_intervals"};
std::vector<double> samples[5];
for (int round = -1; round < repeats; ++round)
for (int j = 0; j < 5; ++j) {
const int mode = round < 0 ? j : (round + j) % 5;
float ms;
if (mode == 0) {
cudaDeviceProp prop{};
CUDA(cudaGetDeviceProperties(&prop, 0));
CUDA(cudaMemset(d.total, 0, sizeof(*d.total)));
CUDA(cudaEventRecord(d.start));
enumerateRemaining<<<prop.multiProcessorCount * 32, 256>>>(
d.positions, d.jobs, roots, d.matches, d.total);
ms = d.finish();
} else if (mode == 1) {
CUDA(cudaMemset(d.total, 0, sizeof(*d.total)));
CUDA(cudaEventRecord(d.start));
intervalsWithoutFilter<<<unsigned(((roots << 17) + 255) / 256), 256>>>(
d.positions, d.jobs, roots, d.matches, d.total);
ms = d.finish();
} else
ms = d.search(roots, mode == 2 ? SearchStage::Difference
: mode == 3 ? SearchStage::Precomputed
: SearchStage::Grouped);
if (d.results() != expected)
throw std::runtime_error("full result list mismatch");
if (round >= 0)
samples[mode].push_back(ms);
}
std::cout << std::setprecision(10)
<< "{\"anchor\":[51069,419124],\"roots\":84,\"lower35\":11010048,\"comparison_"
"equal\":true,\"rows\":[";
for (int mode = 0; mode < 5; ++mode) {
if (mode)
std::cout << ",";
auto sorted = samples[mode];
std::sort(sorted.begin(), sorted.end());
double median = sorted[sorted.size() / 2];
if (sorted.size() % 2 == 0)
median = (median + sorted[sorted.size() / 2 - 1]) / 2;
std::cout << "{\"mode\":\"" << labels[mode] << "\",\"median_ms\":" << median
<< ",\"samples_ms\":[";
for (size_t i = 0; i < samples[mode].size(); ++i) {
if (i)
std::cout << ",";
std::cout << samples[mode][i];
}
std::cout << "]}";
}
std::cout << "],\"matches\":[";
for (size_t i = 0; i < expected.size(); ++i) {
if (i)
std::cout << ",";
std::cout << expected[i].seed;
}
std::cout << "]}\n";
return 0;
} catch (const std::exception &e) {
std::cerr << e.what() << "\n";
return 1;
}
}

View file

@ -0,0 +1,213 @@
#pragma once
// Fixed 5x5 workload shared by the reverse-search and coordinate-reuse examples.
#include "grouped.hpp"
#include <cuda_runtime.h>
#include <algorithm>
#include <array>
#include <chrono>
#include <cstdint>
#include <fstream>
#include <iomanip>
#include <iostream>
#include <map>
#include <numeric>
#include <stdexcept>
#include <string>
#include <tuple>
#include <vector>
namespace sr = slime;
using Clock = std::chrono::steady_clock;
#define CUDA(call) \
do { \
auto e = (call); \
if (e != cudaSuccess) \
throw std::runtime_error(std::string(#call) + ": " + cudaGetErrorString(e)); \
} while (0)
struct Position {
int32_t x, z;
uint64_t anchor;
sr::CellTerm cells[25];
};
struct Job {
uint32_t position, root;
};
struct Match {
uint64_t position, seed;
bool operator<(const Match &o) const {
return std::tie(position, seed) < std::tie(o.position, o.seed);
}
bool operator==(const Match &o) const { return position == o.position && seed == o.seed; }
};
constexpr uint32_t MATCH_CAPACITY = 1U << 20;
constexpr uint32_t JOB_CAPACITY = 1U << 22;
Position makePosition(int32_t x, int32_t z) {
Position p{};
p.x = x;
p.z = z;
p.anchor = sr::coordinateTerm(x, z);
for (int j = 0; j < 5; ++j)
for (int i = 0; i < 5; ++i)
p.cells[j * 5 + i] = {(sr::coordinateTerm(x + i, z + j) - p.anchor) & sr::kMask48,
sr::kSlime};
return p;
}
__global__ void rootKernel(const Position *positions, uint32_t count, Job *jobs,
unsigned long long *total) {
uint64_t idx = uint64_t(blockIdx.x) * blockDim.x + threadIdx.x;
if (idx >= (uint64_t(count) << 18))
return;
const uint32_t pos = uint32_t(idx >> 18), root = uint32_t(idx) & ((1U << 18) - 1);
const Position &p = positions[pos];
for (int i = 0; i < 25; ++i) {
const uint32_t in = root + uint32_t(p.cells[i].term);
if ((((in ^ uint32_t(sr::kCombinedXor)) * uint32_t(sr::kJavaMultiplier) + 11U) >> 17) & 1U)
return;
}
const auto at = atomicAdd(total, 1ULL);
if (at < JOB_CAPACITY)
jobs[at] = {pos, root};
}
struct Emitter {
uint32_t position;
uint64_t anchor;
Match *out;
unsigned long long *count;
__device__ void operator()(uint64_t s) {
auto at = atomicAdd(count, 1ULL);
if (at < MATCH_CAPACITY)
out[at] = {position, (s - anchor) & sr::kMask48};
}
};
using reverse_demo::Prepared;
using reverse_demo::preparedQ;
__global__ void prepareKernel(const Position *positions, const Job *jobs, uint32_t count,
Prepared *out) {
const uint32_t j = blockIdx.x * blockDim.x + threadIdx.x;
if (j < count)
reverse_demo::prepare(jobs[j].root, positions[jobs[j].position].cells, out[j]);
}
enum class SearchStage { Difference, Precomputed, Grouped };
template <SearchStage Mode>
__global__ void searchKernel(const Position *positions, const Job *jobs, uint32_t count, Match *out,
unsigned long long *total, const Prepared *prepared) {
uint64_t idx = uint64_t(blockIdx.x) * blockDim.x + threadIdx.x;
constexpr int bits = Mode == SearchStage::Grouped ? 13 : 17;
if (idx >= (uint64_t(count) << bits))
return;
const Job job = jobs[idx >> bits];
const uint32_t m = idx & ((1U << bits) - 1);
uint64_t low = job.root + (uint64_t(m) << 18);
const Position &p = positions[job.position];
Emitter emit{job.position, p.anchor, out, total};
if constexpr (Mode == SearchStage::Grouped) {
const uint32_t base = ((m >> 4) << 8) + (m & 15);
uint32_t mask = reverse_demo::groupMask(prepared[idx >> 13], base);
while (mask) {
const uint32_t j = __ffs(mask) - 1;
mask &= mask - 1;
const uint64_t candidate = job.root + (uint64_t(base + 16 * j) << 18);
sr::solveIntervals(candidate, p.cells, 25, emit);
}
} else if constexpr (Mode == SearchStage::Difference) {
if (sr::differenceFilter(low, p.cells, 25))
sr::solveIntervals(low, p.cells, 25, emit);
} else if constexpr (Mode == SearchStage::Precomputed) {
const Prepared &t = prepared[idx >> 17];
const uint32_t q0 = preparedQ(t, 0, m);
for (int i = 1; i < 25; ++i) {
const uint32_t r = ((preparedQ(t, i, m) - q0) & 0x7fffffffU) % 10;
if (r != 0 && r != 8)
return;
}
sr::solveIntervals(low, p.cells, 25, emit);
}
}
struct Device {
Prepared *prepared = nullptr;
size_t preparedCapacity = 0;
Position *positions = nullptr;
Job *jobs = nullptr;
Match *matches = nullptr;
unsigned long long *total = nullptr;
cudaEvent_t start, stop;
Device(const std::vector<Position> &p) {
CUDA(cudaMalloc(&positions, p.size() * sizeof(Position)));
CUDA(cudaMemcpy(positions, p.data(), p.size() * sizeof(Position), cudaMemcpyHostToDevice));
CUDA(cudaMalloc(&jobs, JOB_CAPACITY * sizeof(Job)));
CUDA(cudaMalloc(&matches, MATCH_CAPACITY * sizeof(Match)));
CUDA(cudaMalloc(&total, sizeof(*total)));
CUDA(cudaEventCreate(&start));
CUDA(cudaEventCreate(&stop));
}
~Device() {
cudaFree(prepared);
cudaFree(positions);
cudaFree(jobs);
cudaFree(matches);
cudaFree(total);
cudaEventDestroy(start);
cudaEventDestroy(stop);
}
float finish() {
CUDA(cudaGetLastError());
CUDA(cudaEventRecord(stop));
CUDA(cudaEventSynchronize(stop));
float ms;
CUDA(cudaEventElapsedTime(&ms, start, stop));
return ms;
}
uint64_t totalCount() {
unsigned long long n;
CUDA(cudaMemcpy(&n, total, sizeof(n), cudaMemcpyDeviceToHost));
return n;
}
float roots(uint32_t n) {
CUDA(cudaMemset(total, 0, sizeof(*total)));
CUDA(cudaEventRecord(start));
unsigned blocks = unsigned(((uint64_t(n) << 18) + 255) / 256);
rootKernel<<<blocks, 256>>>(positions, n, jobs, total);
return finish();
}
float search(uint32_t n, SearchStage mode) {
if (n > preparedCapacity) {
CUDA(cudaFree(prepared));
prepared = nullptr;
CUDA(cudaMalloc(&prepared, n * sizeof(Prepared)));
preparedCapacity = n;
}
CUDA(cudaMemset(total, 0, sizeof(*total)));
CUDA(cudaEventRecord(start));
unsigned blocks = unsigned(((uint64_t(n) << 17) + 255) / 256);
if (blocks) {
if (mode != SearchStage::Difference)
prepareKernel<<<(n + 127) / 128, 128>>>(positions, jobs, n, prepared);
if (mode == SearchStage::Difference)
searchKernel<SearchStage::Difference>
<<<blocks, 256>>>(positions, jobs, n, matches, total, prepared);
if (mode == SearchStage::Precomputed)
searchKernel<SearchStage::Precomputed>
<<<blocks, 256>>>(positions, jobs, n, matches, total, prepared);
if (mode == SearchStage::Grouped)
searchKernel<SearchStage::Grouped>
<<<unsigned(((uint64_t(n) << 13) + 255) / 256), 256>>>(
positions, jobs, n, matches, total, prepared);
}
return finish();
}
std::vector<Match> results() {
uint64_t n = totalCount();
if (n > MATCH_CAPACITY)
throw std::runtime_error("match overflow");
std::vector<Match> r(n);
CUDA(cudaMemcpy(r.data(), matches, n * sizeof(Match), cudaMemcpyDeviceToHost));
std::sort(r.begin(), r.end());
return r;
}
};

73
examples/test_reverse.py Normal file
View file

@ -0,0 +1,73 @@
#!/usr/bin/env python3
"""Check complete reverse variants and coordinate reuse with an independent oracle."""
import json
import re
from pathlib import Path
import subprocess
import statistics
import tempfile
from test_steps import slime
HERE = Path(__file__).resolve().parent
def run(binary, *args):
result = subprocess.run(
[str(HERE / 'bin' / binary), *map(str, args)],
capture_output=True, text=True, check=True, timeout=180,
)
return result.stdout
def main():
reverse = json.loads(run('reverse', 2))
reference = json.loads((HERE / 'data' / 'known-5x5.json').read_text())
assert reverse['anchor'] == reference['anchor']
assert reverse['roots'] == reference['roots'] and reverse['comparison_equal']
assert len(reverse['rows']) == 5
assert all(len(row['samples_ms']) == 2 for row in reverse['rows'])
assert all(abs(row['median_ms'] - statistics.median(row['samples_ms'])) < 1e-5
for row in reverse['rows'])
seeds = reverse['matches']
assert len(seeds) == len(set(seeds)) == 24
assert set(seeds) == set(reference['seeds'])
assert 61692151016558 in seeds
assert all(slime(seed, 51069 + x, 419124 + z)
for seed in seeds for x in range(5) for z in range(5))
with tempfile.TemporaryDirectory() as directory:
positions = Path(directory) / 'positions.txt'
# Repeated classes, negative coordinates and the known nonempty class.
positions.write_text('51069 419124\n116605 550196\n-14467 288052\n0 0\n65536 131072\n')
rows = [json.loads(line) for line in run('reuse', positions, 1).splitlines()]
for invalid in ['51069 419124\n1\n', '51069 419124 extra\n',
'2147483647 0\n', '-2147483649 0\n']:
positions.write_text(invalid)
result = subprocess.run([str(HERE / 'bin' / 'reuse'), str(positions), '1'],
capture_output=True, text=True, timeout=10)
assert result.returncode != 0 and ('input line' in result.stderr or 'fit int32' in result.stderr)
timings = [row for row in rows if row['type'] == 'pipeline']
assert {row['mode'] for row in timings} == {1, 2, 3}
validation = next(row for row in rows if row['type'] == 'validation')
assert validation['complete_roots_equal'] and validation['complete_matches_equal']
hits = validation['matches']
assert len(hits) == len(set(map(tuple, hits)))
assert {seed for seed, x, z in hits if (x, z) == (51069, 419124)} == set(seeds)
assert all(slime(seed, x + dx, z + dz)
for seed, x, z in hits for dx in range(5) for dz in range(5))
baseline = run('brute', '--x', 51069, '--z', 419124, '-n', 5,
'--start', 61692151016558, '--count', 16)
count = int(re.search(r'\bmatches=(\d+)', baseline)[1])
expected = sum(all(slime(seed, 51069 + dx, 419124 + dz)
for dx in range(5) for dz in range(5))
for seed in range(61692151016558, 61692151016558 + 16))
assert count == expected
for axis in ['--x', '--z']:
result = subprocess.run([str(HERE / 'bin' / 'brute'), axis, '2147483647', '--count', '1'],
capture_output=True, text=True, timeout=10)
assert result.returncode == 2
print(json.dumps({'reverse_seeds': len(seeds), 'reuse_matches': len(hits), 'passed': True}))
if __name__ == '__main__':
main()

139
examples/test_steps.py Normal file
View file

@ -0,0 +1,139 @@
#!/usr/bin/env python3
"""Compare complete tuples to an independent Python Java-arithmetic oracle."""
import argparse
import json
from pathlib import Path
import subprocess
import unittest
ROOT = Path(__file__).resolve().parent
GPU = False
A = 0x5DEECE66D
MASK = (1 << 48) - 1
XOR = 987234911
def i32(v):
v &= (1 << 32) - 1
return v - (1 << 32) if v >> 31 else v
def term(x, z):
return i32(x*x*4987142) + i32(x*5947611) + i32(z*z)*4392871 + i32(z*389711)
def first(seed, x, z):
state = ((seed + term(x, z)) ^ XOR ^ A) & MASK
return (state*A + 11) & MASK
def slime(seed, x, z):
state = first(seed, x, z)
while True:
q = state >> 17
if q < 2147483640:
return q % 10 == 0
state = (state*A + 11) & MASK
def oracle(seed, seeds, x0, z0, width, height, n):
return [[s, x, z] for s in range(seed, seed+seeds)
for x in range(x0, x0+width) for z in range(z0, z0+height)
if all(slime(s, x+dx, z+dz) for dx in range(n) for dz in range(n))]
def execute(binary, args, json_output=True):
result = subprocess.run([str(ROOT/'bin'/binary), *map(str, args)],
capture_output=True, text=True, timeout=60, check=True)
return json.loads(result.stdout) if json_output else result.stdout
def cli(case):
seed, seeds, x, z, width, height, n = case
return ['--seed', seed, '--seeds', seeds, '--x0', x, '--z0', z,
'--width', width, '--height', height, '-n', n, '--repeats', 1]
class Steps(unittest.TestCase):
def compare(self, case):
expected = oracle(*case)
self.assertEqual(execute('cpu_forward', cli(case))['hits'], expected)
if GPU:
result = execute('cuda_steps', cli(case))
self.assertTrue(result['comparison_equal'])
self.assertEqual(result['hits'], expected)
def test_nonzero_seed_and_nonblock_dimensions(self):
self.compare((1337, 7, -23, 17, 19, 21, 1))
def test_negative_and_overflow_coordinates(self):
self.compare((98765, 3, -1875000, 1874995, 17, 19, 2))
def test_int32_edges(self):
self.compare((42, 2, -2147483648, 2147483600, 17, 17, 2))
def test_known_hit_and_partial_tiles(self):
case = (61692151016558, 3, 51050, 419107, 37, 35, 5)
self.compare(case)
self.assertIn([61692151016558, 51069, 419124], oracle(*case))
def test_all_pattern_sizes(self):
for n in range(1, 9):
with self.subTest(n=n):
self.compare((61692151016558, 2, 51069, 419124, 3, 3, n))
def test_high16_equivalence_and_seed48_wrap(self):
base = (61692151016558, 2, 51060, 419115, 17, 19, 5)
high = (base[0]+(34567 << 48), *base[1:])
self.compare(high)
# Compare normalized seed labels, not raw world seed IDs.
normalized = [[s & MASK, x, z] for s, x, z in oracle(*high)]
self.assertEqual(normalized, oracle(*base))
self.compare((MASK-2, 7, -7, 5, 17, 19, 1))
def test_rejection_tail(self):
# Engineer each of Java's eight rejected first outputs and a successful redraw.
inv = pow(A, -1, 1 << 48)
for q in range(2147483640, 2147483648):
for suffix in range(10000):
v = (q << 17) | suffix
u = ((v-11)*inv) & MASK
seed = ((u ^ (XOR ^ A))-term(-31, 29)) & MASK
if slime(seed, -31, 29):
break
else:
self.fail('could not construct successful redraw')
self.assertEqual(first(seed, -31, 29) >> 17, q)
self.compare((seed, 1, -31, 29, 1, 1, 1))
def test_invalid_ranges_and_truncation(self):
invalid = [
['--width', 0], ['--repeats', 0], ['--seeds', 0],
['--seed', (1 << 64)-1, '--seeds', 2],
['--x0', 2147483647, '--width', 2],
['--seed', 0, '--seeds', 5, '-n', 1, '--capacity', 1],
]
for binary in ['cpu_forward'] + (['cuda_steps'] if GPU else []):
for args in invalid:
p = subprocess.run([str(ROOT/'bin'/binary), *map(str, args)],
capture_output=True, text=True, timeout=60)
self.assertNotEqual(p.returncode, 0, (binary, args))
def test_outer_tall_rectangle_fallback(self):
if not GPU:
self.skipTest('requires --gpu')
# More than 65535 tiles on Z: exercise the safe linear-grid fallback.
args = cli((61692151016558, 1, 51069, 0, 1, 1048561, 5))
cpu = execute('cpu_forward', args)
gpu = execute('cuda_steps', [*args, '--modes', '3,4'])
self.assertEqual(cpu['hits'], gpu['hits'])
self.assertIn([61692151016558, 51069, 419124], cpu['hits'])
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--gpu', action='store_true')
args, rest = parser.parse_known_args()
GPU = args.gpu
unittest.main(argv=[__file__, *rest], verbosity=2)