Skip to content

Densest Subgraph Problem: FISTA based algorithm + Large scale tests. - #7770

Merged
rossbar merged 16 commits into
networkx:mainfrom
FaroukY:densest-subgraph-implement-fista
Feb 11, 2025
Merged

rossbar merged 16 commits into
networkx:mainfrom
FaroukY:densest-subgraph-implement-fista

Conversation

@FaroukY

@FaroukY FaroukY commented Dec 14, 2024 •

Copy link
Copy Markdown
Contributor

This PR builds on the work from PR #7731, specifically addressing Future Work point 1: implementing the algorithm from [3], which provides enhanced scalability and improved runtime performance.

The implemented algorithm demonstrates notable advantages over Greedy++, both in the number of iterations required to converge to the densest subgraph and, more importantly, in the vectorizability of each iteration, resulting in significant performance gains. For instance, in the "close_cliques" test case, this algorithm (FISTA) is 26 times faster than Greedy++. For example, on a graph with around 3,300 vertices, and around 100,000 edges, it finds the densest subgraph in ~0.2 seconds compared to Greedy++ which takes ~12 seconds. My implementation is based on my original paper [3].

That said, Greedy++ remains relevant, as it can converge faster than FISTA on certain graphs, particularly those with highly imbalanced degree distributions.

Finally, the PR refactors the tests and adds more scalability test cases.

[3] Harb, Elfarouk, Kent Quanrud, and Chandra Chekuri. 
    "Faster and scalable algorithms for densest subgraph and decomposition."
    Advances in Neural Information Processing Systems 35 (2022): 26966-26979.

@FaroukY

FaroukY commented Jan 9, 2025

Copy link
Copy Markdown
Contributor Author

@rossbar @dschult Happy New Year! Just letting you know that my holiday break is over, and I'm ready to dive back into this whenever you are. No rush if you're still in holiday mode—take your time. Looking forward to getting this reviewed and merged when you're ready! 😊

@FaroukY

FaroukY commented Feb 3, 2025

Copy link
Copy Markdown
Contributor Author

@dschult @rossbar Just checking in, any updates on this? Let me know if there’s anything I can do on my end to help move this forward for the March/April release. Looking forward to your thoughts!

@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.

Thanks for this!

Silly question to start: Why is it called "fractional peeling" and "fractional edge values"?

Any quick estimates of improvement using fista over greedy?
What might be a good way to look at that question? Does it make sense to just use a random graph with say 1000 nodes and run the function?

The code looks like it is bending over backwards to use numpy arrays -- lots of transfers from index to node and back again. The peeling still ends up looping in python. So does numpy really help with this? The payoff appears to be in computing z, clampedx and y in steps 7b,d. Maybe there could be a way to use the arrays in the iterations and avoid all the index conversion in the peeling? I'm not close enough to the code though -- so what do you think?

Just to give a flavor of what I'm thinking about: In a dict-vector system, you'd set up a dict-of-dict vector x and then use that to initialize b, z and clamped_x with something like:

x = {node: dict.fromkeys(nbrs, 0.5) for node, nbrs in G.adj.items()}
b = {node: sum(x_val for nbr, x_val in nbrs.items()) for node, nbrs in x.items()}
y = x.copy()

z = {node: {nbr: y_val - 2 * learning_rate * b[node]
            for nbr, y_val in nbrs.items()} for node, nbrs in y.items()}
clamped_x = {node: {nbr: max(min((z_val - z[nbr][node] + 1) / 2, 1), 0) 
            for nbr, z_val in nbrs.items()} for node, nbrs in z.items()}

I would guess this is slower for the code inside the iterations loop. But it avoids all the index to node conversion stuff at the beginning and the peeling at the end. At the least, it would be worth thinking about whether this could make the peeling code simpler. And maybe it is not worth doing at all. My intuition is clouded by my history of slow index lookups when you get too many of them.

As a whole this algorithm itself looks good, the tests are nicely set up. Fun Stuff!!
Do you want a description of this algorithm somewhere in the docs? Maybe I missed that.
Thanks!!

Elfarouk Harb added 2 commits February 6, 2025 02:13
…mments. Removed _bidirectional_edges, using direct adjacency iteration, and added a lot of docstrings to give context.
@FaroukY

FaroukY commented Feb 6, 2025 •

Copy link
Copy Markdown
Contributor Author

Hi @dschult, thanks for the review, I’ve addressed all your in-code comments. As for your other questions:

Silly question to start: Why is it called "fractional peeling" and "fractional edge values"?

Not silly at all. The FISTA-based algorithm works quite differently. I realized I forgot to add a docstring explaining how the algorithm actually works, so the latest commit should provide more context. In short:

Harb et al. [1] showed that computing the densest subgraph can be formulated as the following convex optimization problem:

Minimize $\sum_{u \in V(G)} b_u^2$

Subject to:
$b_u = \sum_{v : (u,v) \in E(G)} x_{uv}~$ for all $u \in V(G)$
$x_{uv} + x_{vu} = 1.0~~~~~~~~~~~~~~$ for all $(u,v) \in E(G)$
$x_{uv}\geq 0, x_{vu}\geq 0~~~~~~~~~~~~~$ for all $(u,v) \in E(G)$

Here, $x_{uv}$ represents the fraction of edge $(u,v)$ assigned to $u$, and $x_{vu}$ to $v$. So each edge distributes its weight among its two neighbors.

The optimal solution of this convex program provides the densest subgraph (by sorting the vertices by $b_u$ and applying a standard peeling process in this order). However, when using gradient descent or FISTA, we only obtain an approximate solution ($\hat{b}, \hat{x}$) after $k$ iterations for the convex program. Fractional peeling, introduced in [1], is inspired by standard peeling but utilizes the fractional values of $b_u$ and $x_uv$ to determine a "good" ordering—hence the name fractional peeling. It "peels" the vertex $u$ with minimum $b_u$ fractional load value, then for each of its neighbors $v$, it subtracts the fractional edge weight $x_{uv}$ from $b_v$ (remember normal peeling would just subtract 1 signifying $u$ was deleted).

Any quick estimates of improvement using FISTA over Greedy++? What might be a good way to look at that question? Does it make sense to just use a random graph with, say, 1000 nodes and run the function?

In C++, the main advantage of FISTA over Greedy++ is its parallelizability—you can use 4-10 threads, achieving orders-of-magnitude speedup since Greedy++ is inherently sequential.

In Python, the difference is even more drastic. For example, in the benchmark "test_fista_big_dataset" on a graph with ~3,300 vertices and ~100,000 edges (in the tests), FISTA finds the densest subgraph in ~0.29 seconds, compared to ~15.89 seconds for Greedy++, yielding a ~55x speedup:

0.29s call     networkx/algorithms/approximation/tests/test_density.py::test_fista_big_dataset
15.89s call     networkx/algorithms/approximation/tests/test_density.py::test_greedypp_big_dataset

(I removed the Greedy++ test from the official tests since it takes too long). The primary reason is that FISTA allows for NumPy vectorization, making all operations nearly as fast as C, whereas Greedy++ does not benefit from such optimizations since unfortunately it is very sequential.

That said, Greedy++ isn’t completely obsolete—it can converge quickly on some graph classes.

As for what graphs to apply it on, all the graphs in the test suite right now are really hard and adversarially designed to challenge all these approximation algorithms. On a random graph, or even arbitrary "real world" graphs, these algorithms converge extremely fast, often taking for example 10-20 iterations at most which was shown in a lot of prior work practically. This was tested on graphs with even up to hundreds of millions of vertices and more than one hundred million edges. So in a sense, the current tests really forces all the algorithms to "work hard" to find the densest subgraph.

The code looks like it is bending over backwards to use NumPy arrays—lots of transfers from index to node and back again. The peeling still ends up looping in Python. So does NumPy really help with this? The payoff appears to be in computing z, clamped_x, and y in steps 7b, d. Maybe there could be a way to use the arrays in the iterations and avoid all the index conversion in the peeling? I'm not close enough to the code though—so what do you think?

Just to give a flavor of what I'm thinking about: In a dict-vector system, you'd set up a dict-of-dict vector x and then use that to initialize b, z, and clamped_x with something like: [...]

You’re right—I am going out of my way to use NumPy, but for a good reason :). Initially, I implemented it exactly as you suggested (see commit bfe2f42), but after benchmarking, I found it was actually slightly slower than Greedy++ due to dictionary indexing inside the main loop. Simply replacing dictionaries with NumPy arrays led to a huge speedup (commit 5a440a7).

The main issue is that I can’t assume G.nodes are {0, 1, ..., n-1} since networkx allows arbitrary node names (for example strings), which required me to do back-and-forth indexing during fractional peeling. If the nodes were always {0, ..., n-1}, these conversions wouldn't be necessary and the code would be (conceptually) simpler.

Hope that makes sense!

@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.

Thanks for those answers! Very cool!

I dug into the formulas a little bit and it looks temptingly close to being able to track x_uv - x_vu, y_uv - y_vu and b_u - b-v. But the clipping/clamping makes for a nonlinear interaction that might separate the symmetry. Tracking both directions of the edge allows control of the restrictions like x_uv + x_vu = 1. It's also nice to read about the applications to other network problems -- like community detection. I don't see the direct connection, but it'd be cool to connect algorithms like this one to the community detection part of this library.

I have a bunch more suggestions -- push back on any that don't fit. These are suggestions.

  • the doc_string for _fista() won't be seen anywhere because it is a private function. I suggest either copy/paste it into the main function's doc-string -- you could leave it in _fista as well -- and add headings to start sections for greedy++ (just one paragraph) and then fista (with multiple paragraph and a section on peeling.
  • can you rewrap the docs so they are ~80 chars (below 88 chars)? In step 2) of the algorithm you can shorten the expression using b_u(k) and then immediately put the expression for b_u(k). I think this also brings in the idea of b_u, which is helpful.
  • in lines 217, 228, 236, 257 there is a comment at the end of the line which makes the linter split the expression over 3 lines. Try moving the comment to its own line before the expression, and then having a single line for the expression itself. That provides the hint of what is happening before the details, and puts the details in a compact form on one line. It also allows the bluk of the function to appear on one screen. (there are a few places in the tests where this happens too, but those don't help with keeping the expression on one line -- and they keep the comment close to the part of the expression it describes. So I would leave those.)
  • line 252 "peformance" is mispelled.
  • the fractional peeling algorithm can reduce the index finding quite a bit without losing the numpy tools in the following way:
    • store remaining_nodes, heap and best_subgraph in terms of nodes instead of indexes. e.g. best_subgraph = set(remainng_nodes) and
    for idx, node in enumerate(remaining_nodes):
        heap.insert(node, b[idx])

The heap will then pop nodes instead of indexes. node and neighbor will remain in node-land, but you'll need to look up indexes to update b. Something like:

        for neighbor in G.neighbors(node):
            if neighbor in remaining_nodes:
                neighbor_idx = node_to_idx[neighbor]
                # Take off fractional value
                b[neighbor_idx] -= x[edge_to_idx[node, neighbor]]
                num_edges -= 1
                heap.insert(neighbor, b[neighbor_idx])

I believe you end up never using idx_to_node this way either. But the gain is staying with nodes for the heap and neighbor lookup. I think the code is more readable due to fewer lookups. And I think it should be slightly faster but hard to know.

The tests look nice -- basically the same as for the greedy algorithm only run for fista.

Would it be good to include one that compares the output for the two methods?

…idx_to_edge indexing which gave some performance gains. Minor typo and linter fixes too.
@FaroukY

FaroukY commented Feb 8, 2025

Copy link
Copy Markdown
Contributor Author

Hi @dschult, thanks for the recommendations. I've implemented all changes but one (see last comment below)

the fractional peeling algorithm can reduce the index finding quite a bit without losing the numpy tools in the following way...

Nice! This led to further performance gains. The largest test case for FISTA now runs in 0.24s compared to 0.29s previously. According to the profiler, a significant amount of time was saved from _fractional_peeling.

the doc_string for _fista() won't be seen anywhere because it is a private function. I suggest either copy/paste it into the main function's doc-string -- you could leave it in _fista as well -- and add headings to start sections for greedy++ (just one paragraph) and then fista (with multiple paragraph and a section on peeling.

Just did, you can have a look at the new docstring here (from the circleci documentation artifact).

can you rewrap the docs so they are ~80 chars (below 88 chars)? ...

Done

line 252 "peformance" is mispelled.

Nice spot! Fixed

Would it be good to include one that compares the output for the two methods?

After $k$ iterations, the outputs of FISTA and Greedy++ are not necessarily comparable in terms of density. The only feasible validation I can think of is ensuring that the return type is the same. However, we already cover this in several tests by verifying that both algorithms ultimately produce the correct output. So, I don't think additional checks are necessary, unless you have other ideas, in which case I'd be happy to add more tests!

Thanks!

@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.

Excellent -- looks good to me!
Thanks for this addition -- and follow up.
:)
I approve this PR

@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 @FaroukY , this looks great! The implementation and updated explanations are quite nice. I pushed up some docstring formatting updates for the private function (not that it matters) and left a small comment but no blockers!

@FaroukY

FaroukY commented Feb 11, 2025

Copy link
Copy Markdown
Contributor Author

Thanks @rossbar, fixed the minor comment and thanks for the review!

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.

4 participants