Streaming label propagation#
In this tutorial you run DynLP, dynG’s label_propagation, twice. Part 1 reproduces the
paper’s setup on LabelPropagation-CUDA’s own synthetic stream and gets the original’s labels
byte for byte. Part 2 runs your own data: feature vectors turned into a kNN similarity graph by
the recipe datasets/preprocess/knn_graph.py, arriving in batches, in the streaming mode (rows
that grow, the threshold taken from the current graph), with the labels handed to PyTorch without
a copy. It takes about ten minutes on a laptop CPU; every step also runs on a GPU with
dyng.Resources.cuda() (a CUDA plugin wheel: pip install "dyng[cu13]"), where the labels are
device memory: read them with lp.labels.to_numpy() or hand them to PyTorch with
torch.from_dlpack(lp.labels) (NumPy’s np.from_dlpack takes host arrays only).
What you need: dynG 0.4 or newer, pip install "dyng>=0.4" (label_propagation is new in 0.4;
this upgrades an installed 0.3.0, which does not have it, but not its CUDA plugin, which is
pinned to its own version: with the plugin, upgrade both with pip install -U "dyng[cu13]" or
"dyng[cu12]", Install), PyTorch for
the last step (optional), and a clone of the repository for the recipe (datasets/ is not in the
wheel). The algorithm itself is described
on label_propagation: binary harmonic label propagation under vertex batches; the row layouts on Row layouts, vertex batches and capacities.
The example, the recipe and their input are in the repository, not in the installed package: clone it and run every command of this page from its root (the tag of your version keeps the files as this page quotes them):
git clone --branch v0.4.0 https://github.com/dyng-dev/dyng.git
cd dyng
The problem in two sentences#
Some vertices of a similarity graph are labelled with a class, 0 or 1 (the seeds); every other
vertex should get a label F in [0, 1] that is the weighted average of its neighbours’ labels
(the harmonic solution), and its class is F >= 0.5. Vertices arrive in batches with their edges
and leave, and dyng.label_propagation.update() brings the labels up to date by propagating only
from the vertices a batch affects.
Part 1: the paper’s setup, the original’s bytes#
LabelPropagation-CUDA generates a synthetic Erdős-Rényi stream: the full graph, the true class of
every vertex, and batches of arriving and departing vertices with their edges. dynG generates the
same stream byte for byte (dyng.generators.legacy.dynlp_vertex_arrival_stream) and runs the
published setup: the graph gets the stream’s full degrees as its row capacities (slot rows that
never move), compute() runs on the empty graph (every label 0.5), and every batch is one
update() with the published threshold (the full graph’s average edge weight). This is
examples/python/label_propagation_torch.py:
res = dyng.Resources.cuda() if backend == "cuda" else dyng.Resources.sequential() # no OpenMP
stream = dyng.generators.legacy.dynlp_vertex_arrival_stream(
total_vertices=n, num_batches=5, seed=42, resources=dyng.Resources.sequential()
)
g = dyng.Graph.with_capacity(stream.row_capacity, resources=res) # slot rows, float32 weights
lp = dyng.label_propagation.compute(
g, update_schedule="damped", similarity_threshold=stream.similarity_threshold
)
lp.reserve(stream.max_batch_vertices, stream.max_batch_edges)
for i, batch in enumerate(stream.batches):
st = dyng.label_propagation.update(g, batch, lp)
print(
f"batch {i}: {st.iterations} iterations, {st.components} components, "
f"{g.num_active_vertices} active"
)
The resources are explicit: sequential or cuda (label_propagation has no OpenMP backend in
0.4: dyng.label_propagation.compute() and update() given OpenMP resources raise
NotSupportedError naming the fix). The damped
schedule makes the labels bitwise reproducible: on the sequential backend they equal
dyng-compat-dynlp’s sequential output, and on cuda they equal the original’s own
dynlp_labels.txt byte for byte (the example’s CI test compares both against committed digests).
Run it:
$ python examples/python/label_propagation_torch.py out sequential
batch 0: ...
...
$ dyng label_propagation update --generate legacy --total-vertices 5000 --num-batches 5 \
--update-schedule damped --backend sequential --out run
Both write the labels in the original’s format (i label with six decimals,
dyng.io.write_labels); run/dynlp_labels.txt and out/dynlp_labels.txt are the same bytes.
The accuracy the example prints is about 51 %: the synthetic weights carry little signal with 1 %
seeds, as the original’s own README says (“it is not a quality measure of the update”). Quality is
measured against the harmonic solution (dyng.testing.harmonic_solution) and IrLP; real data,
part 2, is where the labels mean something.
Part 2: your own data, streaming#
Feature vectors#
Any n x d matrix of feature vectors works (image embeddings, TF-IDF rows); here two Gaussian blobs stand in for them:
rng = np.random.default_rng(2026)
n, d = 2000, 16
y = (np.arange(n) % 2).astype(np.int8) # two classes
centre = rng.standard_normal(d)
centre *= 2.0 / np.linalg.norm(centre)
x = np.where(y[:, None] == 1, centre, -centre) + 0.5 * rng.standard_normal((n, d))
np.save(out / "features.npy", x) # n x d feature vectors, one per row
(out / "labels.txt").write_text("".join(f"{c}\n" for c in y)) # their classes
The kNN graph and the arrival batches#
The DynLP paper built its non-graph datasets as cosine-similarity kNN graphs with k = 5; the
recipe does the same (scikit-learn when it is installed, a NumPy brute force otherwise: both write
the same files) and, with --arrival-batches, cuts the vertices into batches in a seeded random
order, a share of each batch’s arrivals with their class as seeds, every edge in the batch of its
later endpoint, and departures of earlier vertices:
subprocess.run(
[sys.executable, RECIPE, features, out / "g.txt", "--labels", labels, "-k", "5",
"--arrival-batches", "5", "--seed-fraction", "0.01", "--seed", "7"],
check=True,
) # fmt: skip
It writes g.txt (the graph, u v w with float weights in (0, 1]; dyng.io.read_edge_list(..., weight_dtype="float32", directed=False) reads it, and dyng label_propagation compute --graph g.txt --seeds seeds.txt --out run runs it with seed labels, v class lines such as a share of
g.true_labels.txt’s), g.dgb (the
five batches, with vertex records: arrivals with their seed labels, the edges they bring,
departures), g.row_capacity.txt (each vertex’s final degree), g.true_labels.txt and
g.stream.json (the published threshold). The paper’s own datasets are not redistributed (the
recipe’s header names where to get them).
The streaming mode#
You could run these batches in the published setup, since the recipe wrote the final degrees and
the threshold. A real stream does not know them, so run the streaming mode: slack rows
without capacity hints (a row that outgrows its slots moves to the tail of the slot arena, and the
arena is compacted when the dead slots outnumber the live ones) and tau of the current graph
(similarity_threshold left unset):
n = len((out / "g.true_labels.txt").read_text().splitlines())
g = dyng.Graph.with_capacity([], vertex_capacity=n, layout="slack", resources=res)
lp = dyng.label_propagation.compute(g, update_schedule="damped") # tau: the current graph's
for i, batch in enumerate(dyng.io.read_binary_batches(out / "g.dgb")):
st = dyng.label_propagation.update(g, batch, lp)
print(
f"batch {i}: {g.num_active_vertices} active, {st.iterations} iterations, "
f"{st.batch.relocated_rows} rows moved, {st.batch.compactions} compactions"
)
Each update() reports what the batch did to the rows (st.batch.relocated_rows,
st.batch.compactions) next to the propagation’s counts. The two lines that differ from the
published setup are the layout and the threshold; the streaming mode has no performance gate, and
at 500k vertices it takes about 1.4x the published setup’s update time.
The labels#
lp.labels is a read-only float32 dyng.Array over the result’s memory: NumPy and PyTorch read
it without a copy.
active = g.vertex_status() == dyng.VertexStatus.active
unseeded = active & (lp.seed_labels.to_numpy() < 0)
F = np.from_dlpack(lp.labels) # float32, read-only, no copy (on the host backends)
accuracy = ((F[unseeded] >= 0.5) == (y[unseeded] == 1)).mean()
print(f"accuracy {accuracy:.4f} over {unseeded.sum()} vertices")
On the two blobs the accuracy is above 95 % (the test checks it, and that the labels are within
2000 delta of the harmonic solution of the final graph). With PyTorch, torch.from_dlpack views
the same memory (on cuda, device memory on cuda:0). PyTorch has no read-only tensors, so the
tensor aliases the result’s labels and must not be written (a write changes the state the next
update starts from); clone() it to modify it:
F = torch.from_dlpack(lp.labels) # a tensor over the result's memory: no copy
assert F.data_ptr() == lp.labels.__array_interface__["data"][0]
classes = (F >= 0.5).to(torch.int8) # what a model downstream would read
del F # drop the view before the next update (or it copies the labels once)
A view keeps showing the labels it was made from: if a view is still alive when the next update()
runs, the update copies the result’s per-vertex state first and changes the copy (copy-on-write),
so drop views you no longer need.
Where to go next#
label_propagation: binary harmonic label propagation under vertex batches: the options (tolerance, the iteration cap and what happens at it, the engines), the determinism of each schedule, the gates against the original, and the differences from the paper.
Row layouts, vertex batches and capacities: slot rows, slack rows, vertex status and net-effect batches.
dyng label_propagation --helpand Command-line interface: the same runs from the shell, with the original’s output files.