Repository navigation
Faster square_clustering - #7810
Conversation
|
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 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
left a comment
There was a problem hiding this comment.
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!
|
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 While we're here, should we add |
|
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: networkx/networkx/algorithms/bipartite/cluster.py Lines 262 to 267 in 33768e1 networkx/networkx/algorithms/bipartite/redundancy.py Lines 109 to 111 in 33768e1 networkx/networkx/algorithms/centrality/dispersion.py Lines 63 to 67 in 33768e1 networkx/networkx/algorithms/community/quality.py Lines 312 to 315 in 33768e1 |
| 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 |
There was a problem hiding this comment.
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).
There was a problem hiding this comment.
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 :) :)
There was a problem hiding this comment.
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:
networkx/networkx/classes/graph.py
Line 1372 in 33768e1
If I experiment with using dict.keys again, I'll share what I find!
There was a problem hiding this comment.
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).
|
I am collecting some benchmarks on real data here:
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 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 Are there any other datasets (preferably from https://sparse.tamu.edu/) that anyone would like me to benchmark and compare? |
|
Gentle nudge. Does this need anything else? @rossbar approved, so I think this is awaiting somebody else to merge. |
|
Two comments from a quick read-through. 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 |
|
Thanks for taking a look!
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.
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
Heh, it turns out using |
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.
I think it depends on the graph structure whether
This might be the case too. The old way would actually create a set where squares are counted individually as |
dschult
left a comment
There was a problem hiding this comment.
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
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 (
*_previs original version,*_newis new version in this PR):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_clusteringfor NetworkX and @marcusjcrook who corrected it a few years ago (just in case y'all are interested in the fun of algorithm design!).