Compare commits

..
Author SHA1 Message Date
starcells e632fb4824 Rewrite the searcher: bit planes, and the last block searched backwards
The BFS used to walk the whole 1<<CELL_SIZE table for every edge, keep the
states in an unordered_set and the parents in a second unordered_map.  For
the six plane full adder layer 4 is 642729 states, and layer 5 never
finished (75s, heading for GBs).

A state is now CELL_SIZE bit planes, each a truth table over only the
inputs that influence the answer, so a state is CELL_SIZE * 2^K bits --
48 bits for every adder-shaped problem -- and a block is a handful of
64-bit ops.  The instruction list also lost its duplicated encodings
(378 instead of 762 for six planes).

The bigger win is not expanding the last layer at all.  A block clears its
own plane, so for the goal to be its target goal[s] must be 0; the
preimages of the goal under each such block are enumerated exactly and
looked up in the BFS table.  For full_add that is 9.3e3 lookups instead of
7.4e9 edges, which turns "unreachable" into "5 blocks, proven shortest,
7 seconds".

Results (r8veritas<6>, max_depth 5, MSVC /O2):

    copy          2   33 states
    clb_and       3   3398
    clb_half_add  4   32898
    half_add      4   32898
    full_add_S    4   656528
    full_add_Co   5   20388515
    full_add      5   20388515      7.2s

All of those lengths are proven minimal, and the old bit_raw_add needed
eight blocks for the same slice.

Richer instruction sets were tried as well -- per destination OR/XOR, and
adding set_0 on top (6144 blocks) -- and neither admits a four-block full
adder, so five is not an artifact of the model.

CELL_SIZE stays a template parameter; the truth table compression picks K
at run time and dispatches on it.  CMake flags got the same fix as r8asm:
stop clobbering CMAKE_CXX_FLAGS so Debug keeps /RTC1 and MSVC keeps /EHsc.
2026-11-05 23:35:56 +08:00
4 changed files with 725 additions and 310 deletions

No files matched your search

+8 -1
View File
@@ -2,12 +2,19 @@ cmake_minimum_required(VERSION 3.10)
project(R8Veritas)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
include_directories(include)
add_library(r8veritas_core src/r8veritas.cc)
set(CMAKE_CXX_FLAGS "-O3 -march=native -DNDEBUG")
# 原先是 set(CMAKE_CXX_FLAGS "-O3 -march=native -DNDEBUG"):
# 它把 CMake 的整套默认 flag 换掉了 —— MSVC 下等于丢了 /EHsc,还把 -O3 塞进
# 了 Debug 配置,和 /RTC1 冲突(D8016)。CMake 的 Release 配置本来就带
# -O3 / /O2 和 NDEBUG,所以这里只补 -march=native,且只给非 MSVC 的 Release。
if(NOT MSVC)
add_compile_options($<$<CONFIG:Release>:-march=native>)
endif()
add_executable(r8veritas_test tests/r8_test.cc)
target_link_libraries(r8veritas_test r8veritas_core)
+169
View File
@@ -0,0 +1,169 @@
# R8Veritas
ROT-8 / R8ASM 的最短程序搜索器。
给两个真值表(输入 → 输出),找**最短**的一段中间代码把它算出来;代码可以直接翻译成
R8ASM 的 `biz` 块。
## 中间代码
一条指令(一层)就是一个 `biz` 块:
```asm
.tp s
biz
.tp b ; mask 里每一位一条
set_1 / flb
.tp s
flb
rnz
```
- `s` 是被牺牲的那一位:块的条件是 `bit s`,块结束时它一定被清掉
- `mask` 里的每一位 `b` 会被 `cond`(`bit s` 为 1 的那些输入)或上 / 异或上
- 一层 = 一个块,所以长度 = 层数
这些位来自不同的 cell,是调用方传进来的参数(`%1`..`%n`),一层只是一次条件重写。
## 状态与位平面
一个状态是整张真值表:每个输入组合下,这些位各自的值。
按位平面来存(`plane[b]` = 所有输入下第 b 位的取值),一层就变成几个 64 位操作:
```
cond = plane[s]; plane[s] = 0;
for b in mask: plane[b] |= cond (set_1)
plane[b] ^= cond (flb)
```
`compress_stat_space` 会先清掉不影响答案的输入 —— 加法器这类问题上往往只剩 3 个相关输入,
于是每个 plane 只是一张 8 bit 真值表,整个状态 48 bit,塞得进一个 `uint64_t`。
参数个数是模板参数 `CELL_SIZE`,搜索里没有写死。
## 搜索
1. 前向 BFS 到第 d−1 层,每个状态记下它是哪条指令、从哪个状态来的
2. 最后一层不前向展开。因为指令会清掉自己的平面,目标态必须满足 `goal[s] == 0`;
对每个合法的块,把目标的全部一步前驱枚举出来(异或目的地唯一,或目的地按位自由),
拿这些前驱去 BFS 表里查
3. 找到了 → 长度 d 且最优(前 1..d−1 层已经穷尽)
4. 没找到 → 展开第 d 层,继续
最后一步反向查表是性能的关键:full_add 上第 5 层直接展开要算
`19.7e6 × 378 ≈ 7.4e9` 条边,而枚举目标的 1 步前驱只有 `9.3e3` 次查表。
> 反向枚举要遍历 `cond` 的 `2^K` 种取值,所以只在 `K <= 3` 时启用;`K > 3` 时最后一层仍然前向展开。
## 结果
`r8veritas<6>`,`max_depth = 5`(单核,MSVC /O2):
| 问题 | 最短层数 | 状态数 | 用时 | 最优性 |
|---|---|---|---|---|
| copy (A → bit0,bit1) | 2 | 33 | 0.0005 s | 证明 |
| clb_and (A&B → bit2) | 3 | 3,398 | 0.0008 s | 证明 |
| clb_half_add | 4 | 32,898 | 0.008 s | 证明 |
| half_add | 4 | 32,898 | 0.008 s | 证明 |
| full_add_S (S → bit3) | 4 | 656,528 | 0.10 s | 证明 |
| full_add_Co (Co → bit4) | 5 | 20,388,515 | 7.1 s | 证明 |
| full_add | 5 | 20,388,515 | 7.2 s | 证明 |
full_add 的最短程序(`%1..%6` 对应 6 个参数 cell):
```
sacrifice %1, FLIP {%2,%3,%6}
sacrifice %2, FLIP {%1,%4,%6}
sacrifice %3, FLIP {%1,%2,%5,%6}
sacrifice %4, SET1 {%3,%5}
sacrifice %6, FLIP {%1,%2,%3,%4,%5}
```
`output_ins(..., false)` 打出来就是 5 个 r8asm 块,可以直接替换 `raw_add.r8asm` 里的
`bit_raw_add`(那一版是 8 个块)。
## 试过但没能把层数压到 4 的做法
full_add 上,下面每一种都做了穷尽搜索,都没有 4 层解:
| 放宽方式 | 指令数 | 搜索规模 | 结论 |
|---|---|---|---|
| 每目的地独立选 OR / XOR | 1,458 | 前向 3 层 1.73e6 状态 + 反向 20,096 前驱 | 无 4 层 |
| 再加 set_0(`&~cond`) | 6,144 | 前向 3 层 9.56e6 状态 + 反向 40,928 | 无 4 层 |
| 参数从 6 个加到 7 / 8 个 | 2,040(8 个时) | 穷尽 5.4e6 / 44.1e6 状态 | 无 4 层 |
| 条件位 ≠ 牺牲位 | 2,304 | 前向 3 层 3.17e6 状态 + 反向 1,280 | 无 4 层 |
最后一种是这套指令里唯一能让条件位活下来的写法:
```asm
.tp s
biz
.tp b
set_1 ; 目的地可以各自选 set_1 / flb / set_0
.tp t
set_0 ; rnz 测的是这里,t 才是被清掉的那个
rnz
```
它比原模型严格更强(原模型只能 `s == t`),但 full_add 仍然要 5 层。
至于完全不牺牲:`biz`/`rnz` 的循环必须让 `rnz` 测到的那个 cell 变成 0 才会退出,
所以一层里清掉某一位是硬约束,只能换位置,不能取消。
## 还能往哪儿走
一层 = 一个条件块这个粒度下,full_add 的地板就是 5。要在 4 层以内,只能让一层表达力更强,
剩下的方向是复合条件:
```asm
.tp %1
biz
.tp %2
biz
... ; 条件变成 %1 AND %2
.tp %7
set_0
rnz
.tp %6
set_0
rnz
```
嵌套 `biz` 在 ROT-8 里完全合法,于是一层可以写好几个「与」条件的小块,
`Co = AB|AC|BC` 就能在一层里用三个 `A&B` 小块直接置位。层数能掉到 2–3,
但磁带会变长(每个小块自带一组 `biz`/`set_0`/`rnz`)。
也就是「层数最少」和「代码最短」在嵌套条件下会分叉,得先确定要哪个指标。
## 用法
```cpp
#include "r8veritas.hh"
r8veritas<6> v;
v.initialize_nicknames();
v.initialize_tp_paths();
auto raw = v.generate_truthtable([](r8veritas<6>::cell inp) -> r8veritas<6>::cell {
// 这里写你要算的函数
});
auto compressed = v.compress_stat_space(raw);
r8veritas<6>::options opt;
opt.max_depth = 5;
auto res = v.solve(compressed, opt);
if (res.found) {
v.print_program(res.program, std::cout, false); // 直接是 r8asm
v.run_program(compressed, res.program); // 拿参考语义复核一遍
}
```
`res.proven_optimal` 为真表示:`res.program` 的长度已经被穷尽搜索证明是最短的。
## 限制
- 相关输入最多 6 个(状态要塞进 64 位字里)
- 反向查表需要 `2^K` 小(`K <= 3`),否则最后一层仍按前向展开
- `options.max_states` 是内存闸门,撞到它会返回「搜索未完成」而不是假装最优
+471 -267
View File
@@ -1,333 +1,537 @@
#ifndef R8VERITAS
#define R8VERITAS
// R8Veritas -- shortest program search over the rot-8 "sacrifice block":
//
// .tp s
// biz
// .tp b ; once per b in the mask
// set_1 / flb ; OR / XOR
// .tp s
// flb
// rnz
//
// A state is the whole truth table of the working cell: for every input
// combination, what the cell holds. Written as bit planes -- plane b is bit
// b of the cell, over all inputs -- one block becomes a handful of 64-bit
// operations:
//
// cond = plane[s]; plane[s] = 0;
// for b in mask: plane[b] |= cond (set_1)
// plane[b] ^= cond (flb)
//
// Search strategy:
// * only the input bits that influence the answer survive (the old
// compress_stat_space), so a plane is a 2^K bit truth table instead of
// 2^CELL_SIZE, and the whole state is CELL_SIZE * 2^K bits
// * forward BFS keeps every reachable state of depth < d plus the block
// that produced it
// * the last block is not searched forward. A block clears its own
// plane, so the goal can only be its target if goal[s] == 0; for each
// such block every preimage of the goal is generated and looked up in
// the BFS table. A hit is the shortest program, and "nothing below d,
// something at d" is a proof.
//
// The backward step enumerates 2^K values of the condition, so it is only
// used while K <= 3; above that the last layer is expanded forward like the
// others (still a lot cheaper than the old implementation).
#include <algorithm>
#include <array>
#include <bit>
#include <bitset>
#include <chrono>
#include <cstddef>
#include <cstdint>
#include <functional>
#include <iostream>
#include <map>
#include <optional>
#include <ostream>
#include <queue>
#include <set>
#include <stack>
#include <string>
#include <unordered_map>
#include <unordered_set>
#include <utility>
#define CELL_SIZE_BITWIDTH std::bit_width(unsigned(CELL_SIZE))
#define INS_SIZE (CELL_SIZE + 1)
// mask and opcode
#define INS_BYTECODE_SIZE (INS_SIZE + CELL_SIZE_BITWIDTH)
// mask,opcode and sacrifice
#include <vector>
template <int CELL_SIZE> class r8veritas {
public:
using cell = uint8_t;
using stat = std::array<r8veritas::cell, (1 << CELL_SIZE)>;
using stat = std::array<cell, (size_t(1) << CELL_SIZE)>;
using stat_ref = const stat *;
using truthtable = std::pair<r8veritas::stat_ref, r8veritas::stat_ref>;
using op = std::function<r8veritas::cell(r8veritas::cell)>;
using index = size_t;
using influence = size_t;
using ins_body = size_t;
/*
e.g. cell_size=3:
0b aaa b
^--mask ^opcode
*/
using ins_bytecode = size_t;
enum ins_opcode {
SET1 = 0,
FLIP = 1,
using truthtable = std::pair<stat_ref, stat_ref>;
using op = std::function<cell(cell)>;
// one biz block
struct instruction {
uint8_t sacrifice = 0; // plane whose bit is tested and cleared
uint8_t mask = 0; // bit b set: plane b is a destination
bool or_mode = false; // true: set_1 (|), false: flb (^)
};
struct ins {
r8veritas::ins_body bc;
r8veritas::index sacrifice;
operator const ins_bytecode() const {
return (bc << CELL_SIZE_BITWIDTH) | sacrifice;
}
struct options {
int max_depth = 5; // longest program to look for
size_t max_states = 80'000'000; // memory guard
bool verbose = false;
};
using path =
std::stack<std::pair<r8veritas::stat_ref, r8veritas::ins_bytecode>>;
struct result {
bool found = false;
// true when every program shorter than program.size() was ruled out
bool proven_optimal = false;
std::vector<instruction> program;
size_t states = 0; // states kept by the BFS
int depth_reached = 0; // deepest layer fully expanded
double seconds = 0;
std::string message;
};
std::array<std::string, CELL_SIZE> nicknames;
std::array<std::string, CELL_SIZE> tp_paths;
private:
std::array<r8veritas::influence, CELL_SIZE> all_influences;
struct compare_ins {
bool operator()(const ins &a, const ins &b) const {
auto pop_a = std::popcount(a.bc >> 1);
auto pop_b = std::popcount(b.bc >> 1);
if (pop_a != pop_b)
return pop_a < pop_b;
if (a.bc != b.bc)
return a.bc < b.bc;
return a.sacrifice < b.sacrifice;
}
};
const std::set<r8veritas::ins, compare_ins> all_ins =
[]() -> std::set<r8veritas::ins, compare_ins> {
std::set<r8veritas::ins, compare_ins> s;
for (r8veritas::index sacrifice_it = 0; sacrifice_it < CELL_SIZE;
sacrifice_it++) {
for (r8veritas::index bc_it = 0; bc_it < (1 << INS_SIZE); bc_it++) {
auto tmp = bc_it & (~(1 << (sacrifice_it + 1)));
// sacrifice shouldn't be operated,
// which means that bit in bc's mask can't be 1.
// so here I forcefully change it to 0,
// and use set to ensure it won't duplicate.
// for here's the initialization part,it's acceptable
s.insert({((tmp == 0) ? 1 : tmp), sacrifice_it});
// both bc == 0b0 and bc == 0b1 mean erasing sacrifice,so here I skip
// 0b0
}
}
return s;
}();
std::unordered_map<r8veritas::stat_ref,
std::pair<r8veritas::stat_ref, r8veritas::ins_bytecode>>
visited_op;
struct stat_hash {
size_t operator()(const stat &s) const {
size_t h = 0;
for (auto i : s) {
h ^= std::hash<r8veritas::cell>{}(i) + 0x9e3779b9 + (h << 6) + (h >> 2);
// Magic,from Boost's hash_combine.
// An explanation from MCMC here: https://zhuanlan.zhihu.com/p/574573421
}
return h;
}
};
std::unordered_set<r8veritas::stat, stat_hash> stat_pool;
std::queue<r8veritas::stat_ref> stats;
public:
r8veritas::ins to_ins(const r8veritas::ins_bytecode &bc) {
return {bc >> CELL_SIZE_BITWIDTH, bc & ((1 << CELL_SIZE_BITWIDTH) - 1)};
}
void initialize_nicknames() {
for (r8veritas::index i = 0; i < CELL_SIZE; i++) {
for (int i = 0; i < CELL_SIZE; i++)
nicknames[i] = "%" + std::to_string(i + 1);
}
return;
}
void initialize_tp_paths() {
for (r8veritas::index i = 0; i < CELL_SIZE; i++) {
for (int i = 0; i < CELL_SIZE; i++)
tp_paths[i] = ".tp " + nicknames[i];
}
// ---------------------------------------------------------------- states
stat_ref generate_empty_stat() {
stat arr{};
arr.fill(0);
return keep(arr);
}
truthtable generate_truthtable(const op &operation) {
stat in{}, out{};
for (size_t i = 0; i < (size_t(1) << CELL_SIZE); i++) {
in[i] = cell(i);
out[i] = operation(cell(i));
}
return;
return {keep(in), keep(out)};
}
r8veritas::stat_ref generate_empty_stat() {
r8veritas::stat arr;
for (r8veritas::index i = 0; i < (1 << CELL_SIZE); i++) {
arr[i] = 0;
// Clears the input bits that never influence the answer, so the search
// starts from a canonical state.
truthtable compress_stat_space(const truthtable &raw) {
stat start = *raw.first;
for (int i = 0; i < CELL_SIZE; i++) {
bool influences = false;
for (size_t j = 0; j < (size_t(1) << CELL_SIZE); j++)
if ((*raw.second)[j] != (*raw.second)[j ^ (size_t(1) << i)])
influences = true;
if (!influences)
for (size_t j = 0; j < (size_t(1) << CELL_SIZE); j++)
start[j] = cell(start[j] & ~(1u << i));
}
auto tmp_ptr = stat_pool.insert(std::move(arr)).first;
return &(*tmp_ptr);
return {keep(start), raw.second};
}
// WARNING:ST WILL BE DESTROYED
std::pair<r8veritas::stat_ref, bool> save_stat(r8veritas::stat &&st) {
auto t = stat_pool.insert(std::move(st));
return {&(*(t.first)), !t.second};
}
r8veritas::truthtable generate_truthtable(const r8veritas::op &operation) {
r8veritas::stat inp = *generate_empty_stat();
r8veritas::stat out = *generate_empty_stat();
for (r8veritas::index i = 0; i < (1 << CELL_SIZE); i++) {
inp[i] = i;
out[i] = operation(r8veritas::cell(i));
}
return (r8veritas::truthtable(save_stat(std::move(inp)).first,
save_stat(std::move(out)).first));
}
std::pair<r8veritas::stat_ref,
bool> // true means the next stat has been visited.
operate_ins(const r8veritas::stat_ref &last_stat, const r8veritas::ins &ins) {
auto key = std::pair(last_stat, r8veritas::ins_bytecode(ins));
r8veritas::stat next_stat = *last_stat;
int opcode = ins.bc & 1;
r8veritas::cell cell_mask = (ins.bc >> 1);
for (r8veritas::index i = 0; i < (1 << CELL_SIZE); i++) {
if ((next_stat[i] & (1 << ins.sacrifice)) != 0) {
next_stat[i] ^= (1 << ins.sacrifice);
if (opcode == ins_opcode::SET1) {
next_stat[i] |= cell_mask;
} else if (opcode == ins_opcode::FLIP) {
next_stat[i] ^= cell_mask;
// Applies a program with the reference semantics (one state at a time) and
// tells whether it lands on the target.
bool run_program(const truthtable &raw, const std::vector<instruction> &p,
bool verbose = false) const {
stat cur = *raw.first;
for (const auto &i : p) {
for (size_t j = 0; j < cur.size(); j++)
if (cur[j] & (1u << i.sacrifice)) {
cur[j] = cell(cur[j] & ~(1u << i.sacrifice));
for (int b = 0; b < CELL_SIZE; b++)
if (i.mask & (1 << b))
cur[j] = i.or_mode ? cell(cur[j] | (1u << b))
: cell(cur[j] ^ (1u << b));
}
if (verbose) {
output_stat(cur);
std::cout << "\n";
}
}
auto tmp = save_stat(std::move(next_stat));
visited_op.insert(std::pair(tmp.first, std::move(key)));
return tmp;
return cur == *raw.second;
}
void output_stat(const r8veritas::stat_ref &s) {
for (auto i : *s) {
std::cout << std::bitset<CELL_SIZE>(i).to_string() << " ";
// ---------------------------------------------------------------- output
void output_stat(const stat &s) const {
for (auto v : s)
std::cout << std::bitset<CELL_SIZE>(v).to_string() << " ";
}
void output_ins(const instruction &ins, std::ostream &os,
bool debug_output = true) const {
if (debug_output) {
os << "SACRIFICE: " << int(ins.sacrifice);
if (ins.mask) {
os << (ins.or_mode ? ", SET1: {" : ", FLIP: {");
bool first = true;
for (int b = 0; b < CELL_SIZE; b++)
if (ins.mask & (1 << b)) {
if (!first)
os << ',';
os << b;
first = false;
}
os << '}';
}
os << ';';
return;
}
os << tp_paths[ins.sacrifice] << "\n";
os << "biz\n";
for (int b = 0; b < CELL_SIZE; b++)
if (ins.mask & (1 << b)) {
os << '\t' << tp_paths[b] << "\n";
os << '\t' << (ins.or_mode ? "set_1" : "flb") << "\n";
}
os << '\t' << tp_paths[ins.sacrifice] << "\n";
os << "\tflb\n";
os << "rnz\n";
}
void print_program(const std::vector<instruction> &p, std::ostream &os,
bool debug_output = false) const {
for (const auto &i : p) {
output_ins(i, os, debug_output);
os << "\n";
}
}
void output_ins(const r8veritas::ins &s, bool enable_debug_output = true) {
// ---------------------------------------------------------------- search
result solve(const truthtable &raw, const options &opt = {}) {
result r;
const auto t0 = std::chrono::steady_clock::now();
auto finish = [&]() {
r.seconds =
std::chrono::duration<double>(std::chrono::steady_clock::now() - t0)
.count();
return r;
};
auto str = std::bitset<INS_SIZE>(s.bc).to_string();
std::queue<r8veritas::index> arg_list;
bool just_sacrifice = ((s.bc == 0b0) || (s.bc == 0b1));
std::reverse(&str[0], &str[CELL_SIZE]);
/* e.g.
CELL_SIZE = 4
(0b)00101 -> 01001
^ ^str[CELL_SIZE]
*/
if (!just_sacrifice) {
for (r8veritas::index i = 0; i < str.length() - 1; i++) {
if (str[i] == '1') {
arg_list.push(i);
// which input bits matter, in compression order
std::array<int, CELL_SIZE> bit_of{};
int k = 0;
for (int i = 0; i < CELL_SIZE; i++) {
for (size_t j = 0; j < (size_t(1) << CELL_SIZE); j++)
if ((*raw.second)[j] != (*raw.second)[j ^ (size_t(1) << i)]) {
bit_of[k++] = i;
break;
}
}
}
if (k > 6) {
r.message = "the answer depends on more than 6 inputs; the packed state "
"does not fit and the search would be hopeless anyway";
return finish();
}
bool is_set1 = ((s.bc & 1) == SET1);
// compressed index j -> index in the full truth table
std::vector<size_t> full(size_t(1) << k, 0);
for (size_t j = 0; j < full.size(); j++)
for (int b = 0; b < k; b++)
if (j & (size_t(1) << b))
full[j] |= size_t(1) << bit_of[b];
if (enable_debug_output) {
std::cout << "SACRIFICE: " << s.sacrifice;
if (!just_sacrifice) {
if (is_set1)
std::cout << ", SET1: {";
else
std::cout << ", FLIP: {";
while (!arg_list.empty()) {
std::cout << arg_list.front() << ',';
arg_list.pop();
}
std::cout << "\b}";
}
std::cout << ';';
/* e.g.
SACRIFICE: a, SET1: {b,c};
*/
} else {
std::cout << tp_paths[s.sacrifice] << std::endl;
std::cout << "biz" << std::endl;
if (!just_sacrifice) {
while (!arg_list.empty()) {
std::cout << '\t' << tp_paths[arg_list.front()] << std::endl;
if (is_set1)
std::cout << "\tset_1" << std::endl;
else
std::cout << "\tflb" << std::endl;
arg_list.pop();
}
std::cout << '\t' << tp_paths[s.sacrifice] << std::endl;
}
std::cout << "\tflb" << std::endl;
std::cout << "rnz" << std::endl;
/* e.g.
.tp a
biz
.tp b
set_1
.tp c
set_1
.tp a
flb
rnz
*/
switch (k) {
case 0:
return solve_with<0>(raw, full, opt, r, finish);
case 1:
return solve_with<1>(raw, full, opt, r, finish);
case 2:
return solve_with<2>(raw, full, opt, r, finish);
case 3:
return solve_with<3>(raw, full, opt, r, finish);
case 4:
return solve_with<4>(raw, full, opt, r, finish);
case 5:
return solve_with<5>(raw, full, opt, r, finish);
default:
return solve_with<6>(raw, full, opt, r, finish);
}
}
r8veritas::truthtable
compress_stat_space(const r8veritas::truthtable &raw_truthtable) {
// raw means input must be 0 ~ (1<<CELL_SIZE),
// which makes reaching the output of after-xor input easier.
std::array<r8veritas::influence, CELL_SIZE> influences;
r8veritas::truthtable new_truthtable = raw_truthtable;
for (r8veritas::index i = 0; i < CELL_SIZE; i++) {
influences[i] = 0;
for (r8veritas::index j = 0; j < (1 << CELL_SIZE); j++) {
if ((*(raw_truthtable.second))[j] !=
(*(raw_truthtable.second))[j ^ (1 << i)]) {
// when [j] can influence the ans
influences[i]++;
private:
std::set<stat> pool;
stat_ref keep(const stat &s) { return &*pool.insert(s).first; }
// ---------------------------------------------------------------- engine
// K relevant inputs: every plane is a 2^K bit truth table, the whole state
// is CELL_SIZE * 2^K bits packed into KEYW words.
template <int K> struct engine {
static constexpr int M = 1 << K; // bits per plane
static constexpr int KEYW = (CELL_SIZE * M + 63) / 64;
static constexpr uint64_t PMASK =
(M >= 64) ? ~uint64_t(0) : ((uint64_t(1) << (M & 63)) - 1);
using key = std::array<uint64_t, KEYW>;
static uint64_t get(const key &k, int b) {
const int off = b * M;
return (k[off >> 6] >> (off & 63)) & PMASK;
}
static void put(key &k, int b, uint64_t v) {
const int off = b * M;
k[off >> 6] =
(k[off >> 6] & ~(PMASK << (off & 63))) | ((v & PMASK) << (off & 63));
}
static key zero() {
key k{};
return k;
}
static uint64_t cond(const key &k, const instruction &i) {
return get(k, i.sacrifice);
}
static key step(const key &k, const instruction &i) {
key n = k;
const uint64_t c = get(k, i.sacrifice);
put(n, i.sacrifice, 0);
for (int b = 0; b < CELL_SIZE; b++)
if (i.mask & (1 << b))
put(n, b, i.or_mode ? (get(k, b) | c) : (get(k, b) ^ c));
return n;
}
static uint64_t hash(const key &k) {
uint64_t h = 0xcbf29ce484222325ULL;
for (int i = 0; i < KEYW; i++) {
h ^= k[i];
h *= 0x100000001b3ULL;
h ^= h >> 29;
h *= 0xbf58476d1ce4e5b9ULL;
h ^= h >> 32;
}
return h;
}
struct slot {
key k{};
key parent{};
uint16_t ins = 0xFFFF; // 0xFFFF free, 0xFFFE start of a program
};
struct table {
std::vector<slot> v;
uint64_t mask = 0;
size_t used = 0;
static constexpr uint16_t FREE = 0xFFFF, ROOT = 0xFFFE;
static uint64_t capacity_for(size_t n) {
uint64_t c = 1 << 12;
while (c * 3 < n * 4 + 4)
c <<= 1;
return c;
}
void init(uint64_t cap) {
v.assign(cap, slot{});
mask = cap - 1;
used = 0;
}
void grow() {
std::vector<slot> old = std::move(v);
init(old.size() * 2);
for (const auto &s : old)
if (s.ins != FREE)
insert(s.k, s.parent, s.ins);
}
bool insert(const key &k, const key &parent, uint16_t ins) {
uint64_t j = hash(k) & mask;
while (v[j].ins != FREE) {
if (v[j].k == k)
return false;
j = (j + 1) & mask;
}
v[j].k = k;
v[j].parent = parent;
v[j].ins = ins;
if (++used * 4 > (mask + 1) * 3)
grow();
return true;
}
const slot *find(const key &k) const {
uint64_t j = hash(k) & mask;
while (v[j].ins != FREE) {
if (v[j].k == k)
return &v[j];
j = (j + 1) & mask;
}
return nullptr;
}
};
};
template <int K>
result solve_with(const truthtable &raw, const std::vector<size_t> &full,
const options &opt, result &r,
const std::function<result()> &finish) {
using E = engine<K>;
using table_t = typename E::table;
using key = typename E::key;
constexpr uint16_t ROOT = table_t::ROOT;
const std::vector<instruction> insns = build_instructions();
// start = identity over the compressed inputs, goal = the target
key start = E::zero(), goal = E::zero();
for (size_t j = 0; j < full.size(); j++)
for (int b = 0; b < CELL_SIZE; b++) {
if (j & (size_t(1) << b))
E::put(start, b, E::get(start, b) | (uint64_t(1) << j));
if ((*raw.second)[full[j]] & (1u << b))
E::put(goal, b, E::get(goal, b) | (uint64_t(1) << j));
}
table_t tab;
tab.init(table_t::capacity_for(1 << 16));
tab.insert(start, E::zero(), ROOT);
std::vector<key> frontier{start};
auto path_to = [&](const key &k, int extra) {
std::vector<instruction> p;
if (extra >= 0)
p.push_back(insns[size_t(extra)]);
key cur = k;
while (true) {
const auto *s = tab.find(cur);
if (s == nullptr || s->ins == ROOT)
break;
p.push_back(insns[s->ins]);
cur = s->parent;
}
std::reverse(p.begin(), p.end());
return p;
};
if (start == goal) {
r.found = r.proven_optimal = true;
return finish();
}
for (int d = 1; d <= opt.max_depth; d++) {
// ---- close the last block: enumerate the goal's preimages ----
// Only worth it while 2^K is small enough to walk every condition.
if (K <= 3) {
for (uint16_t ii = 0; ii < insns.size(); ii++) {
const instruction &i = insns[ii];
if (E::get(goal, i.sacrifice) != 0)
continue; // the block clears its own plane
for (uint64_t c = 1; c <= E::PMASK; c++) {
bool hit = false;
for_each_preimage<E>(
goal, i, c, [&](const key &p) {
if (tab.find(p) != nullptr) {
r.program = path_to(p, int(ii));
r.found = true;
r.proven_optimal = true;
hit = true;
return true;
}
return false;
});
if (hit)
return finish();
}
}
// the backward step has covered this length already
if (d == opt.max_depth)
break;
}
// ---- expand the BFS by one layer ----
std::vector<key> next;
next.reserve(frontier.size());
for (const auto &k : frontier) {
for (uint16_t ii = 0; ii < insns.size(); ii++) {
if (E::cond(k, insns[ii]) == 0)
continue; // nothing to sacrifice, the block would do nothing
key n = E::step(k, insns[ii]);
if (n == goal) {
r.program = path_to(k, int(ii));
r.found = true;
r.proven_optimal = true;
r.states = tab.used;
r.depth_reached = d;
return finish();
}
if (tab.insert(n, k, ii))
next.push_back(n);
}
if (tab.used > opt.max_states) {
r.message = "state budget exhausted: the search is not complete";
r.states = tab.used;
r.depth_reached = d;
return finish();
}
}
influences[i] >>= 1;
r.states = tab.used;
r.depth_reached = d;
if (opt.verbose)
std::cout << " depth " << d << ": " << next.size() << " new, "
<< tab.used << " kept\n";
frontier.swap(next);
}
for (r8veritas::index i = 0; i < CELL_SIZE; i++) {
if (influences[i] == 0) {
new_truthtable.first = operate_ins(new_truthtable.first, {0, i}).first;
}
}
return (new_truthtable);
r.proven_optimal = (r.message.empty());
if (r.message.empty())
r.message = "no program of length <= " + std::to_string(opt.max_depth);
return finish();
}
bool bfs(const r8veritas::truthtable &truthtable,
bool enable_debug_output = false, r8veritas::index layer = 1) {
if (layer == 1) {
stats.push(truthtable.first);
}
if (stats.empty()) {
return (false);
}
r8veritas::index i = stats.size();
if (enable_debug_output)
std::cout << "LAYER=" << layer << ",stats_size=" << i << std::endl;
r8veritas::stat_ref tmp_stat_ref;
std::pair<stat_ref, bool> ans;
for (; i > 0; i--) {
tmp_stat_ref = stats.front();
for (auto j : r8veritas::all_ins) {
ans = operate_ins(tmp_stat_ref, j);
if (ans.first == truthtable.second) {
while (!stats.empty())
stats.pop();
return (true);
}
if (!ans.second) {
stats.push(ans.first);
}
}
stats.pop();
}
return (bfs(truthtable, enable_debug_output, layer + 1));
// Calls f on every preimage of `post` under `ins` with condition `c`.
// XOR destinations are forced, OR destinations are free on the bits of c
// they contain, so walk the destinations and branch where needed.
template <class E, class F>
static bool for_each_preimage(const typename E::key &post,
const instruction &ins, uint64_t c, F &&f) {
using key = typename E::key;
key pre = post;
E::put(pre, ins.sacrifice, c);
return preimage_walk<E>(post, ins, c, pre, 0, f);
}
r8veritas::path track_path(const r8veritas::truthtable &truthtable) {
r8veritas::path p;
for (auto tmp_stat = truthtable.second; tmp_stat != truthtable.first;) {
p.push(visited_op[tmp_stat]);
tmp_stat = p.top().first;
template <class E, class F>
static bool preimage_walk(const typename E::key &post,
const instruction &ins, uint64_t c,
typename E::key pre, int b, F &f) {
using key = typename E::key;
for (; b < CELL_SIZE; b++)
if (ins.mask & (1 << b))
break;
if (b == CELL_SIZE)
return f(pre);
const uint64_t T = E::get(post, b);
if (!ins.or_mode) {
E::put(pre, b, T ^ c);
return preimage_walk<E>(post, ins, c, pre, b + 1, f);
}
return p;
if ((T & c) != c)
return false; // a destination bit can only be set, not cleared
const uint64_t fixed = T & ~c, free = T & c;
for (uint64_t sub = free;; sub = (sub - 1) & free) {
E::put(pre, b, fixed | sub);
if (preimage_walk<E>(post, ins, c, pre, b + 1, f))
return true;
if (sub == 0)
break;
}
return false;
}
// ---------------------------------------------------------------- syntax
std::vector<instruction> build_instructions() const {
std::vector<instruction> out;
out.reserve(CELL_SIZE * (2 * (1 << (CELL_SIZE - 1)) + 1));
for (int s = 0; s < CELL_SIZE; s++) {
out.push_back({uint8_t(s), 0, false}); // pure sacrifice: clear plane s
for (int sub = 1; sub < (1 << (CELL_SIZE - 1)); sub++) {
uint8_t m = 0;
int bit = 0;
for (int b = 0; b < CELL_SIZE; b++)
if (b != s)
m |= uint8_t(((sub >> bit++) & 1) << b);
out.push_back({uint8_t(s), m, false});
out.push_back({uint8_t(s), m, true});
}
}
return out;
}
};
#undef CELL_SIZE_BITWIDTH
#undef INS_SIZE
#undef INS_BYTECODE_SIZE
#endif
#endif
+77 -42
View File
@@ -1,56 +1,51 @@
#include "r8veritas.hh"
#include <cstdlib>
#include <iostream>
#include <ostream>
#include <string>
#include <vector>
using problem_t = r8veritas<6>;
problem_t::cell func_copy(problem_t::cell inp) {
bool A = inp & 0b1;
return (A << 1) | A;
static problem_t::cell func_copy(problem_t::cell inp) {
const unsigned A = inp & 0b1;
return problem_t::cell((A << 1) | A);
}
problem_t::cell func_clb_and(problem_t::cell inp) {
static problem_t::cell func_clb_and(problem_t::cell inp) {
bool A = inp & 0b1;
bool B = inp & 0b10;
bool S = A & B;
return S << 2;
return (A & B) << 2;
}
problem_t::cell func_full_add_Co(problem_t::cell inp) {
static problem_t::cell func_clb_half_add(problem_t::cell inp) {
bool A = inp & 0b1;
bool B = inp & 0b10;
return ((A ^ B) << 1) | (A & B);
}
static problem_t::cell func_half_add(problem_t::cell inp) {
bool A = inp & 0b1;
bool B = inp & 0b10;
return ((A ^ B) << 3) | ((A & B) << 2) | (inp & 0b11);
}
static problem_t::cell func_full_add_Co(problem_t::cell inp) {
bool A = inp & 0b1;
bool B = inp & 0b10;
bool C = inp & 0b100;
bool S = A ^ B ^ C;
bool Co = (A & B) | (A & C) | (B & C);
return (Co << 4) | (inp & 0b111);
}
problem_t::cell func_full_add_S(problem_t::cell inp) {
static problem_t::cell func_full_add_S(problem_t::cell inp) {
bool A = inp & 0b1;
bool B = inp & 0b10;
bool C = inp & 0b100;
bool S = A ^ B ^ C;
bool Co = (A & B) | (A & C) | (B & C);
return (S << 3) | (inp & 0b111);
}
problem_t::cell func_clb_half_add(problem_t::cell inp) {
bool A = inp & 0b1;
bool B = inp & 0b10;
bool S = A ^ B;
bool Co = A & B;
return (S << 1) | Co;
}
problem_t::cell func_half_add(problem_t::cell inp) {
bool A = inp & 0b1;
bool B = inp & 0b10;
bool S = A ^ B;
bool Co = A & B;
return (S << 3) | (Co << 2) | (inp & 0b11);
}
problem_t::cell func_full_add(problem_t::cell inp) {
static problem_t::cell func_full_add(problem_t::cell inp) {
bool A = inp & 0b1;
bool B = inp & 0b10;
bool C = inp & 0b100;
@@ -59,20 +54,60 @@ problem_t::cell func_full_add(problem_t::cell inp) {
return (Co << 4) | (S << 3) | (inp & 0b111);
}
int main() {
problem_t problem;
problem.initialize_nicknames();
problem.initialize_tp_paths();
auto tab1 = problem.generate_truthtable(func_full_add);
auto new_tab1 = problem.compress_stat_space(tab1);
if (problem.bfs(new_tab1, true)) {
auto p = problem.track_path(tab1);
while (!p.empty()) {
problem.output_ins(problem.to_ins(p.top().second), true);
std::cout << std::endl;
p.pop();
struct problem {
const char *name;
problem_t::op fn;
};
int main(int argc, char **argv) {
const int max_depth = argc > 1 ? std::atoi(argv[1]) : 5;
const bool verbose = argc > 2 ? std::atoi(argv[2]) != 0 : false;
std::vector<problem> problems = {
{"copy", func_copy},
{"clb_and", func_clb_and},
{"clb_half_add", func_clb_half_add},
{"half_add", func_half_add},
{"full_add_S", func_full_add_S},
{"full_add_Co", func_full_add_Co},
{"full_add", func_full_add},
};
for (const auto &p : problems) {
problem_t problem_obj;
problem_obj.initialize_nicknames();
problem_obj.initialize_tp_paths();
auto raw = problem_obj.generate_truthtable(p.fn);
auto compressed = problem_obj.compress_stat_space(raw);
problem_t::options opt;
opt.max_depth = max_depth;
opt.verbose = verbose;
auto res = problem_obj.solve(compressed, opt);
std::cout << "==== " << p.name << "\n";
if (!res.found) {
std::cout << " no program of length <= " << max_depth << " ("
<< res.states << " states, " << res.seconds << "s) "
<< res.message << "\n\n";
continue;
}
} else
std::cout << "PATH NOT FOUND!";
const bool ok = problem_obj.run_program(compressed, res.program);
std::cout << " length " << res.program.size()
<< (res.proven_optimal ? " (proven shortest)" : " (unproven)")
<< " " << res.states << " states, " << res.seconds << "s"
<< " replay: " << (ok ? "ok" : "MISMATCH") << "\n ";
problem_obj.print_program(res.program, std::cout, true);
std::cout << "\n";
if (std::string(p.name) == "full_add") {
std::cout << " r8asm:\n";
for (const auto &i : res.program) {
problem_obj.output_ins(i, std::cout, false);
std::cout << "\n";
}
}
}
return (0);
}