# Ternary root graphs for the decic rank calculations The C++17 program below builds the raising and lowering graphs used by `projected-rank.py`. It enumerates degree-ten coefficient monomials by weight, groups the moves for each root, and writes the graph indices and coefficients to the chosen scratch directory. The two graph modes correspond to the `projector` and `binary` entries in `projected-types.tsv`. From `anc/`, extract the listing and compile it in a scratch directory: ~~~sh awk '/^~~~cpp$/{src=1;next} src && /^~~~$/{exit} src' a10/projected-row.md > "$work/projected-row.cpp" c++ -std=c++17 -O3 "$work/projected-row.cpp" -o "$work/projected-row" ~~~ For a three-root calculation use `--prepare`. For a binary-basis calculation use `--prepare-flag`. For example, after creating the output directory, `"$work/projected-row" 50 44 6 --prepare "$work/graphs"` prepares the $(50,44,6)$ test. The [supplement instructions](../README.md) give the subsequent rank command. ~~~cpp // Prepare the decic root ladders or evaluate an eight-row minor independently on the CPU. #include #include #include #include #include #include #include #include #include #include #include #include namespace { constexpr int d = 10, n = 10, p = 239, batch = 8; using u64 = uint64_t; using Row = std::array; using Exp = std::array; using Degrees = std::array; using Clock = std::chrono::steady_clock; int term_id[11][11]; int inverse[p]; u64 choose[76][11]; void init() { for (int i = 1; i < p; ++i) { for (int j = 1; j < p; ++j) if (i * j % p == 1) { inverse[i] = j; break; } } for (int i = 0; i < 76; ++i) { choose[i][0] = 1; for (int j = 1; j <= std::min(i, 10); ++j) choose[i][j] = choose[i - 1][j - 1] + choose[i - 1][j]; } int id = 0; for (int y = 0; y <= d; ++y) for (int t = 0; t <= d - y; ++t) term_id[y][t] = id++; } std::array split_points() { std::mt19937 rng(50158); std::array values{}; for (int row = 0; row < batch; ++row) { int f[11][11]{}; f[0][0] = 1; for (int a = 0; a < n; ++a) { const int ycoef = rng() % p, tcoef = rng() % p; for (int y = a + 1; y >= 0; --y) for (int t = a + 1 - y; t >= 0; --t) f[y][t] = (f[y][t] + (y ? ycoef * f[y - 1][t] : 0) + (t ? tcoef * f[y][t - 1] : 0)) % p; } for (int y = 0; y <= d; ++y) for (int t = 0; t <= d - y; ++t) { int scale = choose[d][y] * choose[d - y][t] % p; values[term_id[y][t]][row] = f[y][t] * inverse[scale] % p; } } return values; } std::size_t weight_count(Exp w) { std::vector>> a( n + 1, std::vector>(w[1] + 1, std::vector(w[2] + 1))); a[0][0][0] = 1; for (int y = 0; y <= d; ++y) for (int t = 0; t <= d - y; ++t) for (int k = 1; k <= n; ++k) for (int i = y; i <= w[1]; ++i) for (int j = t; j <= w[2]; ++j) a[k][i][j] += a[k - 1][i - y][j - t]; return a[n][w[1]][w[2]]; } // Sorted multiset rank is unique among all ten-element multisets on the 66 coefficients. u64 multiset_key(std::array ids) { std::sort(ids.begin(), ids.end()); u64 v = 1; for (int i = 0; i < n; ++i) v += choose[ids[i] + i][i + 1]; return v; } u64 mix(u64 v) { v = (v ^ (v >> 30)) * 0xbf58476d1ce4e5b9ULL; v = (v ^ (v >> 27)) * 0x94d049bb133111ebULL; return v ^ (v >> 31); } class Coordinates { std::vector keys; std::vector indices; std::size_t mask; public: std::vector rows; explicit Coordinates(std::size_t count) { std::size_t cap = 1; while (cap < 3 * count / 2 + 1) cap *= 2; mask = cap - 1; keys.resize(cap); indices.resize(cap); rows.reserve(count); } std::size_t locate(u64 key) const { auto pos = mix(key) & mask; while (keys[pos] && keys[pos] != key) pos = (pos + 1) & mask; return pos; } uint32_t add(u64 key, const Row &value) { auto pos = locate(key); if (keys[pos]) throw std::runtime_error("duplicate monomial"); uint32_t j = rows.size(); keys[pos] = key; indices[pos] = j; rows.push_back(value); return j; } uint32_t at(u64 key) const { auto pos = locate(key); if (keys[pos] != key) throw std::runtime_error("missing monomial"); return indices[pos]; } }; struct Edge { uint32_t lower; uint8_t up, down; }; struct Level { std::vector codes; std::vector offsets; std::vector edges; std::vector values; }; struct Graph { std::vector offsets{0}, edges; void append(const std::vector &off, const std::vector &pairs) { auto start = edges.size(); for (std::size_t j = 1; j < off.size(); ++j) offsets.push_back(start + off[j]); edges.insert(edges.end(), pairs.begin(), pairs.end()); } void write(std::ofstream &os) const { uint32_t sizes[2]{uint32_t(offsets.size() - 1), uint32_t(edges.size())}; os.write(reinterpret_cast(sizes), sizeof(sizes)); os.write(reinterpret_cast(offsets.data()), offsets.size() * sizeof(uint32_t)); os.write(reinterpret_cast(edges.data()), edges.size() * sizeof(uint32_t)); } }; struct Bin { std::vector up, down; std::vector global; std::size_t vertices = 0; explicit Bin(int h) : up(h + 1), down(h + 1) {} void write(const std::string &file) { std::ofstream os(file, std::ios::binary); uint32_t count = global.size(); os.write(reinterpret_cast(&count), sizeof(count)); os.write(reinterpret_cast(global.data()), global.size() * sizeof(uint32_t)); for (std::size_t r = 1; r < up.size(); ++r) { up[r].write(os); down[r].write(os); } if (!os) throw std::runtime_error("could not write ladder graph"); } }; class RootBlock { Degrees spec, deg, suffix{}; int i, j, other, h; std::vector levels; void enumerate(int slot, int left, int low, u64 code, std::vector &out) { if (slot == n) { if (!left) out.push_back(code); return; } for (int b = std::max(low, left - suffix[slot] + deg[slot]); b <= std::min(left, deg[slot]); ++b) enumerate(slot + 1, left - b, slot + 1 < n && spec[slot + 1] == spec[slot] ? b : 0, code | (u64(b) << (4 * slot)), out); } void edges(int r) { auto &high = levels[r]; auto &low = levels[r - 1]; std::unordered_map pos; pos.reserve(low.codes.size()); for (uint32_t t = 0; t < low.codes.size(); ++t) pos[low.codes[t]] = t; high.offsets.reserve(high.codes.size() + 1); for (auto code : high.codes) { high.offsets.push_back(high.edges.size()); int start = 0, previous = 0; while (start < n) { int b = (code >> (4 * start)) & 15, end = start + 1; while (end < n && spec[end] == spec[start] && int((code >> (4 * end)) & 15) == b) ++end; if (b) { int dup = (start && spec[start] == spec[start - 1] && int((code >> (4 * (start - 1))) & 15) == b - 1) ? previous : 0; auto to = pos.at(code - (u64(1) << (4 * start))); high.edges.push_back( {to, uint8_t((end - start) * b), uint8_t((dup + 1) * (deg[start] - b + 1))}); } previous = end - start; start = end; } } high.offsets.push_back(high.edges.size()); } public: RootBlock(Degrees s, int recipient, int donor, int marked, bool top_only = false) : spec(s), i(recipient), j(donor), other(3 - i - j), h(marked), levels(h + 1) { for (int b = n - 1; b >= 0; --b) { deg[b] = d - spec[b]; suffix[b] = deg[b] + (b + 1 < n ? suffix[b + 1] : 0); } if (top_only) { enumerate(0, h, 0, 0, levels[h].codes); return; } for (int r = 0; r <= h; ++r) { enumerate(0, r, 0, 0, levels[r].codes); levels[r].values.resize(levels[r].codes.size()); if (r) edges(r); } } std::size_t vertices() const { std::size_t total = 0; for (const auto& level : levels) total += level.codes.size(); return total; } std::array terms(u64 code) const { std::array ids; for (int a = 0; a < n; ++a) { Exp e; e[other] = spec[a]; e[j] = (code >> (4 * a)) & 15; e[i] = deg[a] - e[j]; ids[a] = term_id[e[1]][e[2]]; } return ids; } std::size_t write_monomials(std::ofstream &out) const { for (u64 code : levels[h].codes) { auto ids=terms(code); std::array digits; std::copy(ids.begin(),ids.end(),digits.begin()); out.write(reinterpret_cast(digits.data()),n); } return levels[h].codes.size(); } void prepare(Coordinates &space, Bin &bin, std::ofstream *monomials, bool top_only = false) const { for (u64 code : levels[h].codes) { auto ids = terms(code); auto key = multiset_key(ids); if (monomials) { std::array digits; std::copy(ids.begin(), ids.end(), digits.begin()); monomials->write(reinterpret_cast(digits.data()), n); auto index = space.add(key, {}); if (!top_only) bin.global.push_back(index); } else bin.global.push_back(space.at(key)); } if (top_only) return; for (int r = 1; r <= h; ++r) { const auto &high = levels[r]; const auto &low = levels[r - 1]; uint32_t highbase = bin.up[r].offsets.size() - 1; uint32_t lowbase = bin.down[r].offsets.size() - 1; std::vector reverse(low.codes.size() + 1), upedges(high.edges.size()); for (auto edge : high.edges) ++reverse[edge.lower + 1]; for (std::size_t a = 1; a < reverse.size(); ++a) reverse[a] += reverse[a - 1]; auto cursor = reverse; std::vector downedges(high.edges.size()); // Eight bits hold the coefficient, the remaining bits the index within this bin. if (highbase + high.codes.size() > (1u << 24) || lowbase + low.codes.size() > (1u << 24)) throw std::runtime_error("ladder bin exceeds packed index"); for (uint32_t a = 0; a < high.codes.size(); ++a) for (auto z = high.offsets[a]; z < high.offsets[a + 1]; ++z) { auto edge = high.edges[z]; upedges[z] = ((lowbase + edge.lower) << 8) | edge.up; downedges[cursor[edge.lower]++] = ((highbase + a) << 8) | edge.down; } bin.up[r].append(high.offsets, upedges); bin.down[r].append(reverse, downedges); } } void apply(Exp w, Coordinates &space, const std::array &coeff, bool first, std::vector *probes) { auto &top = levels[h]; std::vector global; global.reserve(top.codes.size()); for (auto code : top.codes) { auto ids = terms(code); auto key = multiset_key(ids); uint32_t index; if (first) { Row v; v.fill(1); for (auto id : ids) for (int b = 0; b < batch; ++b) v[b] = int(v[b]) * coeff[id][b] % p; index = space.add(key, v); } else index = space.at(key); top.values[global.size()] = space.rows[index]; global.push_back(index); } // On evaluation rows use the transposed ladders, first F^T and then E^T. for (int r = h; r > 0; --r) { auto &high = levels[r]; auto &low = levels[r - 1]; std::vector> sums(low.codes.size()); for (std::size_t a = 0; a < high.codes.size(); ++a) for (auto e = high.offsets[a]; e < high.offsets[a + 1]; ++e) { auto edge = high.edges[e]; for (int b = 0; b < batch; ++b) sums[edge.lower][b] += edge.down * high.values[a][b]; } for (std::size_t a = 0; a < sums.size(); ++a) for (int b = 0; b < batch; ++b) low.values[a][b] = sums[a][b] % p; } for (int r = 1; r <= h; ++r) { auto &high = levels[r]; auto &low = levels[r - 1]; int step = h - r + 1; int scale = p - inverse[step * (w[i] - w[j] + j - i + step) % p]; for (std::size_t a = 0; a < high.codes.size(); ++a) { std::array sums{}; for (auto e = high.offsets[a]; e < high.offsets[a + 1]; ++e) { auto edge = high.edges[e]; for (int b = 0; b < batch; ++b) sums[b] += edge.up * low.values[edge.lower][b]; } for (int b = 0; b < batch; ++b) high.values[a][b] = (high.values[a][b] + scale * sums[b]) % p; } } if (probes) probes->insert(probes->end(), top.values.begin(), top.values.end()); else for (std::size_t a = 0; a < global.size(); ++a) space.rows[global[a]] = top.values[a]; } }; template void signatures(Degrees &s, int slot, int left, int low, Fn &run) { if (slot == n) { if (!left) run(s); return; } for (int v = std::max(low, left - (n - 1 - slot) * d); v <= std::min(d, left / (n - slot)); ++v) { s[slot] = v; signatures(s, slot + 1, left - v, v, run); } } int witness(const std::vector &probes) { std::array pivots{}; int rank = 0, det = 1, inversions = 0; std::vector chosen, order; for (std::size_t col = 0; col < probes.size() && rank < batch; ++col) { Row v = probes[col]; for (int j = 0; j < batch; ++j) if (v[j]) { if (pivots[j][j]) { int scale = p - v[j]; for (int t = j; t < batch; ++t) v[t] = (v[t] + scale * pivots[j][t]) % p; } else { int lead = v[j]; det = det * lead % p; for (int t = j; t < batch; ++t) pivots[j][t] = int(v[t]) * inverse[lead] % p; for (int prev : order) inversions += (prev > j); chosen.push_back(col); order.push_back(j); ++rank; break; } } } if (inversions % 2) det = (p - det) % p; std::cout << "rank=" << rank << " columns="; for (auto col : chosen) std::cout << col << ' '; if (rank == batch) std::cout << "det=" << det; std::cout << '\n'; return rank; } } // namespace int main(int argc, char **argv) { bool index_only = argc == 6 && std::string(argv[4]) == "--monomials"; bool audit_binary = argc == 6 && std::string(argv[4]) == "--audit-binary"; bool flag = argc == 6 && std::string(argv[4]) == "--prepare-flag"; bool binary = flag || (argc == 6 && std::string(argv[4]) == "--prepare-binary"); std::size_t flag_offset = 0, double_offset = 0; unsigned skip23 = 0, keep13 = 0; bool double_started = false; bool prep = binary || (argc == 6 && std::string(argv[4]) == "--prepare"); bool audit = audit_binary || (argc == 6 && std::string(argv[4]) == "--audit"); bool all = index_only || prep || audit || (argc == 5 && std::string(argv[4]) == "--all-profiles"); if (argc != 4 && !all) { std::cerr << "expected first second third [--all-profiles | --prepare directory | --prepare-binary directory | --prepare-flag directory | --audit query | --audit-binary query | --monomials file]\n"; return 2; } Exp w{std::stoi(argv[1]), std::stoi(argv[2]), std::stoi(argv[3])}; if (w[0] + w[1] + w[2] != 100 || w[0] < w[1] || w[1] < w[2] || w[2] < 0 || w[2] > 10) return 2; init(); auto coeff = split_points(); std::ifstream query; if (audit) { query.open(argv[5], std::ios::binary); for (auto &term : coeff) query.read(reinterpret_cast(term.data()), batch); if (!query) throw std::runtime_error("could not read normalized split evaluations"); } auto count = weight_count(w); if (index_only) { std::ofstream out(argv[5],std::ios::binary); if (!out) throw std::runtime_error("could not open monomial file"); Degrees spec{}; std::size_t written=0; auto emit = [&](Degrees group) { written += RootBlock(group,1,2,w[2],true).write_monomials(out); }; signatures(spec,0,w[0],0,emit); out.close(); if (!out || written!=count) throw std::runtime_error("incomplete monomial file"); return 0; } Coordinates space(count); std::vector probes; std::ofstream monomials; std::vector part_counts; if (prep) { monomials.open(std::string(argv[5]) + "/monomials.bin", std::ios::binary); if (!monomials) throw std::runtime_error("open output in an existing directory"); } for (auto root : {std::pair{1, 2}, {0, 2}, {0, 1}}) { auto [i, j] = root; if ((binary || audit_binary) && j == 1) { if (prep) part_counts.push_back(0); continue; } int other = 3 - i - j; auto start = Clock::now(); Bin bin(w[j]); unsigned part = 0; auto flush = [&] { auto prefix = std::string(argv[5]) + "/root" + std::to_string(i + 1) + std::to_string(j + 1); bin.write(prefix + "-" + std::to_string(part++) + ".bin"); bin = Bin(w[j]); }; auto run = [&](Degrees spec) { // For this minor only the single-marked third profile is read in the last root. if (j == 1 && !all && spec[n - 1] != w[2]) return; // The first split factor is x. Root 23 preserves every slot's x degree. // Root 13 preserves y. Its inputs still have an x in every slot, so y^10 is absent. if (flag && i == 0 && j == 2 && spec.back() == d) return; bool zero_profile = flag && i == 1 && spec[0] == 0; if (flag && i == 1 && spec[0] >= 2 && !double_started) { if (!bin.global.empty()) flush(); double_offset = space.rows.size(); skip23 = part; double_started = true; } RootBlock block(spec, i, j, w[j], zero_profile); if (zero_profile) { block.prepare(space, bin, &monomials, true); flag_offset = space.rows.size(); return; } if (prep) { const auto nodes = block.vertices(); // Count all live weight levels, since each stores one sample batch. if (!bin.global.empty() && bin.vertices + nodes > (1u << 22)) flush(); block.prepare(space, bin, i == 1 ? &monomials : nullptr); bin.vertices += nodes; return; } block.apply(w, space, coeff, i == 1, j == 1 && !audit ? &probes : nullptr); }; Degrees s{}; if (flag && i == 0 && j == 2) { // Keep the repeated-factor bins together; generic samples use both ranges. auto double_profiles = [&](Degrees spec) { if (spec.back() <= d - 2) run(spec); }; signatures(s, 0, w[other], 0, double_profiles); if (!bin.global.empty()) flush(); keep13 = part; auto single_profiles = [&](Degrees spec) { if (spec.back() == d - 1) run(spec); }; signatures(s, 0, w[other], 0, single_profiles); } else { signatures(s, 0, w[other], 0, run); } if (prep && !bin.global.empty()) flush(); if (flag && i == 1 && !double_started) { double_offset = space.rows.size(); skip23 = part; } if (prep) part_counts.push_back(part); if (space.rows.size() != count) throw std::runtime_error("wrong weight dimension"); std::cout << "root=" << i + 1 << j + 1 << " raw=" << count << " seconds=" << std::chrono::duration(Clock::now() - start).count() << std::endl; } if (prep) { std::remove((std::string(argv[5]) + "/binary-readout.npz").c_str()); monomials.close(); if (!monomials) throw std::runtime_error("could not write input monomials"); std::ofstream manifest(std::string(argv[5]) + "/shape.txt"); manifest << w[0] << ' ' << w[1] << ' ' << w[2] << '\n'; for (auto parts : part_counts) manifest << parts << ' '; if (flag) manifest << flag_offset << ' ' << double_offset << ' ' << skip23 << ' ' << keep13; manifest << '\n'; if (!manifest) throw std::runtime_error("could not write shape and bin counts"); return 0; } if (audit) { for (int col = 0; col < batch; ++col) { uint32_t size = 0; if (!query.read(reinterpret_cast(&size), sizeof(size))) throw std::runtime_error("could not read column bucket"); Row value{}; for (uint32_t t = 0; t < size; ++t) { uint32_t index, multiplier; query.read(reinterpret_cast(&index), sizeof(index)); query.read(reinterpret_cast(&multiplier), sizeof(multiplier)); if (!query || index >= space.rows.size()) throw std::runtime_error("invalid audit coordinate"); for (int b = 0; b < batch; ++b) value[b] = (value[b] + multiplier * space.rows[index][b]) % p; } probes.push_back(value); } } std::cout << "probes=" << probes.size() << ' '; int rank = witness(probes); return audit && rank != batch ? 1 : 0; } ~~~