Repository navigation
Speed up the residual flow reset in edmonds_karp and simplify the minimum_cut partition - #8756
Merged
Merged
Conversation
edmonds_karp zeroes the flow attribute of every residual edge before each run. Profiled on connectivity workloads that make thousands of small-cutoff flow computations on one reused residual network, this reset outweighed the actual flow work about 5:1 -- and almost all of it was the public adjacency-view machinery, not the assignments (129M dict-view __iter__ calls in one node_connectivity computation). Iterate the internal adjacency dicts directly instead, a standard idiom in NetworkX hot paths: the reset itself gets ~3x faster (2,000 resets on a 56,402-arc residual: 21.1s to 6.9s). The reset semantics are unchanged -- every edge, every call -- so nothing else has to know: designs that cached per-edge state across runs (touched-edge tracking, a cached edge-dict tuple) were built, measured somewhat faster, and rejected because their staleness invariants leaked into every other flow function and every caller that mutates a reused residual. Caching on residual networks is also disabled by design (build_residual_network sets __networkx_cache__ to None) because flow attributes are written via direct dict access, which bypasses _clear_cache. node_connectivity on a 2,129-node kernel of a real collaboration network: 19.8s to 8.1s. Exact k_components on such networks: 1.5-1.7x end to end. The new test pins the residual-reuse semantics that made the cached designs unsound: replacing residual edges between reused runs (which rebuilds their attribute dicts without changing the edge count, and the copies retain stale flow values) must still compute correct flows.
minimum_cut derived the node partition by snapshotting all saturated edges, removing them from the residual network, running shortest_path_length towards the sink, and re-adding them to keep the residual reusable. Replace that with a reverse breadth-first search from the sink over edges with flow < capacity -- which is exactly how the residual network documentation defines the induced minimum cut. This is a simplification, not a fix: outputs are identical on every benchmark (asserted). The isolated partition step gets 36-78x faster (the old version scanned every edge and traversed the whole residual; the reverse BFS explores only the sink side of the cut), which is worth 7-9% end to end on gomory_hu_tree over sparse capacitated graphs, where n - 1 minimum_cut calls reuse one residual network. It also removes the last place in NetworkX that structurally mutates a residual network between reuses: after this, flow functions write flow attributes and nobody rebuilds edges, which keeps the residual-reuse contract simple for any future optimization work.
dschult
reviewed
Jul 11, 2026
Suggested in review: indexing the .pred adjacency view builds a wrapper per visited node, while the underlying _pred dict is a plain dict lookup. This makes the breadth-first search itself 1.7-2.7x faster on graphs where the traversal covers most nodes, and matches the raw _succ iteration already used in the edmonds_karp residual reset.
Member
Author
Thanks fot looking at this @amcandio ! |
rossbar
approved these changes
Jul 16, 2026
rossbar
left a comment
Contributor
There was a problem hiding this comment.
LGTM as well, thanks @jtorrents !
yangpeng366
added a commit
to yangpeng366/networkx
that referenced
this pull request
Oct 30, 2026
minimum_cut has documented the partition as the set of nodes reachable from
the source in the residual network, but has computed the other side instead:
the nodes that can reach the sink, and then the complement. The two agree only
when the sink side is exactly the sink-reachable set, and they disagree
whenever a minimum cut is not adjacent to the sink. On the digraph
35->36->37->39->40->41->46->47, capacities 2,2,2,2,1,1,1
the bottleneck is (40, 41), yet minimum_cut returns
(1, ({35, 36, 37, 39, 40, 41, 46}, {47}))
which is a valid minimum cut -- cutting the saturated edge (46, 47) also
costs 1 -- but reports a partition unrelated to the cut. Randomized testing
over small capacitated digraphs and graphs puts the rate at which that
trivial partition is returned at around 44%.
This is the behaviour reported in networkx#5239, open since 2021.
The sink-side formulation dates back to networkx#1102; networkx#8756 reimplemented it as a
reverse breadth-first search and left the Notes describing the search
direction as running "to t", so the code and its documentation disagreed
throughout. The cut *value* has always been correct, which is why no test
caught this: what is wrong is the partition, so callers asking which nodes or
edges form the bottleneck get an answer unrelated to it.
Search forward from the source instead, over the same flow < capacity
predicate, which is what the residual network Notes describe ("Reachability
from s ... induces a minimum s-t cut"). That needs a residual network holding
a maximum *flow*: a maximum *preflow* (value_only=True) may still leave excess
on intermediate nodes, and the spare-capacity edges leaving such a node would
report a cut that is not minimum. minimum_cut therefore lets the flow
computation run to completion. On random capacitated graphs that measured
between neutral and roughly 1.25x slower for a single minimum_cut call, and
within noise for gomory_hu_tree, which makes n-1 such calls against a reused
residual.
The five residual-network Notes that described the search direction as running
"to t" -- four in maxflow.py, one in preflow_push -- are corrected to match.
They cannot be corrected on their own: at the parent commit the code, its
inline comment and the Notes all describe the sink-side search consistently,
so the wording only becomes true once the search runs from the source.
yangpeng366
added a commit
to yangpeng366/networkx
that referenced
this pull request
Nov 10, 2026
minimum_cut has documented the partition as the set of nodes reachable from
the source in the residual network, but has computed the other side instead:
the nodes that can reach the sink, and then the complement. The two agree only
when the sink side is exactly the sink-reachable set, and they disagree
whenever a minimum cut is not adjacent to the sink. On the digraph
35->36->37->39->40->41->46->47, capacities 2,2,2,2,1,1,1
the bottleneck is (40, 41), yet minimum_cut returns
(1, ({35, 36, 37, 39, 40, 41, 46}, {47}))
which is a valid minimum cut -- cutting the saturated edge (46, 47) also
costs 1 -- but reports a partition unrelated to the cut. Randomized testing
over small capacitated digraphs and graphs puts the rate at which that
trivial partition is returned at around 44%.
This is the behaviour reported in networkx#5239, open since 2021.
The sink-side formulation dates back to networkx#1102; networkx#8756 reimplemented it as a
reverse breadth-first search and left the Notes describing the search
direction as running "to t", so the code and its documentation disagreed
throughout. The cut *value* has always been correct, which is why no test
caught this: what is wrong is the partition, so callers asking which nodes or
edges form the bottleneck get an answer unrelated to it.
Search forward from the source instead, over the same flow < capacity
predicate, which is what the residual network Notes describe ("Reachability
from s ... induces a minimum s-t cut"). That needs a residual network holding
a maximum *flow*: a maximum *preflow* (value_only=True) may still leave excess
on intermediate nodes, and the spare-capacity edges leaving such a node would
report a cut that is not minimum. minimum_cut therefore lets the flow
computation run to completion. On random capacitated graphs that measured
between neutral and roughly 1.25x slower for a single minimum_cut call, and
within noise for gomory_hu_tree, which makes n-1 such calls against a reused
residual.
The five residual-network Notes that described the search direction as running
"to t" -- four in maxflow.py, one in preflow_push -- are corrected to match.
They cannot be corrected on their own: at the parent commit the code, its
inline comment and the Notes all describe the sink-side search consistently,
so the wording only becomes true once the search runs from the source.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Two commits, both about the same hot path: workloads that run many flow computations on one reused residual network:
node_connectivity,all_node_cuts,k_components,gomory_hu_tree, the connectivity approximations. Companion to #8754, which removed a different kind of waste (building and discarding the flow dict) from the same path; the two compose.Commit 1:
edmonds_karpresidual reset via the internal adjacency dictsedmonds_karpzeroes theflowattribute of every residual edge before each run. Profiled onnode_connectivityover a 2,129-node kernel of a real collaboration network (thousands ofedmonds_karpcalls at small cutoffs on one reused residual) this reset outweighed the actual flow work about 5:1, and nearly all of it was the public adjacency-view machinery rather than the assignments: 129M dict-view__iter__calls and 141Mcoreviews.__getitem__calls in a singlenode_connectivitycomputation, against 8.1s cumulative in the flow BFS itself.The fix is to iterate the internal adjacency dicts directly instead of going through
R[u].values()view objects. Reset semantics are unchanged: every edge, every call. Micro-benchmark, 2,000 resets on the kernel's 56,402-arc residual: 21.1s -> 6.9s (3.1x).Rejected alternatives:
__networkx_cache__cannot help because residual networks deliberately disable it (build_residual_networksets it toNone; flow attributes are written via direct dict access, which bypasses_clear_cache).The boring version keeps most of the win with zero staleness surface. A new test (
test_reusing_residual_after_edge_replacement) pins the residual-reuse semantics that made the cached designs unsound, guarding any future attempt.Commit 2:
minimum_cutpartition without mutating the residual networkTo extract the node partition,
minimum_cutsnapshotted all saturated edges, removed them from the residual network, ranshortest_path_lengthtowards the sink, and re-added them "to make sure that it is reusable". This commit replaces the dance with a reverse breadth-first search from the sink over edges withflow < capacity; which is exactly how the residual-network documentation defines the induced minimum cut.This is a simplification, not a fix: outputs are identical on every benchmark. It is also faster; the old version scanned every edge and traversed the whole residual, while the reverse BFS explores only the sink side of the cut:
gnp(300, 0.05)barabasi_albert(1000, 3)grid_2d(30, 30)gnp(1000, 0.01)And it removes the last place in NetworkX that structurally mutates a residual network between reuses: after this, flow functions write flow attributes and nobody rebuilds edges, which keeps the residual-reuse contract simple.
End-to-end effect (this branch vs current main, best of 3)
gomory_hu_tree,gnp(300, 0.05)with random capacitiesgomory_hu_tree,barabasi_albert(1000, 3)with random capacitiesnode_connectivity, collaboration-network kernel (n=2,129, m=13,036)gomory_hu_treeshows the full effect of both commits (n - 1minimum_cutcalls on one reused residual, and it never built flow dicts). Thenode_connectivitygain looks muted on current main because the dominant waste there is the discarded flow dict that #8754 removes; with both PRs applied, the same kernel computation goes from 46.2s to 8.1s (5.7x). On exactk_componentsover real collaboration networks (where these kernels arise per connectivity level), the two PRs plus algorithm-level work in preparation combine to 2-3x end to end.