Initial release of slime chunk search blog examples
This commit is contained in:
commit
057215c3a2
47 changed files with 40361 additions and 0 deletions
2
bench/.gitignore
vendored
Normal file
2
bench/.gitignore
vendored
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
/bin/
|
||||
/__pycache__/
|
||||
21
bench/Makefile
Normal file
21
bench/Makefile
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
NVCC ?= nvcc
|
||||
CUDA_ARCH ?= 86
|
||||
NVCCFLAGS ?= -O3 -std=c++17
|
||||
TARGET := bin/slime-bench
|
||||
HEADERS := $(wildcard src/*.hpp src/*.cuh) ../include/slime/solver_core.hpp ../include/slime/upper_interval.hpp
|
||||
|
||||
.PHONY: all clean test test-gpu
|
||||
all: $(TARGET)
|
||||
$(TARGET): slime_bench.cu $(HEADERS) Makefile
|
||||
mkdir -p bin
|
||||
$(NVCC) $(NVCCFLAGS) -Xcompiler -pthread -gencode arch=compute_$(CUDA_ARCH),code=sm_$(CUDA_ARCH) -gencode arch=compute_$(CUDA_ARCH),code=compute_$(CUDA_ARCH) slime_bench.cu -o $@
|
||||
bin/test-math: test_math.cu $(HEADERS) Makefile
|
||||
mkdir -p bin
|
||||
$(NVCC) $(NVCCFLAGS) -Xcompiler -pthread test_math.cu -o $@
|
||||
test: $(TARGET) bin/test-math
|
||||
bin/test-math
|
||||
python3 test_cli.py
|
||||
test-gpu: $(TARGET)
|
||||
python3 test_cli.py --gpu
|
||||
clean:
|
||||
rm -f $(TARGET) bin/test-math
|
||||
67
bench/README.md
Normal file
67
bench/README.md
Normal file
|
|
@ -0,0 +1,67 @@
|
|||
# 图案搜索 CLI
|
||||
|
||||
搜索曼哈顿半径内每个锚点的有效 48 位种子,支持 NVIDIA 单卡、多卡及自定义图案。
|
||||
算法推导见[博客](https://yaossg.com/site/docs/slime),分步骤示例见 [examples/](../examples/README.md)。
|
||||
|
||||
## 使用
|
||||
|
||||
```sh
|
||||
make -C bench
|
||||
./bench/bin/slime-bench --help
|
||||
./bench/bin/slime-bench --list-devices
|
||||
./bench/bin/slime-bench --x 51069 --z 419124 --radius 0 --size 5 --max-results 100
|
||||
./bench/bin/slime-bench --radius 256 --pattern-file bench/patterns/heart-5x5.txt --devices all --max-results 1000
|
||||
```
|
||||
|
||||
`--radius` 必填,包含边界。锚点为图案左上角,图案可以伸出该菱形范围;不裁剪世界边界。
|
||||
`--size` 支持实心 1~6 方阵,默认 5。小图案可能产生极多匹配。
|
||||
|
||||
`--pattern '#?/##'` 或 `--pattern-file FILE` 指定图案:`#` 必须是史莱姆、`.` 必须不是、`?` 忽略。
|
||||
宽高各 1~64,至少有一个 `#`,不能与 `--size` 同时指定,不旋转或镜像。
|
||||
正约束参与候选筛选,负约束在输出时验证。以第一个 `#` 的坐标项归一化,返回坐标始终是图案左上角。
|
||||
|
||||
[爱心模板](patterns/heart-5x5.txt)的已知种子为 `22428888508636`,锚点 `(-5,-147)`;
|
||||
单点普通分支共有 1,181 个匹配。[苦力怕模板](patterns/creeper-6x6.txt)是图案输入示例,不保证在指定搜索范围内有解。
|
||||
|
||||
## 调度与输出
|
||||
|
||||
| 参数 | 默认值 | 用途 |
|
||||
| --- | --- | --- |
|
||||
| `--devices` | `0` | 设备索引列表(如 `0,1`)或 `all` |
|
||||
| `--position-batch` | `32` | 每次调度的锚点数,1~256 |
|
||||
| `--job-batch` | `2048` | 每次启动的根任务数,1~65536 |
|
||||
| `--cache-classes` | `4096` | 每设备 FIFO 根缓存,0 禁用 |
|
||||
| `--repeat` | `1` | 完整扫描轮数,每轮重新筛根 |
|
||||
| `--max-results` | `0` | 保存的样本上限,始终统计全部匹配 |
|
||||
| `--start-anchor` | `0` | 按曼哈顿行顺序编号的扫描起点 |
|
||||
| `--anchor-count` | 剩余全部 | 本次扫描的连续锚点数 |
|
||||
| `--output` | 无 | 同时保存 JSON,拒绝覆盖已有文件 |
|
||||
| `--dry-run` | 关闭 | 仅输出范围,不调用 CUDA |
|
||||
|
||||
标准输出为 JSON,进度写入标准错误。`matches` 是全部匹配数,`sample_truncated` 标明样本是否截断。
|
||||
`scan_wall_ms` 包含筛根、传输、搜索和回传,不含一次性设备初始化与显存分配;
|
||||
`elapsed_ms` 包含初始化、扫描和线程汇总。各设备的阶段时间会重叠,不能直接相加。
|
||||
|
||||
普通分支候选生成不包含拒绝重抽补扫。精确验证保证输出正确,但结果不能声明为严格完整目录。
|
||||
|
||||
## 代码结构
|
||||
|
||||
| 文件 | 职责 |
|
||||
| --- | --- |
|
||||
| `slime_bench.cu` | 主入口 |
|
||||
| `src/model.hpp` | 图案、配置、锚点与坐标项 |
|
||||
| `src/cli.hpp` | 帮助、参数解析和验证 |
|
||||
| `src/cuda_support.cuh` | CUDA 检查与设备缓冲区 |
|
||||
| `src/kernels.cuh` | 筛根、预计算、成组筛选和搜索 |
|
||||
| `src/worker.cuh` | 单设备批处理和根缓存 |
|
||||
| `src/runner.cuh` | 多设备调度与结果汇总 |
|
||||
| `src/report.cuh` | JSON 输出 |
|
||||
|
||||
数学实现共用 [include/slime/](../include/README.md)。内部头文件由单个 CUDA 编译单元包含。
|
||||
|
||||
```sh
|
||||
make -C bench test # 需要 nvcc,无需 GPU
|
||||
make -C bench test-gpu # 需要 GPU
|
||||
```
|
||||
|
||||
`testdata/` 只保存回归测试需要的图案、已知种子和预期计数;博客历史计时统一位于 [results/](../results/README.md)。
|
||||
6
bench/patterns/creeper-6x6.txt
Normal file
6
bench/patterns/creeper-6x6.txt
Normal file
|
|
@ -0,0 +1,6 @@
|
|||
##..##
|
||||
##..##
|
||||
..##..
|
||||
.####.
|
||||
.####.
|
||||
.#..#.
|
||||
5
bench/patterns/heart-5x5.txt
Normal file
5
bench/patterns/heart-5x5.txt
Normal file
|
|
@ -0,0 +1,5 @@
|
|||
.#.#.
|
||||
#####
|
||||
#####
|
||||
.###.
|
||||
..#..
|
||||
45
bench/slime_bench.cu
Normal file
45
bench/slime_bench.cu
Normal file
|
|
@ -0,0 +1,45 @@
|
|||
#include "src/cli.hpp"
|
||||
#include "src/report.cuh"
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
try {
|
||||
Config c;
|
||||
bool patternSet = false;
|
||||
if (!parseArguments(argc, argv, c, patternSet))
|
||||
return 0;
|
||||
if (c.list) {
|
||||
int n;
|
||||
CUDA(cudaGetDeviceCount(&n));
|
||||
for (int i = 0; i < n; ++i) {
|
||||
cudaDeviceProp p{};
|
||||
CUDA(cudaGetDeviceProperties(&p, i));
|
||||
std::cout << i << "\t" << p.name << "\tsm_" << p.major << p.minor << "\t"
|
||||
<< p.totalGlobalMem / (1ULL << 20) << " MiB\n";
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
auto report = scopeReport(c, patternSet);
|
||||
if (c.dry) {
|
||||
auto first = coordinate(c, c.startAnchor),
|
||||
last = coordinate(c, c.startAnchor + c.anchorCount - 1);
|
||||
report << ",\"first_anchor\":[" << first.x << "," << first.z << "],\"last_anchor\":["
|
||||
<< last.x << "," << last.z << "]}";
|
||||
} else {
|
||||
searchReport(c, report);
|
||||
}
|
||||
if (!c.output.empty()) {
|
||||
std::ofstream file(c.output);
|
||||
if (!file)
|
||||
throw std::runtime_error("cannot write report: " + c.output);
|
||||
file << report.str() << "\n";
|
||||
file.close();
|
||||
if (!file)
|
||||
throw std::runtime_error("failed writing report");
|
||||
}
|
||||
std::cout << report.str() << "\n";
|
||||
return 0;
|
||||
} catch (const std::exception &e) {
|
||||
std::cerr << "error: " << e.what() << "\n";
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
139
bench/src/cli.hpp
Normal file
139
bench/src/cli.hpp
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
#pragma once
|
||||
|
||||
#include "model.hpp"
|
||||
#include <fstream>
|
||||
#include <iostream>
|
||||
void help() {
|
||||
std::cout << R"(slime-bench --radius R [options]
|
||||
Search effective 48-bit seeds for slime chunk patterns.
|
||||
Ordinary candidate branch only; rejection-tail supplement is NOT included.
|
||||
|
||||
--x X --z Z Center chunk coordinates (default 0,0)
|
||||
--radius R Manhattan radius in chunks (required, >=0)
|
||||
--size N Solid square side, 1..6 (default 5)
|
||||
--pattern TEXT Rows separated by /; # slime, . non-slime, ? ignored
|
||||
--pattern-file FILE Same pattern, one row per line (dimensions 1..64)
|
||||
Requires at least one #; exclusive with --size
|
||||
--devices 0,1,... CUDA device indices, or all (default 0)
|
||||
--start-anchor N Start at this zero-based anchor index (default 0)
|
||||
--anchor-count N Scan only N anchors from start (default remaining)
|
||||
--repeat N Complete passes; fresh root cache each pass (default 1)
|
||||
--position-batch N Anchors per scheduled batch, 1..256 (default 32)
|
||||
--job-batch N Low18-root jobs per GPU launch, 1..65536 (default 2048)
|
||||
--cache-classes N Per-GPU bounded FIFO root cache entries (default 4096)
|
||||
--max-results N Save up to N example matches; count ALL (default 0)
|
||||
--output FILE Also save the complete JSON report (file must not exist)
|
||||
--dry-run Print scope JSON without using CUDA
|
||||
--list-devices List visible CUDA devices
|
||||
--help Show this help
|
||||
|
||||
Scope: abs(anchor_x-X)+abs(anchor_z-Z)<=R, including boundary.
|
||||
Anchor is the minimum-x/minimum-z corner; the square may extend outside
|
||||
this diamond. Coordinates are not clipped to Minecraft's world border.
|
||||
Small squares can have enormous numbers of matching seeds and take very long.
|
||||
)";
|
||||
}
|
||||
|
||||
bool parseArguments(int argc, char **argv, Config &c, bool &patternSet) {
|
||||
bool radiusSet = false, sizeSet = false;
|
||||
std::string patternText;
|
||||
patternSet = false;
|
||||
for (int i = 1; i < argc; ++i) {
|
||||
std::string a = argv[i];
|
||||
if (a == "--help" || a == "-h") {
|
||||
help();
|
||||
return false;
|
||||
}
|
||||
if (a == "--dry-run") {
|
||||
c.dry = true;
|
||||
continue;
|
||||
}
|
||||
if (a == "--list-devices") {
|
||||
c.list = true;
|
||||
continue;
|
||||
}
|
||||
if (i + 1 >= argc)
|
||||
throw std::runtime_error("missing value for " + a);
|
||||
std::string v = argv[++i];
|
||||
auto bounded = [&](uint64_t lo, uint64_t hi) {
|
||||
auto n = number(v);
|
||||
if (n < lo || n > hi)
|
||||
throw std::runtime_error("out of range: " + a);
|
||||
return n;
|
||||
};
|
||||
if (a == "--x")
|
||||
c.x = signed32(v);
|
||||
else if (a == "--z")
|
||||
c.z = signed32(v);
|
||||
else if (a == "--radius") {
|
||||
c.radius = bounded(0, INT32_MAX);
|
||||
radiusSet = true;
|
||||
} else if (a == "--size") {
|
||||
c.size = bounded(1, 6);
|
||||
sizeSet = true;
|
||||
} else if (a == "--pattern" || a == "--pattern-file") {
|
||||
if (patternSet)
|
||||
throw std::runtime_error("specify only one pattern");
|
||||
patternSet = true;
|
||||
if (a == "--pattern")
|
||||
patternText = v;
|
||||
else {
|
||||
std::ifstream file(v);
|
||||
if (!file)
|
||||
throw std::runtime_error("cannot read pattern: " + v);
|
||||
std::ostringstream text;
|
||||
text << file.rdbuf();
|
||||
patternText = text.str();
|
||||
}
|
||||
} else if (a == "--devices")
|
||||
c.devices = v;
|
||||
else if (a == "--repeat")
|
||||
c.repeats = bounded(1, 1000);
|
||||
else if (a == "--start-anchor")
|
||||
c.startAnchor = number(v);
|
||||
else if (a == "--anchor-count") {
|
||||
c.anchorCount = number(v);
|
||||
c.countSet = true;
|
||||
} else if (a == "--position-batch")
|
||||
c.positionBatch = bounded(1, 256);
|
||||
else if (a == "--job-batch")
|
||||
c.jobBatch = bounded(1, 65536);
|
||||
else if (a == "--cache-classes")
|
||||
c.cacheClasses = bounded(0, 1000000);
|
||||
else if (a == "--max-results")
|
||||
c.maxResults = bounded(0, 1000000);
|
||||
else if (a == "--output")
|
||||
c.output = v;
|
||||
else
|
||||
throw std::runtime_error("unknown option: " + a);
|
||||
}
|
||||
|
||||
if (c.list)
|
||||
return true;
|
||||
if (!radiusSet)
|
||||
throw std::runtime_error("--radius is required");
|
||||
if (patternSet && sizeSet)
|
||||
throw std::runtime_error("--size and pattern options are mutually exclusive");
|
||||
if (!patternSet) {
|
||||
for (int z = 0; z < c.size; ++z) {
|
||||
if (z)
|
||||
patternText += '/';
|
||||
patternText += std::string(c.size, '#');
|
||||
}
|
||||
}
|
||||
c.pattern = parsePattern(patternText);
|
||||
for (auto axis : {std::make_pair(c.x, c.pattern.width), std::make_pair(c.z, c.pattern.height)})
|
||||
if (int64_t(axis.first) - int64_t(c.radius) < INT32_MIN ||
|
||||
int64_t(axis.first) + int64_t(c.radius) + axis.second - 1 > INT32_MAX)
|
||||
throw std::runtime_error("coordinates including pattern must fit int32");
|
||||
if (c.startAnchor >= anchors(c.radius))
|
||||
throw std::runtime_error("start anchor outside range");
|
||||
if (!c.countSet)
|
||||
c.anchorCount = anchors(c.radius) - c.startAnchor;
|
||||
if (!c.anchorCount || c.anchorCount > anchors(c.radius) - c.startAnchor)
|
||||
throw std::runtime_error("anchor count outside range");
|
||||
if (!c.output.empty() && std::ifstream(c.output).good())
|
||||
throw std::runtime_error("output already exists: " + c.output);
|
||||
|
||||
return true;
|
||||
}
|
||||
23
bench/src/cuda_support.cuh
Normal file
23
bench/src/cuda_support.cuh
Normal file
|
|
@ -0,0 +1,23 @@
|
|||
#pragma once
|
||||
|
||||
#include <cuda_runtime.h>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#define CUDA(call) \
|
||||
do { \
|
||||
cudaError_t status_ = (call); \
|
||||
if (status_ != cudaSuccess) \
|
||||
throw std::runtime_error(std::string(#call) + ": " + cudaGetErrorString(status_)); \
|
||||
} while (0)
|
||||
template <class T> struct Buffer {
|
||||
T *p = nullptr;
|
||||
explicit Buffer(size_t n) {
|
||||
if (n)
|
||||
CUDA(cudaMalloc(&p, n * sizeof(T)));
|
||||
}
|
||||
~Buffer() {
|
||||
if (p)
|
||||
cudaFree(p);
|
||||
}
|
||||
Buffer(const Buffer &) = delete;
|
||||
};
|
||||
89
bench/src/kernels.cuh
Normal file
89
bench/src/kernels.cuh
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
#pragma once
|
||||
|
||||
#include "model.hpp"
|
||||
#include "cuda_support.cuh"
|
||||
__global__ void rootsKernel(const sr::CellTerm *cells, uint32_t positions, int count, int positive,
|
||||
Job *out, unsigned long long *total) {
|
||||
uint64_t t = uint64_t(blockIdx.x) * blockDim.x + threadIdx.x;
|
||||
if (t >= (uint64_t(positions) << 18))
|
||||
return;
|
||||
uint32_t pos = t >> 18, root = t & 262143;
|
||||
const auto *p = cells + uint64_t(pos) * count;
|
||||
for (int i = 0; i < positive; ++i)
|
||||
if ((((root + uint32_t(p[i].term)) ^ uint32_t(sr::kCombinedXor)) *
|
||||
uint32_t(sr::kJavaMultiplier) +
|
||||
11U) &
|
||||
(1U << 17))
|
||||
return;
|
||||
out[atomicAdd(total, 1ULL)] = {pos, root};
|
||||
}
|
||||
__global__ void prepareKernel(const sr::CellTerm *cells, const Job *jobs, uint32_t n, int count,
|
||||
int positive, uint32_t *prepared) {
|
||||
uint32_t k = blockIdx.x * blockDim.x + threadIdx.x;
|
||||
if (k >= n)
|
||||
return;
|
||||
const auto job = jobs[k];
|
||||
for (int i = 0; i < positive; ++i) {
|
||||
uint64_t a = job.root + cells[uint64_t(job.position) * count + i].term;
|
||||
prepared[(uint64_t(k) * count + i) * 2] = a >> 18;
|
||||
prepared[(uint64_t(k) * count + i) * 2 + 1] =
|
||||
((((a ^ sr::kCombinedXor) & 262143) * sr::kJavaMultiplier + 11) >> 17);
|
||||
}
|
||||
}
|
||||
__host__ __device__ __forceinline__ uint32_t q(const uint32_t *p, int i, uint32_t m) {
|
||||
return (p[2 * i + 1] + 2U * uint32_t(sr::kJavaMultiplier) *
|
||||
((m + p[2 * i]) ^ uint32_t(sr::kCombinedXor >> 18))) &
|
||||
0x7fffffffU;
|
||||
}
|
||||
__host__ __device__ uint32_t groupMask(const uint32_t *p, uint32_t base, int count) {
|
||||
uint32_t mask = 65535, q0 = q(p, 0, base), qe = q(p, 0, base + 240);
|
||||
for (int i = 1; i < count && mask; ++i) {
|
||||
uint32_t cut = (256 - ((base + p[2 * i]) & 255) + 15) >> 4, lo = (1U << cut) - 1;
|
||||
uint32_t r0 = ((q(p, i, base) - q0) & 0x7fffffffU) % 10,
|
||||
r1 = ((q(p, i, base + 240) - qe) & 0x7fffffffU) % 10;
|
||||
mask &= ((r0 == 0 || r0 == 8) ? lo : 0U) | ((r1 == 0 || r1 == 8) ? (65535U ^ lo) : 0U);
|
||||
}
|
||||
return mask;
|
||||
}
|
||||
struct Emit {
|
||||
Coord p;
|
||||
uint64_t originTerm;
|
||||
const sr::CellTerm *negative;
|
||||
int negativeCount;
|
||||
Match *out;
|
||||
uint64_t capacity;
|
||||
unsigned long long *total;
|
||||
__device__ void operator()(uint64_t seed) {
|
||||
if (!sr::verifyPattern(seed, negative, negativeCount))
|
||||
return;
|
||||
uint64_t slot = atomicAdd(total, 1ULL);
|
||||
if (slot < capacity)
|
||||
out[slot] = {(seed - originTerm) & sr::kMask48, p.x, p.z};
|
||||
}
|
||||
};
|
||||
__global__ void searchKernel(const sr::CellTerm *cells, const Coord *coords, const Job *jobs,
|
||||
uint32_t n, int count, int positive, int originX, int originZ,
|
||||
const uint32_t *prepared, Match *out, uint64_t capacity,
|
||||
unsigned long long *total) {
|
||||
uint64_t index = uint64_t(blockIdx.x) * blockDim.x + threadIdx.x;
|
||||
if (index >= (uint64_t(n) << 13))
|
||||
return;
|
||||
uint32_t g = index & 8191, k = index >> 13, base = ((g >> 4) << 8) + (g & 15);
|
||||
const uint32_t *p = prepared + uint64_t(k) * count * 2;
|
||||
uint32_t mask = groupMask(p, base, positive);
|
||||
Job job = jobs[k];
|
||||
Coord origin = coords[job.position];
|
||||
Emit emit{origin,
|
||||
sr::coordinateTerm(origin.x + originX, origin.z + originZ),
|
||||
cells + uint64_t(job.position) * count + positive,
|
||||
count - positive,
|
||||
out,
|
||||
capacity,
|
||||
total};
|
||||
while (mask) {
|
||||
uint32_t j = __ffs(mask) - 1;
|
||||
mask &= mask - 1;
|
||||
sr::solveIntervals(job.root + (uint64_t(base + 16 * j) << 18),
|
||||
cells + uint64_t(job.position) * count, positive, emit);
|
||||
}
|
||||
}
|
||||
137
bench/src/model.hpp
Normal file
137
bench/src/model.hpp
Normal file
|
|
@ -0,0 +1,137 @@
|
|||
#pragma once
|
||||
|
||||
#include "../../include/slime/upper_interval.hpp"
|
||||
#include <algorithm>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <sstream>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace sr = slime;
|
||||
struct Coord {
|
||||
int32_t x, z;
|
||||
};
|
||||
struct Job {
|
||||
uint32_t position, root;
|
||||
};
|
||||
struct Match {
|
||||
uint64_t seed;
|
||||
int32_t x, z;
|
||||
};
|
||||
struct PatternCell {
|
||||
int x, z;
|
||||
uint8_t requirement;
|
||||
};
|
||||
struct Pattern {
|
||||
int width = 0, height = 0, positive = 0;
|
||||
std::vector<std::string> rows;
|
||||
std::vector<PatternCell> cells;
|
||||
};
|
||||
Pattern parsePattern(std::string text) {
|
||||
std::replace(text.begin(), text.end(), '/', '\n');
|
||||
Pattern p;
|
||||
std::stringstream input(text);
|
||||
std::string row;
|
||||
while (std::getline(input, row)) {
|
||||
if (!row.empty() && row.back() == '\r')
|
||||
row.pop_back();
|
||||
if (row.empty())
|
||||
throw std::runtime_error("empty pattern row");
|
||||
p.rows.push_back(row);
|
||||
}
|
||||
if (p.rows.empty())
|
||||
throw std::runtime_error("empty pattern");
|
||||
p.width = p.rows[0].size();
|
||||
p.height = p.rows.size();
|
||||
if (p.width > 64 || p.height > 64)
|
||||
throw std::runtime_error("pattern dimensions must be 1..64");
|
||||
for (auto &r : p.rows)
|
||||
if (r.size() != size_t(p.width))
|
||||
throw std::runtime_error("pattern rows must have equal width");
|
||||
for (char wanted : {'#', '.'})
|
||||
for (int z = 0; z < p.height; ++z)
|
||||
for (int x = 0; x < p.width; ++x) {
|
||||
char ch = p.rows[z][x];
|
||||
if (ch != '#' && ch != '.' && ch != '?')
|
||||
throw std::runtime_error("pattern characters must be #, . or ?");
|
||||
if (ch == wanted)
|
||||
p.cells.push_back({x, z, uint8_t(ch == '#' ? sr::kSlime : sr::kNonSlime)});
|
||||
if (wanted == '#' && ch == '#')
|
||||
++p.positive;
|
||||
}
|
||||
if (!p.positive)
|
||||
throw std::runtime_error("pattern requires at least one # cell");
|
||||
return p;
|
||||
}
|
||||
struct Config {
|
||||
Pattern pattern;
|
||||
int32_t x = 0, z = 0;
|
||||
uint64_t radius = 0;
|
||||
int size = 5, positionBatch = 32, jobBatch = 2048, repeats = 1;
|
||||
uint64_t startAnchor = 0, anchorCount = 0;
|
||||
bool countSet = false;
|
||||
uint64_t maxResults = 0;
|
||||
size_t cacheClasses = 4096;
|
||||
std::string devices = "0", output;
|
||||
bool dry = false, list = false;
|
||||
};
|
||||
uint64_t number(const std::string &s) {
|
||||
size_t used = 0;
|
||||
if (s.empty() || s[0] == '-')
|
||||
throw std::runtime_error("expected nonnegative integer: " + s);
|
||||
auto n = std::stoull(s, &used);
|
||||
if (used != s.size())
|
||||
throw std::runtime_error("invalid integer: " + s);
|
||||
return n;
|
||||
}
|
||||
int32_t signed32(const std::string &s) {
|
||||
size_t used = 0;
|
||||
auto n = std::stoll(s, &used);
|
||||
if (used != s.size() || n < INT32_MIN || n > INT32_MAX)
|
||||
throw std::runtime_error("invalid int32 coordinate");
|
||||
return int32_t(n);
|
||||
}
|
||||
uint64_t anchors(uint64_t r) { return 1 + 2 * r * (r + 1); }
|
||||
uint64_t isqrt(uint64_t v) {
|
||||
uint64_t r = std::sqrt(double(v));
|
||||
while ((r + 1) * (r + 1) <= v)
|
||||
++r;
|
||||
while (r * r > v)
|
||||
--r;
|
||||
return r;
|
||||
}
|
||||
Coord coordinate(const Config &c, uint64_t index) {
|
||||
uint64_t top = (c.radius + 1) * (c.radius + 1);
|
||||
int64_t dx, dz;
|
||||
if (index < top) {
|
||||
uint64_t row = isqrt(index);
|
||||
dz = int64_t(row) - c.radius;
|
||||
dx = int64_t(index - row * row) - int64_t(row);
|
||||
} else {
|
||||
uint64_t back = anchors(c.radius) - 1 - index, row = isqrt(back);
|
||||
dz = int64_t(c.radius) - row;
|
||||
dx = int64_t(row) - int64_t(back - row * row);
|
||||
}
|
||||
return {int32_t(int64_t(c.x) + dx), int32_t(int64_t(c.z) + dz)};
|
||||
}
|
||||
uint64_t classKey(Coord p) {
|
||||
return (uint64_t(uint32_t(p.x) & 65535) << 17) | (uint32_t(p.z) & 131071);
|
||||
}
|
||||
void terms(Coord p, int n, sr::CellTerm *out) {
|
||||
uint64_t anchor = sr::coordinateTerm(p.x, p.z);
|
||||
for (int z = 0; z < n; ++z)
|
||||
for (int x = 0; x < n; ++x)
|
||||
out[z * n + x] = {(sr::coordinateTerm(p.x + x, p.z + z) - anchor) & sr::kMask48,
|
||||
sr::kSlime};
|
||||
}
|
||||
void terms(Coord p, const Pattern &pattern, sr::CellTerm *out) {
|
||||
// The grouped filter needs its first positive term to be zero.
|
||||
auto first = pattern.cells.front();
|
||||
uint64_t anchor = sr::coordinateTerm(p.x + first.x, p.z + first.z);
|
||||
size_t i = 0;
|
||||
for (auto cell : pattern.cells)
|
||||
out[i++] = {(sr::coordinateTerm(p.x + cell.x, p.z + cell.z) - anchor) & sr::kMask48,
|
||||
cell.requirement};
|
||||
}
|
||||
96
bench/src/report.cuh
Normal file
96
bench/src/report.cuh
Normal file
|
|
@ -0,0 +1,96 @@
|
|||
#pragma once
|
||||
|
||||
#include "runner.cuh"
|
||||
#include <iomanip>
|
||||
#include <iostream>
|
||||
std::string escape(const std::string &s) {
|
||||
std::ostringstream o;
|
||||
for (unsigned char ch : s) {
|
||||
if (ch == '"' || ch == '\\')
|
||||
o << '\\' << char(ch);
|
||||
else if (ch < 32)
|
||||
o << "\\u" << std::hex << std::setw(4) << std::setfill('0') << int(ch) << std::dec;
|
||||
else
|
||||
o << char(ch);
|
||||
}
|
||||
return o.str();
|
||||
}
|
||||
|
||||
std::ostringstream scopeReport(const Config &c, bool patternSet) {
|
||||
std::ostringstream report;
|
||||
report << std::setprecision(12)
|
||||
<< "{\"schema_version\":1,\"mode\":\"ordinary_all_effective_seeds\",\"rejection_tail_"
|
||||
"included\":false,\"center\":["
|
||||
<< c.x << "," << c.z << "],\"radius_chunks\":" << c.radius
|
||||
<< ",\"square_size\":" << (patternSet ? "null" : std::to_string(c.size))
|
||||
<< ",\"anchors\":" << anchors(c.radius)
|
||||
<< ",\"effective_seed_bits\":48,\"dry_run\":" << (c.dry ? "true" : "false");
|
||||
report << ",\"start_anchor\":" << c.startAnchor << ",\"anchor_count\":" << c.anchorCount;
|
||||
report << ",\"pattern_width\":" << c.pattern.width << ",\"pattern_height\":" << c.pattern.height
|
||||
<< ",\"slime_cells\":" << c.pattern.positive
|
||||
<< ",\"non_slime_cells\":" << c.pattern.cells.size() - c.pattern.positive
|
||||
<< ",\"pattern\":[";
|
||||
for (size_t i = 0; i < c.pattern.rows.size(); ++i) {
|
||||
if (i)
|
||||
report << ",";
|
||||
report << "\"" << c.pattern.rows[i] << "\"";
|
||||
}
|
||||
report << "]";
|
||||
|
||||
return report;
|
||||
}
|
||||
|
||||
void searchReport(const Config &c, std::ostringstream &report) {
|
||||
auto devices = selectDevices(c);
|
||||
report << ",\"position_batch\":" << c.positionBatch << ",\"job_batch\":" << c.jobBatch
|
||||
<< ",\"cache_classes\":" << c.cacheClasses
|
||||
<< ",\"cuda_runtime_version\":" << CUDART_VERSION << ",\"rounds\":[";
|
||||
std::vector<double> timings;
|
||||
uint64_t expected = 0;
|
||||
for (int round = 0; round < c.repeats; ++round) {
|
||||
auto result = runRound(c, devices, round);
|
||||
const auto &metrics = result.metrics;
|
||||
const auto &sample = result.sample;
|
||||
const auto visited = result.visited, jobs = result.jobs, matches = result.matches;
|
||||
const double elapsed = result.elapsed, scan = result.scan;
|
||||
if (round && matches != expected)
|
||||
throw std::runtime_error("repeat match count mismatch");
|
||||
expected = matches;
|
||||
timings.push_back(scan);
|
||||
if (round)
|
||||
report << ",";
|
||||
report << "{\"round\":" << round + 1 << ",\"elapsed_ms\":" << elapsed
|
||||
<< ",\"scan_wall_ms\":" << scan
|
||||
<< ",\"anchors_per_second\":" << visited / (scan / 1000) << ",\"root_jobs\":" << jobs
|
||||
<< ",\"matches\":" << matches
|
||||
<< ",\"sample_truncated\":" << (matches > sample.size() ? "true" : "false")
|
||||
<< ",\"sample\":[";
|
||||
for (size_t i = 0; i < sample.size(); ++i) {
|
||||
if (i)
|
||||
report << ",";
|
||||
auto m = sample[i];
|
||||
report << "[" << m.seed << "," << m.x << "," << m.z << "]";
|
||||
}
|
||||
report << "],\"gpus\":[";
|
||||
for (size_t i = 0; i < metrics.size(); ++i) {
|
||||
if (i)
|
||||
report << ",";
|
||||
auto &m = metrics[i];
|
||||
report << "{\"device\":" << m.device << ",\"name\":\"" << escape(m.name)
|
||||
<< "\",\"anchors\":" << m.positions
|
||||
<< ",\"root_classes_generated\":" << m.classes
|
||||
<< ",\"cache_hits\":" << m.cacheHits << ",\"root_jobs\":" << m.jobs
|
||||
<< ",\"matches\":" << m.matches << ",\"setup_ms\":" << m.setupMs
|
||||
<< ",\"scan_ms\":" << m.scanMs << ",\"root_stage_ms\":" << m.rootMs
|
||||
<< ",\"search_stage_ms\":" << m.searchMs << "}";
|
||||
}
|
||||
report << "]}";
|
||||
std::cerr << "round " << round + 1 << "/" << c.repeats << ": " << visited << " anchors, "
|
||||
<< matches << " matches, scan " << scan << " ms, elapsed " << elapsed << " ms\n";
|
||||
}
|
||||
std::sort(timings.begin(), timings.end());
|
||||
double median = timings[timings.size() / 2];
|
||||
if (timings.size() % 2 == 0)
|
||||
median = (median + timings[timings.size() / 2 - 1]) / 2;
|
||||
report << "],\"median_scan_wall_ms\":" << median << "}";
|
||||
}
|
||||
84
bench/src/runner.cuh
Normal file
84
bench/src/runner.cuh
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
#pragma once
|
||||
|
||||
#include "worker.cuh"
|
||||
#include <iostream>
|
||||
#include <set>
|
||||
#include <thread>
|
||||
|
||||
std::vector<int> selectDevices(const Config &c) {
|
||||
int available;
|
||||
CUDA(cudaGetDeviceCount(&available));
|
||||
std::vector<int> devices;
|
||||
if (c.devices == "all") {
|
||||
for (int i = 0; i < available; ++i)
|
||||
devices.push_back(i);
|
||||
} else {
|
||||
std::stringstream ss(c.devices);
|
||||
std::string v;
|
||||
while (std::getline(ss, v, ',')) {
|
||||
auto id = number(v);
|
||||
if (id >= uint64_t(available))
|
||||
throw std::runtime_error("CUDA device unavailable: " + v);
|
||||
devices.push_back(id);
|
||||
}
|
||||
}
|
||||
if (devices.empty() || std::set<int>(devices.begin(), devices.end()).size() != devices.size())
|
||||
throw std::runtime_error("device list must be nonempty and unique");
|
||||
return devices;
|
||||
}
|
||||
|
||||
struct RoundResult {
|
||||
std::vector<Metrics> metrics;
|
||||
uint64_t visited = 0, jobs = 0, matches = 0;
|
||||
std::vector<Match> sample;
|
||||
double elapsed = 0, scan = 0;
|
||||
};
|
||||
|
||||
RoundResult runRound(const Config &c, const std::vector<int> &devices, int round) {
|
||||
RoundResult result;
|
||||
Shared shared;
|
||||
shared.next = c.startAnchor;
|
||||
shared.workerCount = devices.size();
|
||||
result.metrics.resize(devices.size());
|
||||
auto &metrics = result.metrics;
|
||||
std::vector<std::thread> workers;
|
||||
auto start = Clock::now();
|
||||
for (size_t i = 0; i < devices.size(); ++i)
|
||||
workers.emplace_back([&, i]() {
|
||||
worker(c, devices[i], shared, metrics[i]);
|
||||
++shared.finished;
|
||||
shared.cv.notify_all();
|
||||
});
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(shared.mutex);
|
||||
while (shared.finished < int(devices.size())) {
|
||||
if (!shared.cv.wait_for(lock, std::chrono::seconds(5),
|
||||
[&]() { return shared.finished == int(devices.size()); }))
|
||||
std::cerr << "progress: " << shared.done << "/" << c.anchorCount
|
||||
<< " anchors (round " << round + 1 << ")\n";
|
||||
}
|
||||
}
|
||||
for (auto &t : workers)
|
||||
t.join();
|
||||
if (!shared.error.empty())
|
||||
throw std::runtime_error(shared.error);
|
||||
result.elapsed = std::chrono::duration<double, std::milli>(Clock::now() - start).count();
|
||||
auto first = metrics[0].start, last = metrics[0].end;
|
||||
|
||||
for (auto &m : metrics) {
|
||||
first = std::min(first, m.start);
|
||||
last = std::max(last, m.end);
|
||||
result.visited += m.positions;
|
||||
result.jobs += m.jobs;
|
||||
if (m.matches > UINT64_MAX - result.matches)
|
||||
throw std::runtime_error("total match count exceeds uint64");
|
||||
result.matches += m.matches;
|
||||
for (auto hit : m.sample)
|
||||
if (result.sample.size() < c.maxResults)
|
||||
result.sample.push_back(hit);
|
||||
}
|
||||
if (result.visited != c.anchorCount)
|
||||
throw std::runtime_error("incomplete anchor coverage");
|
||||
result.scan = std::chrono::duration<double, std::milli>(last - first).count();
|
||||
return result;
|
||||
}
|
||||
197
bench/src/worker.cuh
Normal file
197
bench/src/worker.cuh
Normal file
|
|
@ -0,0 +1,197 @@
|
|||
#pragma once
|
||||
|
||||
#include "kernels.cuh"
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <condition_variable>
|
||||
#include <deque>
|
||||
#include <map>
|
||||
#include <mutex>
|
||||
|
||||
using Clock = std::chrono::steady_clock;
|
||||
struct Metrics {
|
||||
int device;
|
||||
std::string name;
|
||||
uint64_t positions = 0, classes = 0, cacheHits = 0, jobs = 0, matches = 0;
|
||||
double setupMs = 0, scanMs = 0, rootMs = 0, searchMs = 0;
|
||||
Clock::time_point start, end;
|
||||
std::vector<Match> sample;
|
||||
};
|
||||
struct Shared {
|
||||
std::atomic<uint64_t> next{0}, done{0};
|
||||
std::atomic<int> finished{0};
|
||||
int ready = 0, workerCount = 0;
|
||||
std::condition_variable cv;
|
||||
std::atomic<bool> cancel{false};
|
||||
std::mutex mutex;
|
||||
std::string error;
|
||||
};
|
||||
void worker(const Config &c, int device, Shared &shared, Metrics &result) {
|
||||
try {
|
||||
auto setup = Clock::now();
|
||||
CUDA(cudaSetDevice(device));
|
||||
cudaDeviceProp prop{};
|
||||
CUDA(cudaGetDeviceProperties(&prop, device));
|
||||
result.device = device;
|
||||
result.name = prop.name;
|
||||
int count = c.pattern.cells.size(), positive = c.pattern.positive;
|
||||
size_t rootsCapacity = size_t(c.positionBatch) * (1U << 17);
|
||||
Buffer<sr::CellTerm> dcells(size_t(c.positionBatch) * count);
|
||||
Buffer<Coord> dcoords(c.positionBatch);
|
||||
Buffer<Job> droots(rootsCapacity), djobs(c.jobBatch);
|
||||
Buffer<uint32_t> prep(size_t(c.jobBatch) * count * 2);
|
||||
Buffer<unsigned long long> total(1);
|
||||
Buffer<Match> matches(c.maxResults);
|
||||
std::map<uint64_t, std::vector<uint32_t>> cache;
|
||||
std::deque<uint64_t> fifo;
|
||||
size_t cachedRoots = 0;
|
||||
result.setupMs = std::chrono::duration<double, std::milli>(Clock::now() - setup).count();
|
||||
{
|
||||
std::unique_lock<std::mutex> lock(shared.mutex);
|
||||
++shared.ready;
|
||||
shared.cv.notify_all();
|
||||
shared.cv.wait(
|
||||
lock, [&]() { return shared.ready == shared.workerCount || shared.cancel.load(); });
|
||||
if (shared.cancel)
|
||||
return;
|
||||
}
|
||||
result.start = Clock::now();
|
||||
const uint64_t end = c.startAnchor + c.anchorCount;
|
||||
while (!shared.cancel) {
|
||||
uint64_t first = shared.next.fetch_add(c.positionBatch);
|
||||
if (first >= end)
|
||||
break;
|
||||
uint32_t num = std::min<uint64_t>(c.positionBatch, end - first);
|
||||
std::vector<Coord> coords;
|
||||
std::vector<uint64_t> keys;
|
||||
std::map<uint64_t, std::vector<uint32_t>> lists;
|
||||
std::vector<Coord> missing;
|
||||
std::vector<uint64_t> missingKeys;
|
||||
for (uint32_t i = 0; i < num; ++i) {
|
||||
Coord p = coordinate(c, first + i);
|
||||
coords.push_back(p);
|
||||
uint64_t key = classKey(p);
|
||||
keys.push_back(key);
|
||||
if (lists.count(key)) {
|
||||
++result.cacheHits;
|
||||
continue;
|
||||
}
|
||||
auto it = cache.find(key);
|
||||
if (it != cache.end()) {
|
||||
lists[key] = it->second;
|
||||
++result.cacheHits;
|
||||
} else {
|
||||
lists[key] = {};
|
||||
missing.push_back(p);
|
||||
missingKeys.push_back(key);
|
||||
}
|
||||
}
|
||||
if (!missing.empty()) {
|
||||
auto start = Clock::now();
|
||||
std::vector<sr::CellTerm> cells(missing.size() * count);
|
||||
for (size_t i = 0; i < missing.size(); ++i)
|
||||
terms(missing[i], c.pattern, cells.data() + i * count);
|
||||
CUDA(cudaMemcpy(dcells.p, cells.data(), cells.size() * sizeof(sr::CellTerm),
|
||||
cudaMemcpyHostToDevice));
|
||||
CUDA(cudaMemset(total.p, 0, sizeof(*total.p)));
|
||||
rootsKernel<<<unsigned((uint64_t(missing.size()) << 18) / 256), 256>>>(
|
||||
dcells.p, missing.size(), count, positive, droots.p, total.p);
|
||||
CUDA(cudaGetLastError());
|
||||
unsigned long long found;
|
||||
CUDA(cudaMemcpy(&found, total.p, sizeof(found), cudaMemcpyDeviceToHost));
|
||||
if (found > rootsCapacity)
|
||||
throw std::runtime_error("root capacity invariant failed");
|
||||
std::vector<Job> roots(found);
|
||||
if (found)
|
||||
CUDA(cudaMemcpy(roots.data(), droots.p, found * sizeof(Job),
|
||||
cudaMemcpyDeviceToHost));
|
||||
for (auto job : roots)
|
||||
lists[missingKeys[job.position]].push_back(job.root);
|
||||
result.classes += missing.size();
|
||||
for (auto key : missingKeys) {
|
||||
auto &list = lists[key];
|
||||
std::sort(list.begin(), list.end());
|
||||
if (c.cacheClasses) {
|
||||
while (!fifo.empty() && (cache.size() >= c.cacheClasses ||
|
||||
cachedRoots + list.size() > (1U << 20))) {
|
||||
auto old = fifo.front();
|
||||
fifo.pop_front();
|
||||
cachedRoots -= cache.at(old).size();
|
||||
cache.erase(old);
|
||||
}
|
||||
cache[key] = list;
|
||||
cachedRoots += list.size();
|
||||
fifo.push_back(key);
|
||||
}
|
||||
}
|
||||
result.rootMs +=
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - start).count();
|
||||
}
|
||||
// Construct concrete positions only for classes with roots.
|
||||
std::vector<Coord> active;
|
||||
std::vector<sr::CellTerm> cells;
|
||||
std::vector<Job> jobs;
|
||||
jobs.reserve(c.jobBatch);
|
||||
for (uint32_t i = 0; i < num; ++i)
|
||||
if (!lists.at(keys[i]).empty())
|
||||
active.push_back(coords[i]);
|
||||
if (!active.empty()) {
|
||||
cells.resize(active.size() * count);
|
||||
for (size_t i = 0; i < active.size(); ++i)
|
||||
terms(active[i], c.pattern, cells.data() + i * count);
|
||||
CUDA(cudaMemcpy(dcells.p, cells.data(), cells.size() * sizeof(sr::CellTerm),
|
||||
cudaMemcpyHostToDevice));
|
||||
CUDA(cudaMemcpy(dcoords.p, active.data(), active.size() * sizeof(Coord),
|
||||
cudaMemcpyHostToDevice));
|
||||
auto search = [&]() {
|
||||
if (jobs.empty() || shared.cancel)
|
||||
return;
|
||||
auto start = Clock::now();
|
||||
CUDA(cudaMemcpy(djobs.p, jobs.data(), jobs.size() * sizeof(Job),
|
||||
cudaMemcpyHostToDevice));
|
||||
CUDA(cudaMemset(total.p, 0, sizeof(*total.p)));
|
||||
prepareKernel<<<unsigned((jobs.size() + 127) / 128), 128>>>(
|
||||
dcells.p, djobs.p, jobs.size(), count, positive, prep.p);
|
||||
searchKernel<<<unsigned((uint64_t(jobs.size()) << 13) / 256), 256>>>(
|
||||
dcells.p, dcoords.p, djobs.p, jobs.size(), count, positive,
|
||||
c.pattern.cells.front().x, c.pattern.cells.front().z, prep.p, matches.p,
|
||||
c.maxResults, total.p);
|
||||
CUDA(cudaGetLastError());
|
||||
unsigned long long found;
|
||||
CUDA(cudaMemcpy(&found, total.p, sizeof(found), cudaMemcpyDeviceToHost));
|
||||
if (found > UINT64_MAX - result.matches)
|
||||
throw std::runtime_error("match count exceeds uint64");
|
||||
result.matches += found;
|
||||
result.jobs += jobs.size();
|
||||
size_t take = std::min<uint64_t>(found, c.maxResults - result.sample.size());
|
||||
if (take) {
|
||||
size_t old = result.sample.size();
|
||||
result.sample.resize(old + take);
|
||||
CUDA(cudaMemcpy(result.sample.data() + old, matches.p, take * sizeof(Match),
|
||||
cudaMemcpyDeviceToHost));
|
||||
}
|
||||
result.searchMs +=
|
||||
std::chrono::duration<double, std::milli>(Clock::now() - start).count();
|
||||
jobs.clear();
|
||||
};
|
||||
for (uint32_t i = 0; i < active.size() && !shared.cancel; ++i)
|
||||
for (uint32_t root : lists.at(classKey(active[i]))) {
|
||||
jobs.push_back({i, root});
|
||||
if (jobs.size() == size_t(c.jobBatch))
|
||||
search();
|
||||
}
|
||||
search();
|
||||
}
|
||||
result.positions += num;
|
||||
shared.done.fetch_add(num);
|
||||
}
|
||||
result.end = Clock::now();
|
||||
result.scanMs =
|
||||
std::chrono::duration<double, std::milli>(result.end - result.start).count();
|
||||
} catch (const std::exception &e) {
|
||||
shared.cancel = true;
|
||||
std::lock_guard<std::mutex> lock(shared.mutex);
|
||||
shared.error = "GPU " + std::to_string(device) + ": " + e.what();
|
||||
shared.cv.notify_all();
|
||||
}
|
||||
}
|
||||
152
bench/test_cli.py
Normal file
152
bench/test_cli.py
Normal file
|
|
@ -0,0 +1,152 @@
|
|||
#!/usr/bin/env python3
|
||||
import argparse,json,subprocess,tempfile
|
||||
from pathlib import Path
|
||||
HERE=Path(__file__).resolve().parent
|
||||
BIN=HERE/'bin/slime-bench'
|
||||
def run(*args,ok=True):
|
||||
p=subprocess.run([str(BIN),*map(str,args)],capture_output=True,text=True,timeout=180)
|
||||
if ok:
|
||||
assert p.returncode==0,p.stderr
|
||||
return json.loads(p.stdout)
|
||||
assert p.returncode!=0,p.stdout
|
||||
|
||||
def term(x,z):
|
||||
def i32(v):return ((v+2**31)%2**32)-2**31
|
||||
return i32(x*x*4987142)+i32(x*5947611)+i32(z*z)*4392871+i32(z*389711)
|
||||
def slime(seed,x,z):
|
||||
s=((seed+term(x,z))^987234911^0x5DEECE66D)&((1<<48)-1)
|
||||
while True:
|
||||
s=(s*0x5DEECE66D+11)&((1<<48)-1);q=s>>17
|
||||
if q<2147483640:return q%10==0
|
||||
|
||||
def main():
|
||||
ap=argparse.ArgumentParser();ap.add_argument('--gpu',action='store_true');args=ap.parse_args()
|
||||
for radius in [0,1,2,31,1000000]:
|
||||
r=run('--x',-123,'--z',456,'--radius',radius,'--size',6,'--dry-run')
|
||||
assert r['anchors']==1+2*radius*(radius+1)
|
||||
assert r['first_anchor']==[-123,456-radius] and r['last_anchor']==[-123,456+radius]
|
||||
for bad in [[],['--radius','-1'],['--radius','1','--size','0'],['--radius','1','--size','7'],['--radius','abc'],['--radius','0','--x','2147483647'],['--radius','1','--repeat','0'],['--radius','1','--position-batch','0']]:run(*bad,'--dry-run',ok=False)
|
||||
points=[(dx,dz) for dz in range(-3,4) for dx in range(-3,4) if abs(dx)+abs(dz)<=3]
|
||||
for start in range(len(points)):
|
||||
count=min(4,len(points)-start)
|
||||
r=run('--radius',3,'--start-anchor',start,'--anchor-count',count,'--dry-run')
|
||||
assert r['start_anchor']==start and r['anchor_count']==count and r['anchors']==25
|
||||
assert r['first_anchor']==list(points[start]) and r['last_anchor']==list(points[start+count-1])
|
||||
assert run('--radius',3,'--start-anchor',24,'--dry-run')['anchor_count']==1
|
||||
for opts in [('--start-anchor',25),('--anchor-count',0),('--anchor-count',26),
|
||||
('--start-anchor',24,'--anchor-count',2),('--start-anchor',18446744073709551615)]:
|
||||
run('--radius',3,*opts,'--dry-run',ok=False)
|
||||
pattern='?##./#..?/..#?'
|
||||
r=run('--radius',0,'--pattern',pattern,'--dry-run')
|
||||
assert r['pattern']==pattern.split('/') and r['square_size'] is None
|
||||
assert (r['pattern_width'],r['pattern_height'],r['slime_cells'],r['non_slime_cells'])==(4,3,4,5)
|
||||
for bad_pattern in ['', '.', '??', '#/##', '#x', '#//.', '#/'+'#'*65]:
|
||||
run('--radius',0,'--pattern',bad_pattern,'--dry-run',ok=False)
|
||||
run('--radius',0,'--size',5,'--pattern','#','--dry-run',ok=False)
|
||||
run('--radius',0,'--pattern','#','--pattern','#','--dry-run',ok=False)
|
||||
run('--radius',0,'--pattern-file','/nonexistent-pattern','--dry-run',ok=False)
|
||||
run('--radius',0,'--x',2147483647,'--pattern','?#','--dry-run',ok=False)
|
||||
r=run('--radius',0,'--x',2147483647,'--pattern','#/#','--dry-run')
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
path=Path(tmp)/'pattern.txt';path.write_bytes(b'?##.\r\n#..?\r\n..#?\r\n')
|
||||
assert run('--radius',0,'--pattern-file',path,'--dry-run')['pattern']==pattern.split('/')
|
||||
heart_fixture=json.loads((HERE/'testdata/heart-5x5.json').read_text())
|
||||
assert (HERE/'patterns/heart-5x5.txt').read_text().splitlines()==heart_fixture['pattern']
|
||||
assert all(slime(heart_fixture['seed48'],heart_fixture['chunk_x']+dx,heart_fixture['chunk_z']+dz)==(ch=='#')
|
||||
for dz,row in enumerate(heart_fixture['pattern']) for dx,ch in enumerate(row))
|
||||
summary={'cli_scope_and_errors':True,'pattern_inputs':True}
|
||||
if args.gpu:
|
||||
heart_poc=run('--x',heart_fixture['chunk_x'],'--z',heart_fixture['chunk_z'],'--radius',0,
|
||||
'--pattern-file',HERE/'patterns/heart-5x5.txt','--max-results',2000)
|
||||
heart_hits=heart_poc['rounds'][0]
|
||||
assert heart_hits['matches']==heart_fixture['matches']
|
||||
assert heart_hits['root_jobs']==heart_fixture['root_jobs']
|
||||
assert not heart_hits['sample_truncated'] and len(heart_hits['sample'])==heart_hits['matches']
|
||||
assert len(set(map(tuple,heart_hits['sample'])))==heart_hits['matches']
|
||||
assert [heart_fixture['seed48'],heart_fixture['chunk_x'],heart_fixture['chunk_z']] in heart_hits['sample']
|
||||
for seed,x,z in heart_hits['sample']:
|
||||
assert all(slime(seed,x+dx,z+dz)==(ch=='#') for dz,row in enumerate(heart_fixture['pattern']) for dx,ch in enumerate(row))
|
||||
summary['heart_pattern_verified_matches']=heart_hits['matches']
|
||||
# A mixed-mask regression fixture; this is not the target creeper pattern.
|
||||
fixture=json.loads((HERE/'testdata/mixed-mask-regression.json').read_text())
|
||||
face=run('--x',fixture['chunk_x'],'--z',fixture['chunk_z'],'--radius',0,
|
||||
'--pattern','/'.join(fixture['pattern']),'--max-results',1000)
|
||||
hits=face['rounds'][0]
|
||||
assert hits['matches']==fixture['matches']
|
||||
assert not hits['sample_truncated'] and any(s==fixture['seed48'] for s,x,z in hits['sample'])
|
||||
for seed,x,z in hits['sample']:
|
||||
assert all(slime(seed,x+dx,z+dz)==(ch=='#') for dz,row in enumerate(fixture['pattern']) for dx,ch in enumerate(row))
|
||||
summary['mixed_mask_verified_matches']=hits['matches']
|
||||
common=['--x',51069,'--z',419124]
|
||||
reference=run(*common,'--radius',0,'--size',5,'--repeat',2,'--max-results',100)
|
||||
expected={61692151016558,15959335054446}
|
||||
assert all(r['matches']==24 and r['root_jobs']==84 for r in reference['rounds'])
|
||||
samples=[set(map(tuple,r['sample'])) for r in reference['rounds']]
|
||||
assert samples[0]==samples[1] and expected <= {s for s,x,z in samples[0]}
|
||||
sliced=run(*common,'--radius',0,'--size',5,'--job-batch',17,'--max-results',100,'--cache-classes',0)
|
||||
assert set(map(tuple,sliced['rounds'][0]['sample']))==samples[0]
|
||||
partial=run(*common,'--radius',0,'--size',5,'--max-results',3)
|
||||
assert partial['rounds'][0]['matches']==24 and len(partial['rounds'][0]['sample'])==3 and partial['rounds'][0]['sample_truncated']
|
||||
for n in [4,6]:
|
||||
r=run(*common,'--radius',0,'--size',n,'--max-results',1000)
|
||||
for seed,x,z in r['rounds'][0]['sample']:assert all(slime(seed,x+dx,z+dz) for dx in range(n) for dz in range(n))
|
||||
if n>=5:
|
||||
wanted={t for t in samples[0] if all(slime(t[0],t[1]+dx,t[2]+dz) for dx in range(n) for dz in range(n))}
|
||||
assert set(map(tuple,r['rounds'][0]['sample']))==wanted
|
||||
summary[f'size_{n}']=r['rounds'][0]['matches']
|
||||
# The same 5x5 positive constraints, shifted inside a non-square mask.
|
||||
# Empty anchor exercises normalization independently of the first #.
|
||||
rows=['?'*7]+['?'+'#'*5+'.' for _ in range(5)]+['?.?????']
|
||||
pattern='/'.join(rows)
|
||||
masked=run('--x',51068,'--z',419123,'--radius',0,'--pattern',pattern,'--max-results',100)
|
||||
wanted={(seed,51068,419123) for seed,x,z in samples[0]
|
||||
if all(ch=='?' or slime(seed,51068+dx,419123+dz)==(ch=='#')
|
||||
for dz,row in enumerate(rows) for dx,ch in enumerate(row))}
|
||||
assert wanted and set(map(tuple,masked['rounds'][0]['sample']))==wanted
|
||||
assert masked['rounds'][0]['matches']==len(wanted)
|
||||
# Identical positive subset, but ignored rather than forbidden background.
|
||||
ignored=pattern.replace('.', '?')
|
||||
loose=run('--x',51068,'--z',419123,'--radius',0,'--pattern',ignored,'--max-results',100)
|
||||
assert {s for s,x,z in loose['rounds'][0]['sample']}=={s for s,x,z in samples[0]}
|
||||
# Force a forbidden cell to reject at least one known positive candidate.
|
||||
seed=next(iter(samples[0]))[0]
|
||||
dx,dz=next((dx,dz) for dz in range(16) for dx in range(16)
|
||||
if not (1<=dx<=5 and 1<=dz<=5) and slime(seed,51068+dx,419123+dz))
|
||||
rejection=[list('?'*16) for _ in range(16)]
|
||||
for z in range(1,6):
|
||||
for x in range(1,6):rejection[z][x]='#'
|
||||
rejection[dz][dx]='.'
|
||||
rejected=run('--x',51068,'--z',419123,'--radius',0,'--pattern',
|
||||
'/'.join(''.join(row) for row in rejection),'--max-results',100)
|
||||
expected_seeds={s for s,x,z in samples[0] if not slime(s,51068+dx,419123+dz)}
|
||||
assert len(expected_seeds)<24
|
||||
assert {s for s,x,z in rejected['rounds'][0]['sample']}==expected_seeds
|
||||
assert rejected['rounds'][0]['matches']==len(expected_seeds)
|
||||
summary['mixed_pattern_vs_independent_filter']=len(wanted)
|
||||
summary['forbidden_cell_excludes_candidates']=True
|
||||
diamond=run(*common,'--radius',2,'--size',5,'--max-results',1000,'--position-batch',3)
|
||||
split=[]
|
||||
for dz in range(-2,3):
|
||||
for dx in range(-2,3):
|
||||
if abs(dx)+abs(dz)>2:continue
|
||||
r=run('--x',51069+dx,'--z',419124+dz,'--radius',0,'--size',5,'--max-results',1000)
|
||||
split.extend(map(tuple,r['rounds'][0]['sample']))
|
||||
assert sorted(split)==sorted(map(tuple,diamond['rounds'][0]['sample']))
|
||||
assert diamond['anchors']==13
|
||||
partition=[]
|
||||
for start,count in [(0,4),(4,5),(9,4)]:
|
||||
r=run(*common,'--radius',2,'--start-anchor',start,'--anchor-count',count,
|
||||
'--max-results',1000,'--position-batch',3)
|
||||
assert sum(g['anchors'] for g in r['rounds'][0]['gpus'])==count
|
||||
partition.extend(map(tuple,r['rounds'][0]['sample']))
|
||||
assert sorted(partition)==sorted(split)
|
||||
|
||||
run('--radius',0,'--devices','0,0',ok=False)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out=Path(tmp)/'report.json'
|
||||
r=run(*common,'--radius',0,'--output',out)
|
||||
assert json.loads(out.read_text())==r
|
||||
run(*common,'--radius',0,'--output',out,ok=False)
|
||||
summary['gpu_known_matches']=24;summary['diamond_vs_individual_anchors']=True
|
||||
print(json.dumps(summary,indent=2))
|
||||
if __name__=='__main__':main()
|
||||
139
bench/test_math.cu
Normal file
139
bench/test_math.cu
Normal file
|
|
@ -0,0 +1,139 @@
|
|||
#include "src/kernels.cuh"
|
||||
#include <iostream>
|
||||
#include <set>
|
||||
#include <random>
|
||||
struct HostEmit {
|
||||
const sr::CellTerm *cells;
|
||||
int count;
|
||||
std::set<uint64_t> *result;
|
||||
__host__ __device__ void operator()(uint64_t seed) {
|
||||
#ifndef __CUDA_ARCH__
|
||||
if (sr::verifyPattern(seed, cells, count))
|
||||
result->insert(seed);
|
||||
#endif
|
||||
}
|
||||
};
|
||||
void check(bool ok, const char *msg) {
|
||||
if (!ok)
|
||||
throw std::runtime_error(msg);
|
||||
}
|
||||
int main() {
|
||||
uint64_t points = 0, groups = 0, mixed = 0;
|
||||
std::mt19937_64 rng(123456);
|
||||
for (int r = 0; r <= 64; ++r) {
|
||||
Config c;
|
||||
c.x = -123;
|
||||
c.z = 98;
|
||||
c.radius = r;
|
||||
std::set<std::pair<int32_t, int32_t>> actual;
|
||||
for (uint64_t i = 0; i < anchors(r); ++i) {
|
||||
auto p = coordinate(c, i);
|
||||
actual.emplace(p.x, p.z);
|
||||
}
|
||||
check(actual.size() == anchors(r), "duplicate anchor");
|
||||
for (int dz = -r; dz <= r; ++dz)
|
||||
for (int dx = -r; dx <= r; ++dx)
|
||||
check(bool(actual.count({c.x + dx, c.z + dz})) ==
|
||||
(std::abs(dx) + std::abs(dz) <= r),
|
||||
"diamond coverage mismatch");
|
||||
points += actual.size();
|
||||
}
|
||||
Config large;
|
||||
large.radius = 1000000;
|
||||
for (int t = 0; t < 100000; ++t) {
|
||||
auto p = coordinate(large, rng() % anchors(large.radius));
|
||||
check(std::abs(int64_t(p.x)) + std::abs(int64_t(p.z)) <= int64_t(large.radius),
|
||||
"large diamond mismatch");
|
||||
}
|
||||
for (int n : {1, 2, 3, 4, 5, 6})
|
||||
for (int t = 0; t < 512; ++t) {
|
||||
Coord coord{int32_t(rng() % 3750000) - 1875000, int32_t(rng() % 3750000) - 1875000};
|
||||
int count = n * n;
|
||||
std::vector<sr::CellTerm> cells(count);
|
||||
terms(coord, n, cells.data());
|
||||
uint32_t root = rng() & 262143, base = (rng() & 131071) & ~240U;
|
||||
std::vector<uint32_t> prepared(count * 2);
|
||||
for (int i = 0; i < count; ++i) {
|
||||
uint64_t a = root + cells[i].term;
|
||||
prepared[2 * i] = a >> 18;
|
||||
prepared[2 * i + 1] =
|
||||
((((a ^ sr::kCombinedXor) & 262143) * sr::kJavaMultiplier + 11) >> 17);
|
||||
for (int j = 0; j < 16; ++j)
|
||||
check(q(prepared.data(), i, base + 16 * j) ==
|
||||
(sr::nextStateFromTerm(root + (uint64_t(base + 16 * j) << 18),
|
||||
cells[i].term) >>
|
||||
17),
|
||||
"prepared q mismatch");
|
||||
}
|
||||
uint32_t expected = 0;
|
||||
for (int j = 0; j < 16; ++j)
|
||||
if (sr::differenceFilter(root + (uint64_t(base + 16 * j) << 18), cells.data(),
|
||||
count))
|
||||
expected |= 1U << j;
|
||||
check(groupMask(prepared.data(), base, count) == expected,
|
||||
"variable-size group mask mismatch");
|
||||
++groups;
|
||||
}
|
||||
// Compare arbitrary sparse layouts and forbidden cells against all high bits.
|
||||
for (int t = 0; t < 128; ++t) {
|
||||
Coord coord{int32_t(rng()), int32_t(rng())};
|
||||
// Keep offsets away from overflow even for signed boundary samples.
|
||||
coord.x /= 2;
|
||||
coord.z /= 2;
|
||||
uint64_t world = rng() & sr::kMask48;
|
||||
std::string text;
|
||||
for (int z = 0; z < 5; ++z) {
|
||||
if (z)
|
||||
text += '/';
|
||||
for (int x = 0; x < 7; ++x)
|
||||
text +=
|
||||
(x == 0 && z == 0) || rng() % 4 == 0 ? '?'
|
||||
: sr::exactIsSlimeFromTerm(world, sr::coordinateTerm(coord.x + x, coord.z + z))
|
||||
? '#'
|
||||
: '.';
|
||||
}
|
||||
if (text.find('#') == std::string::npos)
|
||||
continue;
|
||||
auto pattern = parsePattern(text);
|
||||
int count = pattern.cells.size();
|
||||
std::vector<sr::CellTerm> cells(count);
|
||||
terms(coord, pattern, cells.data());
|
||||
uint64_t normalized = (world + sr::coordinateTerm(coord.x + pattern.cells.front().x,
|
||||
coord.z + pattern.cells.front().z)) &
|
||||
sr::kMask48;
|
||||
check(sr::verifyPattern(normalized, cells.data(), count), "normalized pattern mismatch");
|
||||
uint64_t low = normalized & ((1ULL << 35) - 1);
|
||||
std::set<uint64_t> actual, expected;
|
||||
HostEmit emit{cells.data() + pattern.positive, count - pattern.positive, &actual};
|
||||
sr::solveIntervals(low, cells.data(), pattern.positive, emit);
|
||||
for (uint64_t high = 0; high < 8192; ++high) {
|
||||
uint64_t seed = low + (high << 35);
|
||||
// Ordinary branch requires a successful first draw at positive cells.
|
||||
bool ordinary = true;
|
||||
for (int i = 0; i < pattern.positive; ++i)
|
||||
if ((sr::nextStateFromTerm(seed, cells[i].term) >> 17) % 10 != 0)
|
||||
ordinary = false;
|
||||
if (ordinary && sr::verifyPattern(seed, cells.data(), count))
|
||||
expected.insert(seed);
|
||||
}
|
||||
check(actual == expected, "mixed pattern high-bit solver mismatch");
|
||||
++mixed;
|
||||
uint32_t root = low & 262143, base = uint32_t(low >> 18) & ~240U;
|
||||
std::vector<uint32_t> prepared(count * 2);
|
||||
for (int i = 0; i < pattern.positive; ++i) {
|
||||
uint64_t a = root + cells[i].term;
|
||||
prepared[2 * i] = a >> 18;
|
||||
prepared[2 * i + 1] =
|
||||
((((a ^ sr::kCombinedXor) & 262143) * sr::kJavaMultiplier + 11) >> 17);
|
||||
}
|
||||
uint32_t wanted = 0;
|
||||
for (int j = 0; j < 16; ++j)
|
||||
if (sr::differenceFilter(root + (uint64_t(base + 16 * j) << 18), cells.data(),
|
||||
pattern.positive))
|
||||
wanted |= 1U << j;
|
||||
check(groupMask(prepared.data(), base, pattern.positive) == wanted,
|
||||
"sparse pattern group mask mismatch");
|
||||
}
|
||||
std::cout << "{\"diamond_points\":" << points << ",\"variable_size_groups\":" << groups
|
||||
<< ",\"mixed_pattern_slices\":" << mixed << ",\"passed\":true}\n";
|
||||
}
|
||||
14
bench/testdata/heart-5x5.json
vendored
Normal file
14
bench/testdata/heart-5x5.json
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"pattern": [
|
||||
".#.#.",
|
||||
"#####",
|
||||
"#####",
|
||||
".###.",
|
||||
"..#.."
|
||||
],
|
||||
"seed48": 22428888508636,
|
||||
"chunk_x": -5,
|
||||
"chunk_z": -147,
|
||||
"matches": 1181,
|
||||
"root_jobs": 405
|
||||
}
|
||||
14
bench/testdata/mixed-mask-regression.json
vendored
Normal file
14
bench/testdata/mixed-mask-regression.json
vendored
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
{
|
||||
"pattern": [
|
||||
"..##..",
|
||||
"..##..",
|
||||
"##..##",
|
||||
"#....#",
|
||||
"#....#",
|
||||
"#.##.#"
|
||||
],
|
||||
"seed48": 100568620033461,
|
||||
"chunk_x": -137,
|
||||
"chunk_z": -53,
|
||||
"matches": 44
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue