Repository navigation
Optimizing Dijkstra's paths to target (~50x faster for graphs with multiple-hops shortest path) - #8023
Conversation
|
There might be a case where computing all predecessors can be slower than computing the list. Need to experiment more but that could be easily fix by an internal Boolean parameter that limits the amount of predecessors to 1. |
I tried with a graph with a bunch of predecessors (~10k) and not really much change: N = 10000
fan = nx.Graph()
fan.add_node(0)
fan.add_node(N - 1)
for mid in range(1, N - 1):
fan.add_edge(0, mid)
fan.add_edge(mid, N - 1)
graphs["fan_two_step_undirected_10000"] = fan |
fei0319
left a comment
There was a problem hiding this comment.
I think we can push the optimization even further!
This path reconstruction technique can be extended to target is None cases. We can completely deprecate the old way of list copying (paths[u] = paths[v] + [u]), and reconstruct paths for all targets, even when we have more than one target.
The point of doing so is that list copying can happen up to
This should work well with dense graphs. For sparse graphs, the reconstruction method could be slower than the original one due to cache or something. The following method can be used to speed up (it should be rather efficient):
# Note that the Dijkstra algorithm inserts node to dist in ascending order of distance
for u in dist:
paths[u] = paths[pred[u][0]] + [u]So we come back to list copying. The only difference is that we used to copy list upon every relaxation in Dijkstra (for at most
Another consideration is that, in the original implementation paths are set for all nodes before target when target is given, while in only paths[target] is set in this one. Additionally, the original implementation searched all the graph without breaking if target is not in G, while the new implementation will set paths[target] to [target]. It seems these issues are handled by the wrapping functions, so it should be fine.
Yes! I struggled a bit building examples where the all-targets case optimization would be noticeable. But I can keep on digging and maybe do it in a separate PR.
Maybe with this trick it becomes noticeable! This should be faster than doing the N dict lookups What I had in mind for the all-targets case was returning lazy paths so the construction is only done when needed. It changes the API a bit but we could do it in a way where most users won't notice (as long they don't depend on stuff like type(list)). This should significantly reduce memory consumption as well. class pathlist(list):
__slots__ = ('pred', 'start', '_wrapped')
def __init__(self, pred, start):
self.pred = pred
self.start = start
self._wrapped = None
super().__init__()
def _ensure_initialized(self):
pred = self.pred
if pres is not None:
path = []
current = self.start
while current is not None:
path.append(current)
current = pred.get(current)
path.reverse()
self._wrapped = path
self.pred = None
def __getitem__(self, index):
self._ensure_initialized()
return self._wrapped.__getitem__(index)
def __iter__(self):
self._ensure_initialized()
return self._wrapped.__iter__()
def __len__(self):
self._ensure_initialized()
return self._wrapped.__len__()
def __repr__(self):
self._ensure_initialized()
return self._wrapped.__repr__() |
|
Small suggestion for the sketch of the |
| reversed_target_path = [] | ||
| next_node = target | ||
| while next_node is not None: | ||
| reversed_target_path.append(next_node) | ||
| next_nodes = pred.get(next_node) | ||
| next_node = next_nodes and next_nodes[0] | ||
| paths[target] = list(reversed(reversed_target_path)) |
There was a problem hiding this comment.
If you use a deque you can appendleft and avoid having to reverse the list.
I also feel this is cleaner get logic, but you decide.
| reversed_target_path = [] | |
| next_node = target | |
| while next_node is not None: | |
| reversed_target_path.append(next_node) | |
| next_nodes = pred.get(next_node) | |
| next_node = next_nodes and next_nodes[0] | |
| paths[target] = list(reversed(reversed_target_path)) | |
| next_node = target | |
| paths[target] = deque() | |
| while next_node is not None: | |
| paths[target].appendleft(next_node) | |
| next_node = pred.get(next_node, [None])[0] | |
| paths[target] = list(paths[target]) |
There was a problem hiding this comment.
I re-wrote this. I ended up using arraylist + in-place reversal. I believe this is still clear and should be faster. Did a quick experiment with 10k elements and list+in-place reverse is something like 40% faster. That is like ~2 ms for long lists such as 10k elements, but given that this method is one of the most used algorithms, I believe it's worth it.
n = 10000
def list_append_reverse():
path = []
for i in range(n):
path.append(i)
path.reverse()
return path
def deque_appendleft():
path = deque()
for i in range(n):
path.appendleft(i)
return list(path)
list_append_reverse_time = timeit.timeit(list_append_reverse, number=1000)
deque_appendleft_time = timeit.timeit(deque_appendleft, number=1000)
list_append_reverse_time, deque_appendleft_time
rossbar
left a comment
There was a problem hiding this comment.
The high-level motivation is clear and the code changes are (IMO) relatively minor and straightforward to understand. The next step in my book would be to add some explicit benchmarks to the benchmark suite to help reproducibly probe the impact of the changes!
Added benchmark results! I need to clean-up benchmarking code a bit so I will send the benchmarks in a separate PR |
|
@dschult @rossbar do you think there’s more work needed here? I sent a follow-up PR to add benchmarks: #8059. In cases where the shortest path has few hops, the new version performs similarly to the old one, which makes sense, since Dijkstra already doesn’t need to explore much of the graph in those cases. The improvement really shines in harder cases, where Dijkstra has to explore many nodes before reaching the target. For example, in a path graph with 20,000 nodes, the new version is about 100× faster. These are the cases where the optimization has the most impact. On a side note, with this experiment I learned that random graphs (erdos renyi) tend to have shortest paths with very few hops so they are not really good for benchmarking shortest-path algos. We can do a parallelism to randomized testing for graphs. Erdos renyi graphs can be good for catching obvious issues but to push algorithms and their corner cases some graph-generation engineering can sometimes be needed. |
|
Thanks for updating the benchmarking results @amcandio ! They give me pause though: the speedups for the long paths are obvious and undisputed, but it also looks like there are real performance regressions for small, non-path-y graphs. IIUC, that would mean a significant performance hit for a user who were doing something like e.g. for G in my_giant_list_of_relatively_small_graphs_with_say_10_nodes:
nx.single_source_dijkstra(G, source=0, target=10)Is that still the case? |
Yes, with very small graphs it might be slower (nanoseconds) but it doesn't look conclusive to me. There are examples with small graphs where it is faster. Could be a measurement error at that point. In the case you mention you probably have other overheads impacting. Like creating those graphs is probably significantly slower than calling Dijkstra's. I'm okay with this tradeoff. If those extra nanoseconds per call in small graphs are really a problem, you can cache the result. (unless you are creating graphs from scratch, in which case it is not the bottleneck). Right now complexity is quadratical with respect to the shortest path length (in terms of hops). I believe having a suboptimal complexity so we can optimize for the small graphs is tuning it too much for one specific type of graph. This change makes that complexity linear, at the expense of some extra nanoseconds. Note that the PR approach not only helps with path graphs but graphs where the shortest path has many hops. The harder Dijkstra's instances are the ones where you need to visit many hops to discover the shortest path, so this change makes those faster. What do you think? The other alternative is having some specific ifs that do list copying for the first hops and then start doing predecessor reconstruction. But the code might not be as nice. |
|
I don't see changes on the scale of nanoseconds. Am I looking in the wrong place (the shortest path benchmarking PR #8059 ) It seems like some cases are ms and 30% slower. I might be able to wrap my filter around that and swallow for the impressive gains elsewhere, but I want to make sure I am understanding the information we've already got in these two PRs. |
Right, in my previous message I was mostly talking about tiny graphs. I'm seeing mixed results with bigger random graphs. Those graphs tend to have a very short (in terms of hops) shortest path (especially if we pick a big p). In that particular 33% example we can also see a big range in measurements (+-20ms) (Am I understanding this correctly?). Once I have my laptop back I can see what the shortest path looks like for this particular instance. |
|
Now that I look at the +- variability everywhere. It could be that my poor Chromebook was struggling when I ran the benchmarks |
|
@dschult so it definetely was my old Chromebook! I was running bencharking on a VM on a 2019 chromebook. Ran it with more respectable hardwarde (M1 chip) and I got: |
|
Hello everyone, I'm new to NetworkX and really appreciate these amazing implementations! I think that for the all-targets case, there might be a simpler appraoch to optimize: we can record the path for each node only when it is popped from the priority queue (fringe). At that point, the shortest distance to the node has been determined, so we only need to copy the path once per node. This avoids copying the path during every edge relaxation, and also eliminates the need to reconstruct paths at the end. In my opinion, this approach should be efficient for both dense and sparse graphs. The code could look like this: pred_dict = pred
if pred is None and paths is not None:
pred_dict = {}
G_succ = G._adj # For speed-up (and works for both directed and undirected graphs)
dist = {} # dictionary of final distances
seen = {}
# fringe is heapq with 3-tuples (distance,c,node)
# use the count c to avoid comparing nodes (may not be able to)
c = count()
fringe = []
for source in sources:
seen[source] = 0
heappush(fringe, (0, next(c), source))
while fringe:
(d, _, v) = heappop(fringe)
if v in dist:
continue # already searched this node.
dist[v] = d
if paths is not None and target is None: # need paths for all nodes
if v in sources:
paths[v] = [v] # in case the caller did not set paths[source] to source
else:
# copy only once for each node
paths[v] = paths[pred_dict[v][0]] + [v]
if v == target:
break
for u, e in G_succ[v].items():
cost = weight(v, u, e)
if cost is None:
continue
vu_dist = dist[v] + cost
if cutoff is not None:
if vu_dist > cutoff:
continue
if u in dist:
u_dist = dist[u]
if vu_dist < u_dist:
raise ValueError("Contradictory paths found:", "negative weights?")
elif pred is not None and vu_dist == u_dist:
pred[u].append(v)
elif u not in seen or vu_dist < seen[u]:
seen[u] = vu_dist
heappush(fringe, (vu_dist, next(c), u))
if paths is not None:
if target is not None:
paths[u] = paths[v] + [u]
#else No need to update paths here
if pred is not None:
pred[u] = [v]
elif pred_dict is not None:
pred_dict[u] = [v]
elif vu_dist == seen[u]:
if pred is not None:
pred[u].append(v)
# No need to reconstruct paths if target is None
The core change is just these lines: if v in sources:
paths[v] = [v] # in case the caller did not set pred[source] to source
else:
# copy only once for each node
paths[v] = paths[pred_dict[v][0]] + [v]and removes the copy at each edge relaxation. |
|
Correct! A similar idea was proposed by @fei0319 earlier in the thread. I am planning on taking that one after we ship this one (wanted to limit the scope of PR to ease reviewing). |
Thank you so much Dan! I'll address benchmarking PR's comments and then will do the followup optimization for multiple destinations. |
rossbar
left a comment
There was a problem hiding this comment.
Thanks for re-running and sharing the updated results @amcandio ! I also added some benchmarks to explicitly test the "looping over a ton of small graphs" case, which confirms there is no performance degradation.
Thanks for sticking with it through the back-and-forth over benchmarks!
|
Thank you so much! Will send the follow up optimizations later 🙂 |
Summary
Optimize Dijkstra's algorithm when a single
targetis specified by avoiding full path reconstruction for all nodes.Motivation
In the current implementation of
_dijkstra_multisource, when thepathsargument is provided, paths are computed and stored for all reachable nodes. However, if only a specifictargetnode is of interest, this can be wastefully expensive.This change avoids storing all paths when only a
targetis specified, and instead reconstructs the path to thetargetat the end using thepreddictionary, which is much cheaper to maintain.Changes
targetis requested.pred(predecessor map) to reconstruct the path totargetat the end.paths[target]frompred.Performance
This change reduces memory usage and computation time when:
targetis specified.pathsis requested.When a specific
targetnode is provided, the original implementation constructs full paths to all reachable nodes usingpaths[v] + [u]on each edge relaxation. This adds an extra cost ofO(n * L), wherenis the number of reachable nodes andLis the average path length, due to repeated list copying. By skipping full path construction during the main loop and reconstructing only the path totargetat the end , we reduce the path-building cost to justO(L). This optimization is particularly noticeable in graphs where the shortest path to thetargethas many hops (especially in the worst case whereL = n).Notes
preddictionary is now always initialized whentargetandpathsare specified (if not already provided), as it's required for final path reconstruction.No public API changes are introduced.
Results
Optimization adds the most value when the shortest paths to the target has many hops. In the case of the line graph of length 10_000, computing the source from node 0 to node 999 gets ~27x faster.
Without optimization
With optimization
Benchmarking results
Run used it
asvcommand with a custom benchmark. Benchmarking for shortest-paths is added in #8059 to not increase the scope of this one too much.Results showed that performance doesn't significantly change for most graphs in benchmark but significantly improve
s for paths with long shortest path (such as the path graph). In line graphs of 20000 nodes, new implementation is 50 times faster.