Count a new hypergraph pattern (an Op)#
In this tutorial you count something on a hypergraph that dynG does not count yet, and keep the
count exact while hyperedges are deleted and inserted. You write it as an Op: a small struct
whose callbacks say what to count for a triangle of hyperedges, a pair of hyperedges or a single
hyperedge. dyng::experimental::count_local_patterns<op_t> runs your Op with the engine
triad_count uses (ESCHER’s wedge engine), on the GPU and on the CPU, and gives you the full count
and the exact update under batches for free.
Warning
count_local_patterns is experimental (Plan: the short roadmap, Section 5.9): its API may
change in any minor release, and the changes are listed in the changelog. It is C++ only and
needs nvcc: its header <dyng/experimental/local_patterns.cuh> holds the kernels that are
compiled for your Op. There is no Python counterpart (Python gaps).
You should be comfortable with C++17 and know what a hypergraph is (Hypergraphs and hyperedge ids).
The code of this tutorial is in examples/tutorial_algorithms/local_patterns/: the Ops
(patterns.hpp), a brute-force oracle (oracle.hpp) and the programs that run them
(tutorial_test.cu on every backend, tutorial_host_test.cpp without nvcc). The snippets below
are quoted from those files. The local GPU gate (ci/gpu_local.sh, run on a machine with nvcc and
a GPU) builds and runs tutorial_test.cu on every backend and both hypergraph types; hosted CI has
no nvcc, so it runs the host half (tutorial_host_test.cpp, which drives the Ops’ callbacks by
hand against the brute force) and the drift check, which fails when a quoted line changes without
this page (ci/tutorial_quotes.py).
1. The idea: a pattern is an Op over wedges, pairs or keys#
triad_count counts the triads of a hypergraph: three hyperedges that pairwise share a
vertex, which are the triangles of its line graph (the graph whose vertices are the hyperedges,
with an edge between two hyperedges that share a vertex). Its engine enumerates them by
wedges: a wedge (a, b) is a hyperedge a and one of its neighbours b in the line graph,
and every common neighbour c of a and b closes a triangle {a, b, c}. The same
enumeration gives every adjacent pair {a, b}, and the hyperedges themselves.
An Op picks one of these shapes and says what to count:
|
the engine calls |
once per |
|---|---|---|
|
|
triangle |
|
|
pair of hyperedges that share a vertex |
|
|
live hyperedge |
and every worker (a GPU thread, a host source) ends with flush(bins). a, b and c are
0-based hyperedge ids; rows gives the members of a hyperedge; bins is where the counts go: an
Op has num_bins unsigned 64-bit bins, and bins.add(bin, value) adds to one.
triad_count’s four patterns are four built-in Ops of this engine (the 30 h-motifs and StatHyper’s
three types); a new pattern is a new Op, not a new triad_count::pattern.
2. A one-bin Op: the triangles of the line graph#
The smallest triangles Op counts every triangle once:
/// The triangles of the line graph: the triples of hyperedges that pairwise share a vertex (one
/// bin). triad_count classifies the same triples into its 30 h-motifs, so this count equals
/// triad_count's h_motif total().
struct line_graph_triangles {
static constexpr int num_bins = 1;
static constexpr dx::shape shape = dx::shape::triangles;
std::uint64_t count = 0; // this worker's partial sum, added to the bin by flush()
DYNG_HD void begin_wedge(const dx::hyperedge_rows& /*rows*/, int /*a*/, int /*b*/) {}
template <class bins_t>
DYNG_HD void triangle(const dx::hyperedge_rows& /*rows*/, int /*c*/, bins_t& /*bins*/) {
++count;
}
template <class bins_t>
DYNG_HD void flush(bins_t& bins) {
if (count != 0) bins.add(0, count);
}
};
num_binsandshapearestatic constexpr;count_local_patternschecks every part of the Op with its ownstatic_assertmessage, so a missing or misspelled member is reported by name.The callbacks are
DYNG_HD(__host__ __device__under nvcc): the same Op runs on the GPU and on the host. The ones that receivebinsare templates, because the GPU and the host hand the Op different bins handles.Write every callback
DYNG_HD, never__device__alone. nvcc reports a host-only callback, but not a__device__-only one: the library calls the host callbacks from a template, where nvcc compiles such a call to a stub, so the program compiles, counts on the GPU, and onsequentialandopenmpends with exit status 1 and no message. PutDYNG_EXPERIMENTAL_CHECK_HOST_CALLBACKS(your_op);after each Op, at namespace scope of the.cufile: it makes nvcc report a__device__-only callback (“calling a__device__function … from a__host__function is not allowed”) and adds no code that runs. The tutorial’s test does it for its four Ops:
// nvcc reports a __device__-only callback here (it would end a host backend's run with exit(1)).
DYNG_EXPERIMENTAL_CHECK_HOST_CALLBACKS(tutorial::line_graph_triangles);
DYNG_EXPERIMENTAL_CHECK_HOST_CALLBACKS(tutorial::strong_pairs);
DYNG_EXPERIMENTAL_CHECK_HOST_CALLBACKS(tutorial::core_triads);
DYNG_EXPERIMENTAL_CHECK_HOST_CALLBACKS(tutorial::hub_pairs);
countis a partial sum in the Op’s own member;flush()adds it to the bin once per worker. The Op must be trivially copyable and default-constructible: the engine copies the Op value you give it (here the default,count = 0) into every worker.
Count it, and a pattern of the next section, on a hypergraph:
const dyng::resources res = resources_of(backend);
graph_t h = random_hypergraph<graph_t>(res, seed, reuse);
using triangles_t = dx::count_local_patterns<tutorial::line_graph_triangles>;
using pairs_t = dx::count_local_patterns<tutorial::strong_pairs>;
triangles_t::result triangles = triangles_t::compute(res, h);
pairs_t::result pairs = pairs_t::compute(res, h, tutorial::strong_pairs{2});
The result holds num_bins counts in host memory (counts(), count(bin), total()), the Op
value it was computed with (op()), and the hypergraph version it matches. The triangles of the
line graph are exactly the triads triad_count classifies into its 30 h-motifs, so the one bin
equals triad_count’s total(), and a brute force over every triple of hyperedges agrees:
const tutorial::member_rows rows = tutorial::live_rows(res, h);
EXPECT_EQ(triangles.count(0), tutorial::brute_triangles(rows));
EXPECT_EQ(triangles.total(), motifs.total()); // the 30 h-motifs of the same triangles
EXPECT_EQ(pairs.count(0), tutorial::brute_strong_pairs(rows, 2));
3. A pattern triad_count does not have#
A pairs Op that counts the pairs of hyperedges sharing at least k vertices: the threshold is a
member of the Op, set by the value you pass to compute() (strong_pairs{2} above) and kept by
the result for every update.
/// The pairs of hyperedges that share at least `k` vertices (one bin). `k` is a parameter of the
/// Op's value: count_local_patterns<strong_pairs>::compute(res, h, strong_pairs{3}).
struct strong_pairs {
static constexpr int num_bins = 1;
static constexpr dx::shape shape = dx::shape::pairs;
int k = 2; // the threshold
std::uint64_t count = 0; // this worker's partial sum
template <class bins_t>
DYNG_HD void pair(const dx::hyperedge_rows& rows, int a, int b, bins_t& /*bins*/) {
if (dx::intersect_size(rows.row(a), rows.row(b)) >= k) ++count;
}
template <class bins_t>
DYNG_HD void flush(bins_t& bins) {
if (count != 0) bins.add(0, count);
}
};
rows.row(id) is a member_span: the members of a hyperedge as opaque, ascending codes. The
set helpers intersect_size(), venn3() and intersects3() merge the codes directly, without
decoding them, so the hot loop reads the store’s own rows. Every Op is checked against a brute
force on the host (oracle.hpp):
/// The triangles of the line graph by brute force: every triple of hyperedges that pairwise
/// share a vertex, by their core size (bins 0, 1, 2 or more); their sum is the triangle count.
inline std::array<std::uint64_t, 3> brute_core_triads(const member_rows& rows) {
std::array<std::uint64_t, 3> bins{};
const std::size_t m = rows.size();
for (std::size_t i = 0; i < m; ++i)
for (std::size_t j = i + 1; j < m; ++j)
for (std::size_t k = j + 1; k < m; ++k)
if (shared(rows[i], rows[j]) > 0 && shared(rows[j], rows[k]) > 0 &&
shared(rows[i], rows[k]) > 0)
++bins[static_cast<std::size_t>(std::min(core(rows[i], rows[j], rows[k]), 2))];
return bins;
}
/// The pairs of hyperedges that share at least k vertices, by brute force.
inline std::uint64_t brute_strong_pairs(const member_rows& rows, int k) {
std::uint64_t n = 0;
for (std::size_t i = 0; i < rows.size(); ++i)
for (std::size_t j = i + 1; j < rows.size(); ++j) n += shared(rows[i], rows[j]) >= k ? 1 : 0;
return n;
}
Several bins: a triangles Op that sorts the triangles by the size of their core (the vertices
all three hyperedges share), with venn3(). It remembers the wedge in begin_wedge() and adds to
a bin directly in triangle(), so its flush() is empty:
/// The triangles of the line graph by the size of their core, the vertices all three hyperedges
/// share: bin 0 none, bin 1 one, bin 2 two or more (three bins, added to directly).
struct core_triads {
static constexpr int num_bins = 3;
static constexpr dx::shape shape = dx::shape::triangles;
int a = 0; // the wedge (a, b) that the next triangles close
int b = 0;
DYNG_HD void begin_wedge(const dx::hyperedge_rows& /*rows*/, int wedge_a, int wedge_b) {
a = wedge_a;
b = wedge_b;
}
template <class bins_t>
DYNG_HD void triangle(const dx::hyperedge_rows& rows, int c, bins_t& bins) {
const dx::venn_counts v = dx::venn3(rows.row(a), rows.row(b), rows.row(c));
bins.add(v.abc < 2 ? v.abc : 2, 1);
}
template <class bins_t>
DYNG_HD void flush(bins_t& /*bins*/) {}
};
When an Op needs a vertex id, rows.decode(code) gives it. The pairs of hyperedges that both
contain a given vertex:
/// The pairs of hyperedges that both contain the vertex `hub` (one bin): the members are opaque
/// codes, and rows.decode() gives a code's vertex id.
struct hub_pairs {
static constexpr int num_bins = 1;
static constexpr dx::shape shape = dx::shape::pairs;
std::int32_t hub = 0; // the vertex
std::uint64_t count = 0;
DYNG_HD bool has_hub(const dx::hyperedge_rows& rows, int id) const {
for (const dx::member_code code : rows.row(id)) {
if (rows.decode(code) == hub) return true;
}
return false;
}
template <class bins_t>
DYNG_HD void pair(const dx::hyperedge_rows& rows, int a, int b, bins_t& /*bins*/) {
if (has_hub(rows, a) && has_hub(rows, b)) ++count;
}
template <class bins_t>
DYNG_HD void flush(bins_t& bins) {
if (count != 0) bins.add(0, count);
}
};
4. Updates under hyperedge batches, and the stats#
count_local_patterns<op_t>::update(res, h, batch, result) applies a batch of hyperedge
deletions and insertions to the hypergraph and changes the counts by what the batch destroyed and
created, without counting the rest again. A result composes with every other hypergraph result in
one dyng::update(), so one commit updates several patterns (and triad_count) together:
const auto [ts, ps] = dyng::update(res, h, batch.view(), triangles, pairs);
// ts.delta[0] is the change of the triangle count, ts.removed the triangles the deleted
// hyperedges took away (counted on the hypergraph before the batch) and ts.added the ones
// the inserted hyperedges brought (on the hypergraph after it).
EXPECT_EQ(ts.delta[0], static_cast<std::int64_t>(ts.added - ts.removed));
EXPECT_EQ(ts.inserted_frontier, static_cast<std::int64_t>(ts.batch.inserted_ids.size()));
The stats (experimental::local_patterns_stats) hold the batch summary (batch.inserted_ids:
the ids the store gave the inserted hyperedges), the frontier sizes (deleted_frontier,
inserted_frontier), removed and added (the two phases’ counts, summed over the bins) and
delta, the change of every bin. The test updates all four Ops (the other two, with
triad_count, in a second dyng::update() over a copy of the hypergraph), under both id-reuse
orders (hypergraph_properties::reuse: erase_first and insert_first), through an empty, a
deletion-only and an insertion-only batch and three mixed ones. After every batch it checks every
updated result against the brute force and against a fresh compute() (“baseline + deltas ==
recount”). Test every new Op this way, under updates, on every backend you claim: a check of
compute() alone cannot catch an Op that depends on the order of its ids (section 6). A result
that was not part of an update is stale: using it on the new hypergraph throws
stale_result_error, and it must be computed again.
5. The same Op on the host and on the GPU#
The Op is compiled for both: run it on the GPU with dyng::resources::cuda() and on the CPU with
sequential() or openmp(), with identical counts:
using graph_t = dyng::hypergraph<std::int32_t, dyng::unweighted>;
const graph_t h = random_hypergraph<graph_t>(dyng::resources::sequential(), 11);
using pairs_t = dx::count_local_patterns<tutorial::strong_pairs>;
const std::uint64_t on_host = pairs_t::compute(dyng::resources::sequential(), h).count(0);
for (const dyng::backend b : backends()) {
const dyng::resources res = resources_of(b);
const graph_t copy = h.clone(res); // the hypergraph moves to the backend of `res`
EXPECT_EQ(pairs_t::compute(res, copy).count(0), on_host) << dyng::to_string(b);
}
In your own project, put the Op and the calls in a .cu file and build it with nvcc against the
installed library:
cmake_minimum_required(VERSION 3.30)
project(my_patterns CXX CUDA)
set(CMAKE_CXX_STANDARD 17)
set(CMAKE_CUDA_STANDARD 17)
find_package(dyng 0.4 REQUIRED)
add_executable(my_patterns my_patterns.cu)
set_target_properties(my_patterns PROPERTIES CUDA_ARCHITECTURES native)
target_link_libraries(my_patterns PRIVATE dyng::dyng)
(ci/cmake_consumer.sh builds this file, unchanged, against an installed build with a user Op as
my_patterns.cu, and runs it on every backend of the build; in CI without nvcc it is skipped.) A
program that only reads the rows (experimental::access_rows()) or names the types includes the
host header <dyng/experimental/local_patterns.hpp> and needs no nvcc.
The same Op value runs on every backend because it holds only scalars. An Op that needs data of
your own (vertex labels, a vertex set) gets it through a pointer member you set: on cuda it must
point to device memory, on sequential and openmp to host memory, and the data must stay valid
and unchanged for the result’s whole lifetime, because the result keeps the Op value and every
update() counts with it. Such an Op value belongs to one backend.
6. Why the Op never sees the frontier or the sign#
An update counts in two phases: on the hypergraph before the batch, everything through the
deleted hyperedges is counted and subtracted; the batch is applied once; on the hypergraph
after it, everything through the inserted hyperedges is counted and added. A triangle through
two changed hyperedges would be counted twice, so the engine counts it once, at its smallest
changed hyperedge (the ownership rule ownership::min_member of the framework): from a changed
hyperedge f it skips every wedge and every closing hyperedge that is a smaller changed one.
All of this is the engine’s: the frontier (the changed hyperedges), the skips, the sign of each
phase and the bins’ arithmetic. The Op only says what one triangle (pair, hyperedge) is worth.
That is why an Op written for compute() is already correct for update(), and why it cannot get
the update wrong: it holds no view of the hypergraph, so the subtraction cannot read the
hypergraph after the batch. What the Op must guarantee is that a structure’s count does not depend
on who counts it or in which order: the engine may hand a triangle to any worker.
The ids of a call come in no particular order. A full count happens to pass a < b to
pair() and begin_wedge(), and a < b < c for a triangle, because it walks each hyperedge’s
larger neighbours. An update’s phases start from the changed hyperedges instead: a is a changed
hyperedge and b any neighbour, smaller or larger (and c any common neighbour above b). So an
Op’s count must be symmetric in a and b (pairs) and in a, b and c (triangles).
This Op is not:
/// NOT an Op to copy: it counts the pairs {a, b} with |a| > |b|, which depends on the order of
/// the ids. compute() happens to pass a < b, so it agrees with a brute force over every pair
/// i < j; a frontier phase of update() passes the changed hyperedge as `a`, so update() is wrong.
struct bigger_first_pairs {
static constexpr int num_bins = 1;
static constexpr dx::shape shape = dx::shape::pairs;
std::uint64_t count = 0;
template <class bins_t>
DYNG_HD void pair(const dx::hyperedge_rows& rows, int a, int b, bins_t& /*bins*/) {
if (rows.size(a) > rows.size(b)) ++count; // asymmetric in a and b: wrong under update()
}
template <class bins_t>
DYNG_HD void flush(bins_t& bins) {
if (count != 0) bins.add(0, count);
}
};
On the hyperedges {0, 1, 2}, {2, 3} and {3, 4, 5, 6} its compute() gives 1, as a brute
force over every pair i < j does. Deleting hyperedge 2 subtracts the pair counted from the
changed hyperedge as pair(2, 1), which this Op counts (|2| > |1|) although the full count did
not (pair(1, 2)): update() gives 0, a recount gives 1, and nothing is reported. The test
AnOpThatDependsOnTheOrderOfItsIdsIsWrongAfterAnUpdate shows it on every backend. A symmetric
version counts the pairs of different sizes, rows.size(a) != rows.size(b). (A bin that the
subtraction would take below zero is reported as an internal_error, but an asymmetric Op need
not take one there.)
7. Limits#
num_binsis at mostexperimental::max_pattern_bins(1024): the bins of a GPU block live in its shared memory (8 KiB at 1024 bins), and those of a host thread on its stack. A bin outside[0, num_bins)is not written:compute()orupdate()throwsinvalid_argument_error(after the commit, the result is left unusable).The Op is at most
experimental::max_op_size(4,096) bytes: its value is a parameter of every counting kernel and every GPU thread holds a copy of it, so it is small per-worker state, not a table (a larger Op stops at its ownstatic_assert). Keep tables in memory the Op points to (section 5).Data of your own comes through a pointer member, into the memory of the result’s backend, valid for the result’s lifetime (section 5); a pointer-free Op is the only kind that runs on every backend unchanged.
__device__-only callbacks are not reported by nvcc unless the Op goes throughDYNG_EXPERIMENTAL_CHECK_HOST_CALLBACKS(section 2); without it the host backends end the program with exit status 1.C++ and nvcc only, by design: the Op is compiled into kernels. No Python binding (Python gaps).
Experimental: the API may change in any minor release;
ci/api_snapshot.pytracks it and reports changes without failing on them.Closed patterns only: the engine enumerates the triangles, edges and vertices of the line graph. A triad with a pair that shares nothing (the open h-motifs, bins 20-25 of
triad_count, always 0) is not a triangle of the line graph, so no Op of this engine sees it.The members’ codes end at INT_MAX: the set helpers merge rows up to
INT_MAX, so every Op is refused on a hypergraph with 2,147,483,647 vertices (the vertex ids up to 2^31 - 3 are supported).Types:
hypergraph<int32_t, unweighted>andhypergraph<int32_t, int32_t>(the weights are not passed to the Op). The shapestrianglesandpairsneed the line graph and the vertex-to-hyperedge rows (the default properties);keysneeds neither.The counts are unsigned 64-bit sums: a count past 2^64 - 1 throws
capacity_error(an Op that computes a product can report its own overflow withbins.overflow()).
8. Run the tutorial’s code#
In a CUDA build of the repository:
cmake --preset dev-cuda && cmake --build --preset dev-cuda
ctest --preset dev-cuda -R 'Tutorial' # the Ops on every backend, against the brute force
and without nvcc, the host half (the Ops’ callbacks driven by hand on the host rows):
cmake --preset cpu-only && cmake --build --preset cpu-only
ctest --preset cpu-only -R 'TutorialHost'
The ADR that introduced the extension point is ADR 0058: experimental::count_local_patterns: one driver, one engine, and the Op concept;
the API reference is experimental. A new Op makes a good first contribution:
the label good-first-issue:op marks such issues (Labels).