Repository navigation
State-of-the-art implementation of Tarjan's algorithm - #8615
Conversation
|
I should add that the code looks quite different because the SciPy version just leaves a component index in an array, whereas NetworkX's version is a generator returning components as they are identified by the algorithm. |
| scc_found.update(scc) | ||
| if source in lowlink: | ||
| continue | ||
| index += 1 |
There was a problem hiding this comment.
Do we need to track index if we do lowlink[source] = len(lowlink) + 1 every time?
There was a problem hiding this comment.
Technically, no, but increasing an integer is faster than computing the length of a dictionary (and here I might be wrong—I'm not exactly a Python expert). Moreover, it is closer to the basic algorithm description, which uses arrays rather than dictionaries as nodes are assumed to be integers in [0..n).
| lowlink[source] = index | ||
| dfs_v.append(source) | ||
| dfs_it.append(iter(adj[source])) | ||
| dfs_lead.append(True) |
There was a problem hiding this comment.
Have you considered using an integer here?
# push True / False
bits = (bits << 1) | 1 # push True
bits = (bits << 1) # push False
# peek
top = bits & 1
# set top = False
bits &= ~1
# pop
top = bits & 1
bits >>= 1
There was a problem hiding this comment.
It doesn't seem like a good idea—it's twice as slow:
============================================================
Erdős–Rényi N=100,000 avg_deg=20 nnz=2,000,000 nodes=100,000
nx.strongly_connected_components : 0.6233s (1 components)
============================================================
Single SCC N=100,000 avg_deg≈20 nnz=1,999,808 nodes=100,000
nx.strongly_connected_components : 0.6290s (1 components)
============================================================
Chain (DAG) N=200,000 edges=199999 nnz=199,999 nodes=200,000
nx.strongly_connected_components : 1.0897s (200,000 components)
There was a problem hiding this comment.
Interesting, thanks for trying it out! It seems like pure python bitsets are not really performat
| comp_stack = [] | ||
| index = 0 | ||
|
|
||
| for source in G: |
There was a problem hiding this comment.
You could iter adj here:
for source, neighbors in adj.items():
...There was a problem hiding this comment.
I cannot find any measurable difference. The form you propose, however, is misleading to the reader who wants to understand the algorithm, because most of the times we will not use the neighbors.
| # v is an SCC root: pull its members off comp_stack. | ||
| v_low = lowlink[v] | ||
| scc = {v} | ||
| while comp_stack and lowlink[comp_stack[-1]] >= v_low: |
There was a problem hiding this comment.
You could remove this dict access by storing (v, lowlink[v]) in th comp_stack but not 100% sure it will necessarily be faster.
|
Very cool, thanks for this! It would be great to run benchmarks in DirectedAlgorithmBenchmarks |
I'm desperately trying, but if you don't have the full stack |
|
Ok, somehow I made it. Well, this is a bloodbath 😂. I mean, there are measurament that change unit. The complete graph on 1000 nodes is 5x faster. New: |
amcandio
left a comment
There was a problem hiding this comment.
Amazing, I was not aware of this state of the art implementation. I approve this PR. Thank you so much!
dschult
left a comment
There was a problem hiding this comment.
Very nice!
It works better -- not crushingly, but systematically.
Go Tarjan! :)
I am surprised that a single queue of 3-tuples is slower than 3 separate queues. And even a queue 2-tuples and a set to hold any nodes where lead is False is slower. We may have to pay attention to our other queues -- many of them store tuples in the stack. Part of what may make this slower is the update that has to pass over the remaining stack members just to pull off the first entry in the tuple. But I'm not sure. rapping and unwrapping tuples may be part of the relatively high cost of calling functions in Python too. fun fun with optimizing python!
I have two comments below. One is a doc word issue and the other is a test question.
| assert len(components) == 1 | ||
| assert components[0] == {0, 1, 2, 3, 4, 5} |
There was a problem hiding this comment.
Does this actually test that the code bails? It looks like it is only testing that a single scc is returned... not that the code stopped once it found all the nodes. Thoughts?
There was a problem hiding this comment.
The test is designed so that the exit is early. I checked with a smoke test (adding a print) that this is actually the case. But there's no way that comes to my mind to embed that in the test.
Not crushingly? Are we looking at the same benchmarks? 😅
So, one thing I discovered checking how things are implemented in Python is that apparently the list of lead bits uses a pointer per Boolean 🥶. So that's not a bit. It is possible to replace the list with a byte array, reducing radically the space but (shockingly) benchmarks are 10% slower. I leave to you the choice. |
Co-authored-by: Dan Schult <[email protected]>
hee hee.... I guess it depends on perspective. It's a factor of ~2. That's significant for sure, but I usually reserve crushingly for factors of 10 or 100. :) I am fine with the handling of the bool I would like your take on the test that says in comments that it is checking that the code bails early -- but it actualy only tests that the answer is correct -- not that the code bailed. Since we cant really check if bailing has occurred, should we keep this teat? |
Definitely different benchmarks. It's almost 6x faster on the complete graphs in NetworkX benchmarks.
A dictionary would be much slower—the entire point of the bit stack is locality of access. I'm not suggesting a different data structure, I'm saying that using a bytearray every boolean costs a byte, whereas now it costs a pointer, which is a lot. But it's faster because... because Python 🤷🏻♂️.
I checked and it does. It tests all the partial exit conditions. If someone fiddles with the code and disturbs the invariants it helps, as it could early exit with a wrong component. |
dschult
left a comment
There was a problem hiding this comment.
I suspect a couple of dictionaries (one for the LIFO queue {v: iter(adj[v])}) and one for the lead tracking) and some len(lowlink) calls could make this simpler, but probably not faster. But I am confident that @vigna has investigated the speed issues here --
It's very nice to include the improved algorithms!
And it is really cool that Tarjan followed up on the 1972 paper with a 2024 paper!!!! Only 52 years later!
I approve this PR. And I give a big thank you to @vigna for providing so much tempting structure here to optimize anything and everything. Rabbit hole alert! :)
The current implementation of the computation of strongs components in NetworkX is the same as that of SciPy: it is a two-pass algorithm that needlessly scan every arc twice and allocates significantly more memory than necessary.
The SciPy version will be replaced in 1.18 with a state-of-the art implementation of Tarjan's algorithm that I coded starting from Tarjan and Zwick's recent survey (see the SciPy PR for details).
This PR implements essentially the same algorithm for NetworkX. The same comments apply: the algorithm is more than twice faster because, beside halving the visit time, it has better locality. Reduction of memory footprint is more difficult to determine, but it should be better than that of SciPy because this version does not materialize iterators on successors unless they are on the the visit stack.
This simple benchmark gives the following results with the current NetworkX version:
These are the results with the new implementation:
UPDATE: Sorry, I said 30% decrease in space but it's actually data-dependent. The Scipy version uses at most three words per node, with one word coming from the sum of the lengths of the visit and component stacks, which is bounded by the number of nodes.