Compare commits
No commits in common. "github-public" and "master" have entirely different histories.
github-pub
...
master
49 changed files with 344 additions and 40360 deletions
|
|
@ -1,4 +0,0 @@
|
|||
BasedOnStyle: LLVM
|
||||
IndentWidth: 4
|
||||
ColumnLimit: 100
|
||||
SortIncludes: Never
|
||||
49
.gitignore
vendored
49
.gitignore
vendored
|
|
@ -1,47 +1,2 @@
|
|||
# Local build output.
|
||||
bin/
|
||||
build/
|
||||
cmake-build-*/
|
||||
*.o
|
||||
*.obj
|
||||
*.a
|
||||
*.so
|
||||
*.dll
|
||||
*.exe
|
||||
*.d
|
||||
*.ptx
|
||||
*.cubin
|
||||
*.fatbin
|
||||
|
||||
# Python environments and caches.
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
.venv/
|
||||
venv/
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
|
||||
# Temporary logs and scratch files.
|
||||
*.log
|
||||
*.stderr
|
||||
*.tmp
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
/artifacts/
|
||||
|
||||
# Machine-local configuration and credentials.
|
||||
.env
|
||||
.env.*
|
||||
!.env.example
|
||||
/.aws/
|
||||
/.codex/
|
||||
/.agents/
|
||||
/.idea/
|
||||
/.vscode/
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Private video sources and generated assets.
|
||||
/show/video/
|
||||
slime
|
||||
slime-cuda
|
||||
|
|
|
|||
21
LICENSE
21
LICENSE
|
|
@ -1,21 +0,0 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2026 Yaossg
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
30
Makefile
30
Makefile
|
|
@ -1,22 +1,10 @@
|
|||
.PHONY: all examples bench test test-cpu test-gpu clean help
|
||||
all: examples bench
|
||||
examples:
|
||||
$(MAKE) -C examples
|
||||
bench:
|
||||
$(MAKE) -C bench
|
||||
test: test-cpu
|
||||
$(MAKE) -C bench test
|
||||
test-cpu:
|
||||
$(MAKE) -C examples test-cpu
|
||||
test-gpu:
|
||||
$(MAKE) -C examples test-gpu
|
||||
$(MAKE) -C bench test-gpu
|
||||
all: slime slime-cuda
|
||||
|
||||
slime: slime.cpp
|
||||
g++ -o slime slime.cpp -O3 -std=c++17
|
||||
|
||||
slime-cuda: slime.cu
|
||||
nvcc -o slime-cuda slime.cu -O3 -std=c++17
|
||||
|
||||
clean:
|
||||
$(MAKE) -C examples clean
|
||||
$(MAKE) -C bench clean
|
||||
help:
|
||||
@echo 'make Build blog examples and the pattern search CLI'
|
||||
@echo 'make test-cpu Test forward examples without CUDA Toolkit or a GPU'
|
||||
@echo 'make test Run all host checks (nvcc required, GPU not required)'
|
||||
@echo 'make test-gpu Verify forward, reverse, reuse and CLI results on a GPU'
|
||||
@echo 'make clean Remove compiled outputs'
|
||||
rm -f slime slime-cuda
|
||||
35
README.md
35
README.md
|
|
@ -1,35 +0,0 @@
|
|||
# 如何快速寻找史莱姆区块?
|
||||
|
||||
[博客正文](https://yaossg.com/site/docs/slime)的配套代码:从 CPU 暴力枚举、CUDA 并行与 Outer Sum,到低位筛根、输出差、成组筛选和高位区间求解。
|
||||
|
||||
| 目录 | 内容 |
|
||||
| --- | --- |
|
||||
| [examples/](examples/README.md) | 按博客顺序阅读、运行和比较各步算法 |
|
||||
| [include/](include/README.md) | 共用的 Random 算术与区间求解 |
|
||||
| [bench/](bench/README.md) | 支持任意图案和多 GPU 的搜索 CLI |
|
||||
| [results/](results/README.md) | 博客最终性能表对应的历史计时样本 |
|
||||
|
||||
## 构建与验证
|
||||
|
||||
需要 Linux/WSL、C++17 编译器、Python 3;CUDA 程序另需 NVIDIA 驱动和 CUDA Toolkit。
|
||||
|
||||
```sh
|
||||
make test-cpu # 仅 CPU,无需安装 CUDA
|
||||
make # 构建示例和搜索 CLI
|
||||
make test # 数学与 CLI 检查,需要 nvcc,无需 GPU
|
||||
make test-gpu # GPU 结果与独立 Python 判定对照
|
||||
```
|
||||
|
||||
默认 CUDA 架构为 `86`,同时生成 PTX。其他架构如 H100 使用 `make -B CUDA_ARCH=90`。
|
||||
|
||||
```sh
|
||||
./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 --max-results 1000
|
||||
```
|
||||
|
||||
反推只生成普通分支候选,可能漏掉依赖 Java 拒绝重抽的解;全部输出经过精确验证。
|
||||
返回的种子是世界种子的低 48 位,坐标单位是区块,图案位置指左上角。
|
||||
|
||||
`make clean` 清理编译产物;临时结果放在已忽略的 `artifacts/` 中。
|
||||
|
||||
代码采用 [MIT 许可证](LICENSE)。
|
||||
2
bench/.gitignore
vendored
2
bench/.gitignore
vendored
|
|
@ -1,2 +0,0 @@
|
|||
/bin/
|
||||
/__pycache__/
|
||||
|
|
@ -1,21 +0,0 @@
|
|||
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
|
||||
|
|
@ -1,67 +0,0 @@
|
|||
# 图案搜索 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)。
|
||||
|
|
@ -1,6 +0,0 @@
|
|||
##..##
|
||||
##..##
|
||||
..##..
|
||||
.####.
|
||||
.####.
|
||||
.#..#.
|
||||
|
|
@ -1,5 +0,0 @@
|
|||
.#.#.
|
||||
#####
|
||||
#####
|
||||
.###.
|
||||
..#..
|
||||
|
|
@ -1,45 +0,0 @@
|
|||
#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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,139 +0,0 @@
|
|||
#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;
|
||||
}
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
#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;
|
||||
};
|
||||
|
|
@ -1,89 +0,0 @@
|
|||
#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);
|
||||
}
|
||||
}
|
||||
|
|
@ -1,137 +0,0 @@
|
|||
#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};
|
||||
}
|
||||
|
|
@ -1,96 +0,0 @@
|
|||
#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 << "}";
|
||||
}
|
||||
|
|
@ -1,84 +0,0 @@
|
|||
#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;
|
||||
}
|
||||
|
|
@ -1,197 +0,0 @@
|
|||
#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();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,152 +0,0 @@
|
|||
#!/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()
|
||||
|
|
@ -1,139 +0,0 @@
|
|||
#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
14
bench/testdata/heart-5x5.json
vendored
|
|
@ -1,14 +0,0 @@
|
|||
{
|
||||
"pattern": [
|
||||
".#.#.",
|
||||
"#####",
|
||||
"#####",
|
||||
".###.",
|
||||
"..#.."
|
||||
],
|
||||
"seed48": 22428888508636,
|
||||
"chunk_x": -5,
|
||||
"chunk_z": -147,
|
||||
"matches": 1181,
|
||||
"root_jobs": 405
|
||||
}
|
||||
14
bench/testdata/mixed-mask-regression.json
vendored
14
bench/testdata/mixed-mask-regression.json
vendored
|
|
@ -1,14 +0,0 @@
|
|||
{
|
||||
"pattern": [
|
||||
"..##..",
|
||||
"..##..",
|
||||
"##..##",
|
||||
"#....#",
|
||||
"#....#",
|
||||
"#.##.#"
|
||||
],
|
||||
"seed48": 100568620033461,
|
||||
"chunk_x": -137,
|
||||
"chunk_z": -53,
|
||||
"matches": 44
|
||||
}
|
||||
|
|
@ -1,24 +0,0 @@
|
|||
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
|
||||
|
|
@ -1,62 +0,0 @@
|
|||
# 博客示例
|
||||
|
||||
对应[《如何快速寻找史莱姆区块?》](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 和拒绝重抽。
|
||||
反推测试比较五版完整结果,并独立验证种子;复用测试比较三版完整根列表与结果。
|
||||
反推候选仍可能漏掉依赖拒绝重抽的解。
|
||||
|
|
@ -1,142 +0,0 @@
|
|||
#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);
|
||||
}
|
||||
|
|
@ -1,172 +0,0 @@
|
|||
#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
|
||||
|
|
@ -1,68 +0,0 @@
|
|||
#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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,66 +0,0 @@
|
|||
#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();
|
||||
}
|
||||
}
|
||||
|
|
@ -1,71 +0,0 @@
|
|||
#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");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,15 +0,0 @@
|
|||
#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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -1,173 +0,0 @@
|
|||
#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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,33 +0,0 @@
|
|||
{
|
||||
"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
|
||||
]
|
||||
}
|
||||
File diff suppressed because it is too large
Load diff
File diff suppressed because it is too large
Load diff
|
|
@ -1,45 +0,0 @@
|
|||
#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
|
||||
|
|
@ -1,233 +0,0 @@
|
|||
#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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,114 +0,0 @@
|
|||
#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;
|
||||
}
|
||||
}
|
||||
|
|
@ -1,213 +0,0 @@
|
|||
#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;
|
||||
}
|
||||
};
|
||||
|
|
@ -1,73 +0,0 @@
|
|||
#!/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()
|
||||
|
|
@ -1,139 +0,0 @@
|
|||
#!/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)
|
||||
|
|
@ -1,7 +0,0 @@
|
|||
# 共用数学实现
|
||||
|
||||
- `slime/solver_core.hpp`:Java 整数回绕、48 位 Random 状态、精确史莱姆判定与模式验证。
|
||||
- `slime/upper_interval.hpp`:输出差必要条件和高 13 位区间求交。
|
||||
|
||||
教学示例和搜索 CLI 共用这些实现。候选生成使用首次随机输出的普通分支;
|
||||
最终验证处理 Java 的拒绝重抽,但不能补回此前漏掉的候选。
|
||||
|
|
@ -1,97 +0,0 @@
|
|||
#pragma once
|
||||
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#if defined(__CUDACC__)
|
||||
#define SLIME_HD __host__ __device__
|
||||
#define SLIME_INLINE __forceinline__
|
||||
#else
|
||||
#define SLIME_HD
|
||||
#define SLIME_INLINE inline
|
||||
#endif
|
||||
|
||||
namespace slime {
|
||||
|
||||
constexpr uint64_t kJavaMultiplier = 0x5DEECE66DULL;
|
||||
constexpr uint64_t kJavaAddend = 0xBULL;
|
||||
constexpr uint64_t kMask48 = (1ULL << 48) - 1ULL;
|
||||
constexpr uint64_t kSlimeXor = 987234911ULL;
|
||||
constexpr uint64_t kCombinedXor = kSlimeXor ^ kJavaMultiplier;
|
||||
constexpr int kLowerBits = 35;
|
||||
constexpr int kUpperBits = 13;
|
||||
constexpr uint32_t kUpperSize = 1U << kUpperBits;
|
||||
constexpr uint32_t kUpperMask = kUpperSize - 1U;
|
||||
constexpr uint32_t kHalfDeltaInverse = 4965U;
|
||||
constexpr int kMaxPatternCells = 64;
|
||||
constexpr uint32_t kX2Coeff = 4987142U;
|
||||
constexpr uint32_t kXCoeff = 5947611U;
|
||||
constexpr uint32_t kZ2Coeff = 4392871U;
|
||||
constexpr uint32_t kZCoeff = 389711U;
|
||||
|
||||
enum Requirement : uint8_t {
|
||||
kNonSlime = 0,
|
||||
kSlime = 1,
|
||||
};
|
||||
|
||||
struct CellTerm {
|
||||
uint64_t term;
|
||||
uint8_t requirement;
|
||||
};
|
||||
|
||||
SLIME_HD SLIME_INLINE uint64_t javaIntAsLongBits(uint32_t value) {
|
||||
return static_cast<uint64_t>(static_cast<int64_t>(static_cast<int32_t>(value)));
|
||||
}
|
||||
|
||||
SLIME_HD SLIME_INLINE uint64_t coordinateTerm(int32_t chunkX, int32_t chunkZ) {
|
||||
const uint32_t x = static_cast<uint32_t>(chunkX);
|
||||
const uint32_t z = static_cast<uint32_t>(chunkZ);
|
||||
return javaIntAsLongBits(x * x * kX2Coeff) + javaIntAsLongBits(x * kXCoeff) +
|
||||
javaIntAsLongBits(z * z) * kZ2Coeff + javaIntAsLongBits(z * kZCoeff);
|
||||
}
|
||||
|
||||
SLIME_HD SLIME_INLINE uint64_t coordinateXTerm(int32_t chunkX) {
|
||||
const uint32_t x = static_cast<uint32_t>(chunkX);
|
||||
return javaIntAsLongBits(x * x * kX2Coeff) + javaIntAsLongBits(x * kXCoeff);
|
||||
}
|
||||
|
||||
SLIME_HD SLIME_INLINE uint64_t coordinateZTerm(int32_t chunkZ) {
|
||||
const uint32_t z = static_cast<uint32_t>(chunkZ);
|
||||
return javaIntAsLongBits(z * z) * kZ2Coeff + javaIntAsLongBits(z * kZCoeff);
|
||||
}
|
||||
|
||||
SLIME_HD SLIME_INLINE uint64_t nextStateFromTerm(uint64_t seed48, uint64_t term) {
|
||||
uint64_t state = ((seed48 + term) ^ kCombinedXor) & kMask48;
|
||||
return (state * kJavaMultiplier + kJavaAddend) & kMask48;
|
||||
}
|
||||
|
||||
SLIME_HD SLIME_INLINE bool exactIsSlimeFromTerm(uint64_t seed48, uint64_t term) {
|
||||
uint64_t state = ((seed48 + term) ^ kCombinedXor) & kMask48;
|
||||
for (;;) {
|
||||
state = (state * kJavaMultiplier + kJavaAddend) & kMask48;
|
||||
const uint32_t bits = static_cast<uint32_t>(state >> 17);
|
||||
const uint32_t value = bits % 10U;
|
||||
if (bits - value + 9U <= 0x7FFFFFFFU) {
|
||||
return value == 0U;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
SLIME_HD SLIME_INLINE bool verifyPattern(uint64_t seed48, const CellTerm *cells, int cellCount) {
|
||||
for (int i = 0; i < cellCount; ++i) {
|
||||
const bool slime = exactIsSlimeFromTerm(seed48, cells[i].term);
|
||||
if (slime != (cells[i].requirement == kSlime)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
SLIME_HD SLIME_INLINE uint32_t firstWithResidue(uint32_t start, uint32_t residue) {
|
||||
return start + ((residue + 5U - (start % 5U)) % 5U);
|
||||
}
|
||||
|
||||
} // namespace slime
|
||||
|
||||
#undef SLIME_HD
|
||||
#undef SLIME_INLINE
|
||||
|
|
@ -1,87 +0,0 @@
|
|||
#pragma once
|
||||
|
||||
#include "solver_core.hpp"
|
||||
|
||||
#if defined(__CUDACC__)
|
||||
#define SLIME_INTERVAL_HD __host__ __device__
|
||||
#define SLIME_INTERVAL_INLINE __forceinline__
|
||||
#else
|
||||
#define SLIME_INTERVAL_HD
|
||||
#define SLIME_INTERVAL_INLINE inline
|
||||
#endif
|
||||
|
||||
namespace slime {
|
||||
namespace sr = slime;
|
||||
|
||||
// Positive (slime) constraints only; positions may be sparse.
|
||||
// Each surviving residue has a single interval. Keeping the first cell's
|
||||
// two residues makes intersection constant-space. Check negative cells on emit.
|
||||
template <class Emit>
|
||||
SLIME_INTERVAL_HD SLIME_INTERVAL_INLINE void solveIntervals(uint64_t low, const sr::CellTerm *cells,
|
||||
int count, Emit &emit) {
|
||||
low &= (1ULL << kLowerBits) - 1;
|
||||
uint32_t q = uint32_t(sr::nextStateFromTerm(low, cells[0].term) >> 17);
|
||||
if (q & 1U)
|
||||
return;
|
||||
uint32_t b = q >> 18;
|
||||
uint32_t r = q & ((1U << 18) - 1);
|
||||
uint32_t threshold = kUpperSize - b;
|
||||
uint32_t residue[2] = {(r % 5 + 5 - b % 5) % 5, 0};
|
||||
residue[1] = (residue[0] + 2) % 5;
|
||||
uint32_t lo[2] = {0, threshold}, hi[2] = {threshold, kUpperSize};
|
||||
unsigned active = 0;
|
||||
for (int k = 0; k < 2; ++k)
|
||||
if (sr::firstWithResidue(lo[k], residue[k]) < hi[k])
|
||||
active |= 1U << k;
|
||||
for (int i = 1; i < count && active; ++i) {
|
||||
q = uint32_t(sr::nextStateFromTerm(low, cells[i].term) >> 17);
|
||||
if (q & 1U)
|
||||
return;
|
||||
b = q >> 18;
|
||||
r = q & ((1U << 18) - 1);
|
||||
threshold = kUpperSize - b;
|
||||
const uint32_t before = (r % 5 + 5 - b % 5) % 5;
|
||||
const uint32_t after = (before + 2) % 5;
|
||||
for (int k = 0; k < 2; ++k)
|
||||
if (active & (1U << k)) {
|
||||
if (residue[k] == before)
|
||||
hi[k] = hi[k] < threshold ? hi[k] : threshold;
|
||||
else if (residue[k] == after)
|
||||
lo[k] = lo[k] > threshold ? lo[k] : threshold;
|
||||
else {
|
||||
active &= ~(1U << k);
|
||||
continue;
|
||||
}
|
||||
if (sr::firstWithResidue(lo[k], residue[k]) >= hi[k])
|
||||
active &= ~(1U << k);
|
||||
}
|
||||
}
|
||||
for (int k = 0; k < 2; ++k)
|
||||
if (active & (1U << k)) {
|
||||
for (uint32_t t = sr::firstWithResidue(lo[k], residue[k]); t < hi[k]; t += 5) {
|
||||
const uint64_t seed =
|
||||
low + (uint64_t((kHalfDeltaInverse * t) & kUpperMask) << kLowerBits);
|
||||
if (sr::verifyPattern(seed, cells, count))
|
||||
emit(seed);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A cheap necessary condition before high-bit interval solving.
|
||||
// Adding the common high-bit shift can wrap q_i-q_0 once: delta mod 10 is 0 or 8.
|
||||
SLIME_INTERVAL_HD SLIME_INTERVAL_INLINE bool
|
||||
differenceFilter(uint64_t low, const sr::CellTerm *cells, int count) {
|
||||
const uint32_t q0 = uint32_t(sr::nextStateFromTerm(low, cells[0].term) >> 17);
|
||||
for (int i = 1; i < count; ++i) {
|
||||
const uint32_t qi = uint32_t(sr::nextStateFromTerm(low, cells[i].term) >> 17);
|
||||
const uint32_t delta = (qi - q0) & 0x7fffffffU;
|
||||
const uint32_t r = delta % 10;
|
||||
if (r != 0 && r != 8)
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
} // namespace slime
|
||||
|
||||
#undef SLIME_INTERVAL_HD
|
||||
#undef SLIME_INTERVAL_INLINE
|
||||
|
|
@ -1,23 +0,0 @@
|
|||
# 博客测量样本
|
||||
|
||||
保留[博客最终性能表](https://yaossg.com/site/docs/slime)对应的历史样本,测于 2026-10-19:
|
||||
AMD Ryzen 7 5800H、NVIDIA GeForce RTX 3060 Laptop GPU。它们不是本次整理后重新测得的性能。
|
||||
|
||||
| 文件 | 内容 | 当前复现入口 |
|
||||
| --- | --- | --- |
|
||||
| `reverse.json` | 区间、输出差、预计算和成组筛选的逐轮样本 | `examples/bin/reverse` |
|
||||
| `reuse.json` | 重复类与不同类输入的三版批次计时样本 | `examples/bin/reuse` |
|
||||
| `full-search.json` | 正推吞吐样本、单点与半径 512 的 CLI 扫描样本 | `examples/bin/brute`、`bench/bin/slime-bench` |
|
||||
|
||||
`reverse.json` 的 `rows` 按博客顺序列出五版算法的历史样本;
|
||||
其中剩余 30 位枚举为五轮中位数,区间及后三版为另一轮对照的 21 轮中位数。
|
||||
当前 `reverse` 为便于复现,将五版合并到同一个程序轮换测量,不能据此认为旧数据来自这份整理后的源码。
|
||||
|
||||
复用输入保存在 `examples/data/`。历史数据中的计时口径见博客与示例说明;
|
||||
`samples_ms` 为逐轮时间,`median_ms` 为中位数(均以毫秒计)。
|
||||
`full-search.json` 的 CLI 样本计完整扫描墙钟,`brute` 的样本计 kernel 时间;
|
||||
其中 `projected_full48_ms` 是吞吐外推。
|
||||
不同阶段和不同输入的加速比不可直接相乘。新跑分请另存到 `artifacts/`。
|
||||
|
||||
已知图案、种子及预期计数分别放在 `bench/testdata/` 和 `examples/data/known-5x5.json`,
|
||||
测试不依赖这些历史性能数据。
|
||||
|
|
@ -1,58 +0,0 @@
|
|||
{
|
||||
"brute": {
|
||||
"count": 17179869184,
|
||||
"samples_ms": [
|
||||
300.036,
|
||||
321.742,
|
||||
332.635,
|
||||
321.361,
|
||||
326.042
|
||||
],
|
||||
"median_ms": 321.742,
|
||||
"projected_full48_ms": 5271420.928
|
||||
},
|
||||
"cli_known": {
|
||||
"center": [
|
||||
51069,
|
||||
419124
|
||||
],
|
||||
"radius_chunks": 0,
|
||||
"square_size": 5,
|
||||
"anchors": 1,
|
||||
"position_batch": 32,
|
||||
"job_batch": 2048,
|
||||
"cache_classes": 4096,
|
||||
"matches": 24,
|
||||
"samples_ms": [
|
||||
3.6075,
|
||||
1.783925,
|
||||
1.660317,
|
||||
1.666167,
|
||||
1.830725,
|
||||
1.766916,
|
||||
1.75565
|
||||
],
|
||||
"median_ms": 1.766916
|
||||
},
|
||||
"cli_region": {
|
||||
"center": [
|
||||
0,
|
||||
0
|
||||
],
|
||||
"radius_chunks": 512,
|
||||
"square_size": 5,
|
||||
"anchors": 525313,
|
||||
"position_batch": 128,
|
||||
"job_batch": 2048,
|
||||
"cache_classes": 4096,
|
||||
"matches": 0,
|
||||
"samples_ms": [
|
||||
4406.497334,
|
||||
4206.928895,
|
||||
4306.823532,
|
||||
4181.983991,
|
||||
4355.03335
|
||||
],
|
||||
"median_ms": 4306.823532
|
||||
}
|
||||
}
|
||||
|
|
@ -1,94 +0,0 @@
|
|||
{
|
||||
"mixed512": {
|
||||
"positions": 32768,
|
||||
"jobs": 15424,
|
||||
"matches": 0,
|
||||
"rows": [
|
||||
{
|
||||
"mode": 1,
|
||||
"classes": 32768,
|
||||
"active_positions": 32768,
|
||||
"samples_ms": [
|
||||
147.004937,
|
||||
149.773603,
|
||||
154.089889,
|
||||
146.688235,
|
||||
157.906047
|
||||
],
|
||||
"median_ms": 149.773603
|
||||
},
|
||||
{
|
||||
"mode": 2,
|
||||
"classes": 512,
|
||||
"active_positions": 32768,
|
||||
"samples_ms": [
|
||||
16.078712,
|
||||
16.835057,
|
||||
16.276929,
|
||||
15.57441,
|
||||
17.099009
|
||||
],
|
||||
"median_ms": 16.276929
|
||||
},
|
||||
{
|
||||
"mode": 3,
|
||||
"classes": 512,
|
||||
"active_positions": 1216,
|
||||
"samples_ms": [
|
||||
9.526938,
|
||||
10.984208,
|
||||
12.278617,
|
||||
9.392953,
|
||||
10.389708
|
||||
],
|
||||
"median_ms": 10.389708
|
||||
}
|
||||
]
|
||||
},
|
||||
"random4096": {
|
||||
"positions": 4096,
|
||||
"jobs": 2960,
|
||||
"matches": 0,
|
||||
"rows": [
|
||||
{
|
||||
"mode": 1,
|
||||
"classes": 4096,
|
||||
"active_positions": 4096,
|
||||
"samples_ms": [
|
||||
21.293458,
|
||||
21.163675,
|
||||
20.567625,
|
||||
20.537725,
|
||||
20.631108
|
||||
],
|
||||
"median_ms": 20.631108
|
||||
},
|
||||
{
|
||||
"mode": 2,
|
||||
"classes": 4096,
|
||||
"active_positions": 4096,
|
||||
"samples_ms": [
|
||||
22.357291,
|
||||
22.729308,
|
||||
22.8618,
|
||||
22.176808,
|
||||
22.662575
|
||||
],
|
||||
"median_ms": 22.662575
|
||||
},
|
||||
{
|
||||
"mode": 3,
|
||||
"classes": 4096,
|
||||
"active_positions": 118,
|
||||
"samples_ms": [
|
||||
22.191759,
|
||||
22.989958,
|
||||
21.745316,
|
||||
21.4955,
|
||||
22.618483
|
||||
],
|
||||
"median_ms": 22.191759
|
||||
}
|
||||
]
|
||||
}
|
||||
}
|
||||
|
|
@ -1,129 +0,0 @@
|
|||
{
|
||||
"anchor": [
|
||||
51069,
|
||||
419124
|
||||
],
|
||||
"roots": 84,
|
||||
"lower35": 11010048,
|
||||
"rows": [
|
||||
{
|
||||
"mode": "low18_enumerate30",
|
||||
"median_ms": 1692.736572,
|
||||
"samples_ms": [
|
||||
1709.381592,
|
||||
1685.830688,
|
||||
1692.736572,
|
||||
1714.200562,
|
||||
1681.941528
|
||||
]
|
||||
},
|
||||
{
|
||||
"mode": "intervals_only",
|
||||
"median_ms": 0.780287981,
|
||||
"samples_ms": [
|
||||
0.780287981,
|
||||
0.7792639732,
|
||||
0.7823359966,
|
||||
0.7792639732,
|
||||
0.780287981,
|
||||
0.780287981,
|
||||
0.7813119888,
|
||||
0.780287981,
|
||||
0.7813119888,
|
||||
0.780287981,
|
||||
0.780287981,
|
||||
0.780287981,
|
||||
0.9953280091,
|
||||
0.780287981,
|
||||
0.7792639732,
|
||||
0.780287981,
|
||||
0.7813119888,
|
||||
0.780287981,
|
||||
0.7813119888,
|
||||
0.780287981,
|
||||
0.780287981
|
||||
]
|
||||
},
|
||||
{
|
||||
"mode": "difference_intervals",
|
||||
"median_ms": 0.318464011,
|
||||
"samples_ms": [
|
||||
0.318464011,
|
||||
0.3174400032,
|
||||
0.3194879889,
|
||||
0.318464011,
|
||||
0.3133440018,
|
||||
0.3194879889,
|
||||
0.3194879889,
|
||||
0.318464011,
|
||||
0.318464011,
|
||||
0.3143680096,
|
||||
0.318464011,
|
||||
0.3174400032,
|
||||
0.3194879889,
|
||||
0.318464011,
|
||||
0.3174400032,
|
||||
0.3174400032,
|
||||
0.3194879889,
|
||||
0.5335040092,
|
||||
0.3133440018,
|
||||
0.3194879889,
|
||||
0.318464011
|
||||
]
|
||||
},
|
||||
{
|
||||
"mode": "precompute_intervals",
|
||||
"median_ms": 0.2641919851,
|
||||
"samples_ms": [
|
||||
0.2641919851,
|
||||
0.2641919851,
|
||||
0.4423680007,
|
||||
0.2641919851,
|
||||
0.2641919851,
|
||||
0.2641919851,
|
||||
0.2641919851,
|
||||
0.2641919851,
|
||||
0.2641919851,
|
||||
0.2641919851,
|
||||
0.2641919851,
|
||||
0.258047998,
|
||||
0.2682879865,
|
||||
0.2641919851,
|
||||
0.2652159929,
|
||||
0.2641919851,
|
||||
0.2631680071,
|
||||
0.2641919851,
|
||||
0.2641919851,
|
||||
0.2631680071,
|
||||
0.2641919851
|
||||
]
|
||||
},
|
||||
{
|
||||
"mode": "group_intervals",
|
||||
"median_ms": 0.1556479931,
|
||||
"samples_ms": [
|
||||
0.1556479931,
|
||||
0.1556479931,
|
||||
0.1576959938,
|
||||
0.1556479931,
|
||||
0.1556479931,
|
||||
0.1556479931,
|
||||
0.1566720009,
|
||||
0.1556479931,
|
||||
0.1556479931,
|
||||
0.1556479931,
|
||||
0.1556479931,
|
||||
0.1546240002,
|
||||
0.1556479931,
|
||||
0.1546240002,
|
||||
0.1556479931,
|
||||
0.1556479931,
|
||||
0.1556479931,
|
||||
0.1556479931,
|
||||
0.1556479931,
|
||||
0.1556479931,
|
||||
0.1556479931
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
156
slime.cpp
Normal file
156
slime.cpp
Normal file
|
|
@ -0,0 +1,156 @@
|
|||
// part 1: header
|
||||
#include <cstdint>
|
||||
|
||||
struct JavaRandom {
|
||||
int64_t seed;
|
||||
|
||||
JavaRandom(int64_t seed) : seed((seed ^ 0x5DEECE66DLL) & ((1LL << 48) - 1)) {}
|
||||
|
||||
int32_t next(int bits) {
|
||||
seed = (seed * 0x5DEECE66DLL + 0xBLL) & ((1LL << 48) - 1);
|
||||
return (int32_t)((uint64_t)seed >> (48 - bits));
|
||||
}
|
||||
|
||||
int32_t nextInt(int32_t n) {
|
||||
if ((n & -n) == n) // n is a power of 2
|
||||
return (int32_t)((n * (int64_t)next(31)) >> 31);
|
||||
|
||||
int32_t bits, val;
|
||||
do {
|
||||
bits = next(31);
|
||||
val = bits % n;
|
||||
} while (bits - val + (n - 1) < 0);
|
||||
return val;
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
bool isSlimeChunk(int64_t worldSeed, int32_t chunkX, int32_t chunkZ) {
|
||||
int64_t seed = worldSeed +
|
||||
(int64_t)(chunkX * chunkX * 4987142) +
|
||||
(int64_t)(chunkX * 5947611) +
|
||||
(int64_t)(chunkZ * chunkZ) * 4392871LL +
|
||||
(int64_t)(chunkZ * 389711) ^ 987234911LL;
|
||||
JavaRandom rand(seed);
|
||||
return rand.nextInt(10) == 0;
|
||||
}
|
||||
|
||||
bool isSlimeChunkNxN(int64_t worldSeed, int32_t n, int32_t d, int32_t startX, int32_t startZ) {
|
||||
int count = n * n;
|
||||
for (int32_t x = 0; x < n; ++x) {
|
||||
for (int32_t z = 0; z < n; ++z) {
|
||||
count -= !isSlimeChunk(worldSeed, startX + x, startZ + z);
|
||||
if (count < d) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// part 2: main
|
||||
|
||||
#include <iostream>
|
||||
#include <atomic>
|
||||
#include <thread>
|
||||
#include <vector>
|
||||
#include <chrono>
|
||||
|
||||
std::atomic<int64_t> foundSeeds(0);
|
||||
|
||||
bool checkSingleSeed(int64_t seed, int32_t n, int32_t d, int32_t radius) {
|
||||
for (int32_t x = -radius; x <= radius; ++x) {
|
||||
for (int32_t z = -radius; z <= radius; ++z) {
|
||||
if (isSlimeChunkNxN(seed, n, d, x, z)) {
|
||||
printf("found seed: %ld, at (%d, %d)\n", seed, x, z);
|
||||
foundSeeds.fetch_add(1, std::memory_order_relaxed);
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void checkSeeds(int64_t startSeed, int64_t endSeed, int32_t n, int32_t d, int32_t radius) {
|
||||
for (int64_t seed = startSeed; seed < endSeed; ++seed) {
|
||||
checkSingleSeed(seed, n, d, radius);
|
||||
}
|
||||
}
|
||||
|
||||
struct Args {
|
||||
int64_t startSeed = 0;
|
||||
int64_t endSeed = 1'000'000;
|
||||
int numThreads = std::thread::hardware_concurrency();
|
||||
int chunkSize = 3;
|
||||
int numChunks = 9;
|
||||
int radius = 100;
|
||||
};
|
||||
|
||||
[[noreturn]] void help(int exitCode = 1) {
|
||||
std::cerr << "Usage: slime [args...]" << std::endl;
|
||||
std::cerr << " -s <startSeed> Starting seed (default: 0)" << std::endl;
|
||||
std::cerr << " -e <endSeed> Ending seed (default: 1000000)" << std::endl;
|
||||
std::cerr << " -p <numThreads> Number of threads to use (default: number of CPU cores)" << std::endl;
|
||||
std::cerr << " -n <chunkSize> Size of the slime chunk area to check (default: 3)" << std::endl;
|
||||
std::cerr << " -d <numChunks> Number of chunks within square of chunkSize to check (default: square of chunkSize)" << std::endl;
|
||||
std::cerr << " -r <radius> Radius of chunks around (0, 0) to check (default: 100)" << std::endl;
|
||||
exit(exitCode);
|
||||
}
|
||||
|
||||
Args parseArgs(int argc, char* argv[]) {
|
||||
Args args;
|
||||
if (argc == 2 && std::string(argv[1]) == "--help") {
|
||||
help(0);
|
||||
}
|
||||
|
||||
bool setNumChunks = false;
|
||||
|
||||
for (int i = 1; i < argc; i += 2) {
|
||||
if (std::string(argv[i]) == "-s") {
|
||||
args.startSeed = std::stoll(argv[i + 1]);
|
||||
} else if (std::string(argv[i]) == "-e") {
|
||||
args.endSeed = std::stoll(argv[i + 1]);
|
||||
} else if (std::string(argv[i]) == "-p") {
|
||||
args.numThreads = std::stoi(argv[i + 1]);
|
||||
} else if (std::string(argv[i]) == "-n") {
|
||||
args.chunkSize = std::stoi(argv[i + 1]);
|
||||
} else if (std::string(argv[i]) == "-d") {
|
||||
args.numChunks = std::stoi(argv[i + 1]);
|
||||
setNumChunks = true;
|
||||
} else if (std::string(argv[i]) == "-r") {
|
||||
args.radius = std::stoi(argv[i + 1]);
|
||||
} else {
|
||||
help();
|
||||
}
|
||||
}
|
||||
if (!setNumChunks) {
|
||||
args.numChunks = args.chunkSize * args.chunkSize;
|
||||
}
|
||||
if (args.startSeed < args.endSeed && args.numThreads > 0 && args.chunkSize > 0 && args.numChunks > 0 && args.numChunks <= args.chunkSize * args.chunkSize && args.radius > 0) {
|
||||
return args;
|
||||
}
|
||||
help();
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
auto [startSeed, endSeed, numThreads, n, d, radius] = parseArgs(argc, argv);
|
||||
|
||||
std::cout << "Searching for seeds with at least " << d << " slime chunks within " << n << "x" << n << " chunks within a radius of " << radius << "." << std::endl;
|
||||
std::cout << "Checking seeds from " << startSeed << " to " << endSeed << " with " << numThreads << " threads." << std::endl;
|
||||
|
||||
auto startTime = std::chrono::high_resolution_clock::now();
|
||||
auto totalSeeds = endSeed - startSeed;
|
||||
std::vector<std::thread> threads;
|
||||
int64_t seedsPerThread = totalSeeds / numThreads;
|
||||
for (int i = 0; i < numThreads; ++i) {
|
||||
int64_t startSeed = i * seedsPerThread;
|
||||
int64_t endSeed = (i == numThreads - 1) ? totalSeeds : startSeed + seedsPerThread;
|
||||
threads.emplace_back(checkSeeds, startSeed, endSeed, n, d, radius);
|
||||
}
|
||||
for (auto& t : threads) {
|
||||
t.join();
|
||||
}
|
||||
auto endTime = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> elapsed = endTime - startTime;
|
||||
std::cout << "It took " << elapsed.count() << " seconds to check " << totalSeeds << " seeds, found " << foundSeeds.load() << " seeds that meet the condition." << std::endl;
|
||||
return 0;
|
||||
}
|
||||
177
slime.cu
Normal file
177
slime.cu
Normal file
|
|
@ -0,0 +1,177 @@
|
|||
// part 1: header
|
||||
#include <cstdint>
|
||||
#include <cuda.h>
|
||||
#include <cuda_runtime_api.h>
|
||||
#include <stdio.h>
|
||||
|
||||
struct JavaRandom {
|
||||
int64_t seed;
|
||||
|
||||
__device__ JavaRandom(int64_t seed) : seed((seed ^ 0x5DEECE66DLL) & ((1LL << 48) - 1)) {}
|
||||
|
||||
__device__ int32_t next(int bits) {
|
||||
seed = (seed * 0x5DEECE66DLL + 0xBLL) & ((1LL << 48) - 1);
|
||||
return (int32_t)((uint64_t)seed >> (48 - bits));
|
||||
}
|
||||
|
||||
__device__ int32_t nextInt(int32_t n) {
|
||||
if ((n & -n) == n) // n is a power of 2
|
||||
return (int32_t)((n * (int64_t)next(31)) >> 31);
|
||||
|
||||
int32_t bits, val;
|
||||
do {
|
||||
bits = next(31);
|
||||
val = bits % n;
|
||||
} while (bits - val + (n - 1) < 0);
|
||||
return val;
|
||||
|
||||
}
|
||||
};
|
||||
|
||||
__device__ bool isSlimeChunk(int64_t worldSeed, int32_t chunkX, int32_t chunkZ) {
|
||||
int64_t seed = worldSeed +
|
||||
(int64_t)(chunkX * chunkX * 4987142) +
|
||||
(int64_t)(chunkX * 5947611) +
|
||||
(int64_t)(chunkZ * chunkZ) * 4392871LL +
|
||||
(int64_t)(chunkZ * 389711) ^ 987234911LL;
|
||||
JavaRandom rand(seed);
|
||||
return rand.nextInt(10) == 0;
|
||||
}
|
||||
|
||||
__device__ bool isSlimeChunkNxN(int64_t worldSeed, int32_t n, int32_t d, int32_t startX, int32_t startZ) {
|
||||
int count = n * n;
|
||||
for (int32_t x = 0; x < n; ++x) {
|
||||
for (int32_t z = 0; z < n; ++z) {
|
||||
count -= !isSlimeChunk(worldSeed, startX + x, startZ + z);
|
||||
if (count < d) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
__device__ bool checkSingleSeed(int64_t seed, int32_t n, int32_t d, int32_t radius) {
|
||||
for (int32_t x = -radius; x <= radius; ++x) {
|
||||
for (int32_t z = -radius; z <= radius; ++z) {
|
||||
if (isSlimeChunkNxN(seed, n, d, x, z)) {
|
||||
printf("found seed: %ld, at (%d, %d)\n", seed, x, z);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// part 2: main
|
||||
#include <iostream>
|
||||
#include <chrono>
|
||||
|
||||
__global__ void checkSeedsKernel(int64_t startSeed, int32_t n, int32_t d, int32_t radius, int* foundCount) {
|
||||
int64_t seed = startSeed + blockIdx.x * blockDim.x + threadIdx.x;
|
||||
atomicAdd(foundCount, checkSingleSeed(seed, n, d, radius));
|
||||
}
|
||||
|
||||
struct Args {
|
||||
int64_t startSeed = 0;
|
||||
int64_t endSeed = 1'000'000;
|
||||
int chunkSize = 3;
|
||||
int numChunks = 9;
|
||||
int radius = 100;
|
||||
};
|
||||
|
||||
[[noreturn]] void help(int exitCode = 1) {
|
||||
std::cerr << "Usage: slime [args...]" << std::endl;
|
||||
std::cerr << " -s <startSeed> Starting seed (default: 0)" << std::endl;
|
||||
std::cerr << " -e <endSeed> Ending seed (default: 1000000)" << std::endl;
|
||||
std::cerr << " -n <chunkSize> Size of the slime chunk area to check (default: 3)" << std::endl;
|
||||
std::cerr << " -d <numChunks> Number of chunks within square of chunkSize to check (default: square of chunkSize)" << std::endl;
|
||||
std::cerr << " -r <radius> Radius of chunks around (0, 0) to check (default: 100)" << std::endl;
|
||||
exit(exitCode);
|
||||
}
|
||||
|
||||
Args parseArgs(int argc, char* argv[]) {
|
||||
Args args;
|
||||
if (argc == 2 && std::string(argv[1]) == "--help") {
|
||||
help(0);
|
||||
}
|
||||
|
||||
bool setNumChunks = false;
|
||||
|
||||
for (int i = 1; i < argc; i += 2) {
|
||||
if (std::string(argv[i]) == "-s") {
|
||||
args.startSeed = std::stoll(argv[i + 1]);
|
||||
} else if (std::string(argv[i]) == "-e") {
|
||||
args.endSeed = std::stoll(argv[i + 1]);
|
||||
} else if (std::string(argv[i]) == "-n") {
|
||||
args.chunkSize = std::stoi(argv[i + 1]);
|
||||
} else if (std::string(argv[i]) == "-d") {
|
||||
args.numChunks = std::stoi(argv[i + 1]);
|
||||
setNumChunks = true;
|
||||
} else if (std::string(argv[i]) == "-r") {
|
||||
args.radius = std::stoi(argv[i + 1]);
|
||||
} else {
|
||||
help();
|
||||
}
|
||||
}
|
||||
if (!setNumChunks) {
|
||||
args.numChunks = args.chunkSize * args.chunkSize;
|
||||
}
|
||||
if (args.startSeed < args.endSeed && args.chunkSize > 0 && args.radius > 0) {
|
||||
return args;
|
||||
}
|
||||
help();
|
||||
}
|
||||
|
||||
void execute(int64_t startSeed, int64_t endSeed, int32_t n, int32_t d, int32_t radius, int* d_foundCount) {
|
||||
int threadsPerBlock = 64;
|
||||
int blocks = (endSeed - startSeed + threadsPerBlock - 1) / threadsPerBlock;
|
||||
|
||||
checkSeedsKernel<<<blocks, threadsPerBlock>>>(startSeed, n, d, radius, d_foundCount);
|
||||
cudaDeviceSynchronize();
|
||||
}
|
||||
|
||||
void renderProgressBar(double progress) {
|
||||
int barWidth = 50;
|
||||
std::cout << "[";
|
||||
int pos = static_cast<int>(barWidth * progress);
|
||||
for (int i = 0; i <= barWidth; ++i) {
|
||||
if (i < pos) std::cout << "=";
|
||||
else if (i == pos) std::cout << ">";
|
||||
else std::cout << " ";
|
||||
}
|
||||
std::cout << "] " << int(progress * 100.0) << " %\r";
|
||||
std::cout.flush();
|
||||
}
|
||||
|
||||
int main(int argc, char* argv[]) {
|
||||
auto [startSeed, endSeed, n, d, radius] = parseArgs(argc, argv);
|
||||
|
||||
std::cout << "Searching for seeds with at least " << d << " slime chunks within " << n << "x" << n << " chunks within a radius of " << radius << "." << std::endl;
|
||||
std::cout << "Checking seeds from " << startSeed << " to " << endSeed << " with CUDA." << std::endl;
|
||||
|
||||
auto startTime = std::chrono::high_resolution_clock::now();
|
||||
auto totalSeeds = endSeed - startSeed;
|
||||
int* d_foundCount;
|
||||
int h_foundCount = 0;
|
||||
|
||||
cudaMalloc(&d_foundCount, sizeof(int));
|
||||
cudaMemcpy(d_foundCount, &h_foundCount, sizeof(int), cudaMemcpyHostToDevice);
|
||||
|
||||
int64_t batchSize = std::max((endSeed - startSeed) / 100, int64_t(1'000'000));
|
||||
renderProgressBar(0);
|
||||
for (int64_t seed = startSeed; seed < endSeed; seed += batchSize) {
|
||||
int64_t batchEnd = std::min(seed + batchSize, endSeed);
|
||||
execute(seed, batchEnd, n, d, radius, d_foundCount);
|
||||
renderProgressBar(double(batchEnd - startSeed) / totalSeeds);
|
||||
}
|
||||
std::cout << std::endl;
|
||||
|
||||
cudaMemcpy(&h_foundCount, d_foundCount, sizeof(int), cudaMemcpyDeviceToHost);
|
||||
|
||||
cudaFree(d_foundCount);
|
||||
auto endTime = std::chrono::high_resolution_clock::now();
|
||||
std::chrono::duration<double> elapsed = endTime - startTime;
|
||||
std::cout << "It took " << elapsed.count() << " seconds to check " << totalSeeds << " seeds, found " << h_foundCount << " seeds that meet the condition." << std::endl;
|
||||
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue