Skip to content

Speed up the residual flow reset in edmonds_karp and simplify the minimum_cut partition - #8756

Merged
dschult merged 3 commits into
networkx:mainfrom
jtorrents:flow-residual-reset
Jul 17, 2026
Merged

dschult merged 3 commits into
networkx:mainfrom
jtorrents:flow-residual-reset

Conversation

@jtorrents

Copy link
Copy Markdown
Member

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_karp residual reset via the internal adjacency dicts

edmonds_karp zeroes the flow attribute of every residual edge before each run. Profiled on node_connectivity over a 2,129-node kernel of a real collaboration network (thousands of edmonds_karp calls 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 141M coreviews.__getitem__ calls in a single node_connectivity computation, 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:

  • Touched-edge tracking (reset only the edges the previous run modified): fastest, but its correctness invariant had to be defended by every other flow function and every caller that mutates a reused residual: an implicit cross-module contract with silent-wrongness as the failure mode.
  • A cached flat tuple of edge dicts: broken by callers that remove and re-add residual edges (the attribute dicts are rebuilt), and __networkx_cache__ cannot help because residual networks deliberately disable it (build_residual_network sets it to None; 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_cut partition without mutating the residual network

To extract the node partition, minimum_cut snapshotted all saturated edges, removed them from the residual network, ran shortest_path_length towards 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 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. 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:

isolated partition step (per call, 200 reps) old new speedup
gnp(300, 0.05) 0.30ms 0.004ms 77x
barabasi_albert(1000, 3) 0.46ms 0.008ms 56x
grid_2d(30, 30) 0.27ms 0.008ms 35x
gnp(1000, 0.01) 0.72ms 0.009ms 79x

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)

benchmark main this PR
gomory_hu_tree, gnp(300, 0.05) with random capacities 0.476s 0.350s (1.36x)
gomory_hu_tree, barabasi_albert(1000, 3) with random capacities 1.750s 1.151s (1.52x)
node_connectivity, collaboration-network kernel (n=2,129, m=13,036) 46.19s 40.19s (1.15x)

gomory_hu_tree shows the full effect of both commits (n - 1 minimum_cut calls on one reused residual, and it never built flow dicts). The node_connectivity gain 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 exact k_components over 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.

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.

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

LGTM!

Comment thread networkx/algorithms/flow/maxflow.py Resolved
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.
@jtorrents

Copy link
Copy Markdown
Member Author

LGTM!

Thanks fot looking at this @amcandio !

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

LGTM as well, thanks @jtorrents !

@dschult
dschult merged commit f77c3b6 into networkx:main Jul 17, 2026
43 checks passed
@dschult dschult added this to the 3.7 milestone Jul 17, 2026
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.
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