Skip to content

Faster square_clustering - #7810

Merged
dschult merged 14 commits into
networkx:mainfrom
eriknw:faster_square_clustering
Apr 14, 2025
Merged

dschult merged 14 commits into
networkx:mainfrom
eriknw:faster_square_clustering

Conversation

@eriknw

@eriknw eriknw commented Jan 25, 2025 •

Copy link
Copy Markdown
Contributor

This implementation is based on my own toiling and experimentation. I don't know if this formulation is published anywhere. I named and described things as best I could, but I suspect it's still somewhat magical. I "discovered" this mostly from brute force and dumb luck--or a little intuition and a lot of perspiration--but it's still a bit mysterious to me. I believe it's solid though! The number of squares and triangles is based on https://arxiv.org/abs/2007.11111 ; the other terms in the denominator are more tricky.

Performance comparison (*_prev is original version, *_new is new version in this PR):

In [1]: import networkx as nx

In [2]: G = nx.gnp_random_graph(5000, 0.001)
In [3]: %timeit nx.algorithms.cluster.square_clustering_prev(G)
307 ms ± 36.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [4]: %timeit nx.algorithms.cluster.square_clustering_new(G)
217 ms ± 31.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [5]: nx.algorithms.cluster.square_clustering_prev(G) == nx.algorithms.cluster.square_clustering_new(G)
Out[5]: True

In [6]: G = nx.complete_graph(100)

In [7]: %timeit nx.algorithms.cluster.square_clustering_prev(G)
5.54 s ± 197 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [8]: %timeit nx.algorithms.cluster.square_clustering_new(G)
60.6 ms ± 4.69 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

You can see we get a 90x speedup for the second example with the "massive" hundred node graph. I'm curious how it performs on larger, real-world graphs, which previously took days when I benchmarked and compared to graphblas_algorithms (see the chart here: https://github.com/python-graphblas/graphblas-algorithms).

I changed the algorithm somewhat (and added a note) by ignoring self-loops (xref #7261 and #7238), which seems like the reasonable thing to do and matches other clustering algorithms.

We could probably get a factor of 2 or so performance if we cached set(G.neighbors(v)) and perhaps more if we tried to reuse computation between iterations, but this would use a lot more memory.

CC @hagberg who first implemented square_clustering for NetworkX and @marcusjcrook who corrected it a few years ago (just in case y'all are interested in the fun of algorithm design!).

@eriknw

eriknw commented Jan 26, 2025 •

Copy link
Copy Markdown
Contributor Author

How does NetworkX usually handle novel implementations? I know there's value in having good reference implementations that can be understood when reading source papers. I think the new version is a good reference implementation, but it is (probably) lacking a source paper (I haven't found one yet). Fwiw, I think this algorithm for square clustering is at least worth a conference paper; would anybody be interested in helping with this? If anybody finds relevant prior art--papers or implementations--please share!

Also, why is there not a squares function similar to triangles? It comes up: https://stackoverflow.com/questions/68893635/counting-the-number-of-squares-in-a-bipartite-networkx-graph
It is a bit simpler to understand and can serve as one step towards understanding square clustering:

def squares(G, nodes=None):
    if nodes is None:
        node_iter = G
    else:
        node_iter = G.nbunch_iter(nodes)
    square_counts = {}
    for v in node_iter:
        v_neighbors = set(G.neighbors(v))
        v_neighbors.discard(v)  # Ignore self-loops
        if len(v_neighbors) <= 1:
            square_counts[v] = 0
            continue
        squares = 0
        # Iterate over all neighbors of neighbors
        two_hop_neighbors = set().union(*(G.neighbors(u) for u in v_neighbors))
        two_hop_neighbors.discard(v)
        for u in two_hop_neighbors:
            u_neighbors = set(G.neighbors(u))
            u_neighbors.discard(u)  # Ignore self-loops
            # P2 from https://arxiv.org/abs/2007.11111
            p2 = len(u_neighbors & v_neighbors)
            # squares is C_4, sigma_12 from https://arxiv.org/abs/2007.11111
            squares += p2 * (p2 - 1)
        square_counts[v] = squares // 2
    if nodes in G:
        # Return the value of the sole entry in the dictionary.
        return square_counts[nodes]
    return square_counts

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Having skimmed through the first referenced paper my impression is that self-loops should be ignored in the square_clustering computation. This is further evidenced by the fact that triangles and the related "standard" clustering functionality ignores self-loops.

I'm still working my way through the algorithms (this one and the formulae published in the references) to make sure I understand correctly!

@eriknw

eriknw commented Jan 27, 2025

Copy link
Copy Markdown
Contributor Author

Thanks for taking a look @rossbar!

The idea behind the new algorithm and why it's faster is straightforward: instead of iterating over all u-w combinations from v in search of u-v-w-x squares (and effectively visiting x many times), the new algorithm iterates over x (the two-hop neighbors) to find squares. From here, it's "just" a matter of counting and keeping the contributions straight (easier said than done!). Fwiw, I still find the original algorithm somewhat mysterious too.

While we're here, should we add @not_implemented_for("directed") to square_clustering? I don't think the original or new algorithms were ever meant to work on directed graphs, since there are no tests, special handling for directed, or discussion about them in the docstring as is done in clustering.

@eriknw

eriknw commented Jan 30, 2025

Copy link
Copy Markdown
Contributor Author

Closely related, counting squares in bipartite graphs is often called "counting butterflies" or 2x2 bi-cliques in the literature. For example: "Accelerated butterfly counting with vertex priority on bipartite graphs", Kai Wang, et al. For all kinds of graphs, 4-cycles is sometimes used.

It's pretty fun to tell people you were "counting butterflies" when they ask e.g. "what did you do last weekend?" 😜

We may be able to use the same trick to speed up other places, such as:
(this first one can be sped up for sure)

def _four_cycles(G):
cycles = 0
for v in G:
for u, w in itertools.combinations(G[v], 2):
cycles += len((set(G[u]) & set(G[w])) - {v})
return cycles / 4

overlap = sum(
1 for (u, w) in combinations(G[v], 2) if (set(G[u]) & set(G[w])) - {v}
)

possib = combinations(ST, 2)
total = 0
for s, t in possib:
# neighbors of s that are in G_u, not including u and v
nbrs_s = u_nbrs.intersection(G_u[s]) - set_uv

# Iterate over the communities, quadratic, to calculate `possible_inter_community_edges`
possible_inter_community_edges = sum(
len(p1) * len(p2) for p1, p2 in combinations(partition, 2)
)

Comment on lines 262 to 273
def _four_cycles(G):
cycles = 0
seen = set()
for v in G:
for u, w in itertools.combinations(G[v], 2):
cycles += len((set(G[u]) & set(G[w])) - {v})
seen.add(v)
v_neighbors = set(G.neighbors(v))
two_hop_neighbors = set().union(*(G.neighbors(u) for u in v_neighbors))
two_hop_neighbors -= seen
for x in two_hop_neighbors:
p2 = len(v_neighbors & set(G.neighbors(x)))
cycles += p2 * (p2 - 1)
return cycles / 4

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using seen here gives us an additional factor of 2 performance, which we can do since we're counting all squares (perhaps we can get even more gain somehow).

Some performance comparisons of the original and the new versions

In [1]: import networkx as nx

In [2]: B = nx.algorithms.bipartite.complete_bipartite_graph(100, 40)

In [3]: nx.bipartite.robins_alexander_clustering(B)
Out[3]: 1.0

In [4]: nx.bipartite.cluster._four_cycles_orig(B)
Out[4]: 3861000.0

In [5]: nx.bipartite.cluster._four_cycles_new(B)
Out[5]: 3861000.0

In [6]: %timeit nx.bipartite.cluster._four_cycles_orig(B)
1.56 s ± 222 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [7]: %timeit nx.bipartite.cluster._four_cycles_new(B)
19.4 ms ± 1.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [8]: B = nx.bipartite.random_graph(1000, 2000, 0.01)

In [9]: nx.bipartite.robins_alexander_clustering(B)
Out[9]: 0.01001574836117604

In [10]: nx.bipartite.cluster._four_cycles_orig(B)
Out[10]: 10047.0

In [11]: nx.bipartite.cluster._four_cycles_new(B)
Out[11]: 10047.0

In [12]: %timeit nx.bipartite.cluster._four_cycles_orig(B)
1.61 s ± 102 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [13]: %timeit nx.bipartite.cluster._four_cycles_new(B)
807 ms ± 191 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [14]: B = nx.bipartite.random_graph(10000, 2000, 0.001)

In [15]: nx.bipartite.robins_alexander_clustering(B)
Out[15]: 0.0010247986195359771

In [16]: nx.bipartite.cluster._four_cycles_orig(B)
Out[16]: 102.0

In [17]: nx.bipartite.cluster._four_cycles_new(B)
Out[17]: 102.0

In [18]: %timeit nx.bipartite.cluster._four_cycles_orig(B)
399 ms ± 79.6 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

In [19]: %timeit nx.bipartite.cluster._four_cycles_new(B)
245 ms ± 43 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

As with square_clustering, this is much faster for some graphs (lots of neighbors), and is a little faster for other graphs (fewer neighbors).

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It might be faster to use dict than set where possible historically (not sure if the speed-ups implemented in the recent versions of python have changed this -- but they focus on sets so probably still true). The dict.keys() method provides the set operations here.

To take advantage of the dict speed you have to shed the public views and go to the private inner workings G._adj (see #4895).

for v in G:
    v_nbrs = G._adj[v].keys()
    two_hop_neighbors = set().union(*(G._adj[u] for u in v_nbrs))
    for x in two_hop_neighbors:
        len(v_nbrs & G._adj[x].keys()) 

And we are deep into rabbit hole territory here :) :)

@eriknw eriknw Feb 2, 2025 •

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the suggestion!

I did play around with using dict.keys views, but doing so was a little slower for me (but I didn't try to use _adj). We'd need to discard v and x before taking the length to ignore self-edges, so sets are convenient. We do use G._adj in nx-cugraph for maximizing performance to convert from networkx, but we are careful to only use _adj for standard NetworkX graph classes and not subclasses:
https://github.com/rapidsai/nx-cugraph/blob/edd96f010ec93bf0b9999a5c09d60532f0a54eb7/nx_cugraph/convert.py#L236-L245

Similarly, using G._adj in networkx functions does not appear common practice (mostly in a couple shortest path algorithms), so I'd prefer to keep things more standard. After all, we're improving algorithmic complexity here, which is already a huge win!

One reason I used G.neighbors is it uses _adj internally:

return iter(self._adj[n])

If I experiment with using dict.keys again, I'll share what I find!

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I updated to use G._adj, which sometimes gives good speedup for square_clustering. For example:

189 ms ± 24 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)  # G.neighbors
138 ms ± 16 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)  # G._adj


60.1 ms ± 6.75 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)  # G.neighbors
36.6 ms ± 1.23 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)  # G._adj   

I didn't see any benefit using .keys() for either square_clustering or _four_cycles (I'm using Python 3.12.8).

@eriknw

eriknw commented Feb 11, 2025 •

Copy link
Copy Markdown
Contributor Author

I am collecting some benchmarks on real data here:

data # nodes # edges # squares prev new prev / new
email-Enron 36,692 367,662 145,048,916 254 s 58.1 s 4.4
preferentialAttachment 100,000 999,970 360,332 78.3 s 64.3 s 1.2
caidaRouterLevel 192,244 1,218,132 192,960,428 152 s 50.5 s 3.0
dblp-2010 326,186 1,615,400 114,852,652 59 s 17.3 s 3.4
citationCiteseer 268,495 2,313,294 52,858,000 238 s 145 s 1.6
coAuthorsDBLP 299,067 1,955,352 216,969,444 104 s 38.3 s 2.7
as-Skitter 1,696,415 22,190,596 251,076,792,072 DNF 31,700 s N/A
coPapersCiteseer 434,102 32,071,440 943,803,419,816 118,000 2,400 s 49
coPapersDBLP 5,404,486 30,491,458 197,618,846,172 40,600 s 3,200 s 17

Running the last three take much longer than the others. My hunch is that the last three will also show the greatest improvement, because they have many more squares per node (or at least coPapersCiteseer will, because it has much higher average degree than the others and the most squares per node of all). Most of the data sets have average degree between 5-10, which is kind of boring that they're so similar. My hunch is based on my demonstration above that showed the new algorithm performing much better on more dense graphs.

Heads up: the final benchmarks will take days to run with the old implementation, so don't hold your breath. I computed number of squares for the last three with graphblas-algorithms.

If we optimize the previous implementation by using G._adj, we can get a factor of 2 or so improvement, which makes it faster than the new implementation in this PR for preferentialAttachment and citationCiteseer (barely) datasets.

Are there any other datasets (preferably from https://sparse.tamu.edu/) that anyone would like me to benchmark and compare?

@rossbar rossbar left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @eriknw , this LGTM! As mentioned earlier in the discussion IMO the ignoring of self-loops is a bug fix so +1 for that changed behavior!

@eriknw eriknw added this to the 3.5 milestone Mar 7, 2025
@eriknw

eriknw commented Apr 2, 2025

Copy link
Copy Markdown
Contributor Author

Gentle nudge. Does this need anything else? @rossbar approved, so I think this is awaiting somebody else to merge.

@dschult

dschult commented Apr 3, 2025

Copy link
Copy Markdown
Member

Two comments from a quick read-through.
Why is it better to iterate over the two-hop nbrs (x) of v (to find the combinations u-v) than to iterate over the combinations u-v to find the number of x? Are there fewer two-hop nbrs than combinations of u-v? Or is each lookup faster for finding u-v combinations given x than finding how many x exist for a u-v combination? :)

This algorithm might be one where we could try making a dict-of-sets from the graph at the beginning -- throwing out selfloops and converting to sets so we don't have to do that repeatedly. We are doing the conversion already, so it won't it down for sure. How much it helps depends on how often we are repeating the lookup/conversion of neighbors to sets. But, in any case, we've done it elsewhere with success. Naming like G_adj makes the conversion from one to the other fairly easy -- but you'll want to remove the checking for selfloops code and maybe change other pieces too. This is a kind of "since we're in the rabbit hole already" point to make. So its fine to say "enough for this PR".

@eriknw

eriknw commented Apr 4, 2025

Copy link
Copy Markdown
Contributor Author

Thanks for taking a look!

Why is it better to iterate over the two-hop nbrs (x) of v (to find the combinations u-v) than to iterate over the combinations u-v to find the number of x? Are there fewer two-hop nbrs than combinations of u-v? Or is each lookup faster for finding u-v combinations given x than finding how many x exist for a u-v combination? :)

Ha, great question, and one that is especially "fun" after being away from this for a couple months 😜. When I'm able to reply with a sensible explanation, I will... but not today. I think the benchmarks are pretty compelling though.

This algorithm might be one where we could try making a dict-of-sets from the graph at the beginning -- throwing out selfloops and converting to sets so we don't have to do that repeatedly.

Yeah, in my original post of this thread I said "We could probably get a factor of 2 or so performance if we cached set(G.neighbors(v))", so getting a factor of say 50% is doable if we pre-compute a dict-of-sets. I didn't do this as part of this PR for two reasons: (1) doing so would use more memory, and (2) for square_clustering in particular, nodes can be given, so we may not need to convert all neighbors to sets. So, for now, I went for simply and less memory, but this could indeed be made a bit faster, and I wasn't sure if this tradeoff (more speed for more memory usage) was commonly done or acceptable for networkx.

Naming like G_adj [...]

Heh, it turns out using G_adj = G._adj can save a non-trivial amount of time (5-10%)! Done in the latest commit.

@eriknw

eriknw commented Apr 11, 2025

Copy link
Copy Markdown
Contributor Author

Why is it better to iterate over the two-hop nbrs (x) of v (to find the combinations u-v) than to iterate over the combinations u-v to find the number of x?

Short answer: I'm actually not sure! Pragmatically, I think it's more useful to demonstrate that the new approach is faster for a wide range of graphs than to fully understand why.

Are there fewer two-hop nbrs than combinations of u-v?

I think it depends on the graph structure whether [# 2-hop neighbors] (new method) is clearly better than [# 1-hop neighbors]**2 (old method). For some graphs, the two approaches (when equally optimized) are about the same performance. For other graphs, using the new 2-hop neighbor approach is much faster.

Or is each lookup faster for finding u-v combinations given x than finding how many x exist for a u-v combination?

This might be the case too. The old way would actually create a set where squares are counted individually as squares += len(u_neighbors & v_neighbors), whereas the new way computes a new set where the squares are counted as squares += p2 * (p2 - 1), so maybe the latter is able to avoid some work.

@dschult dschult left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That description helps me understand that graphs which "expand" quickly (degrees are bigger as you take hops away from most nodes) are where this could prove to be slower... That is, the number of 1-hop neighbors is the degree of the node, but if the degree of those neighbors tends to be bigger than the degree of the node, the number of 2-hop nodes could be larger than the number of pairs of 1-hop neighbors. The more efficient counting using the length of sets rather than the length of an intersection of sets could be very helpful too. :)

I approve this PR

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Development

Successfully merging this pull request may close these issues.

3 participants