Repository navigation
Fix transitive reduction of collective control edges - #124410
copybara-service[bot] merged 3 commits into
Conversation
CreateControlDependencies serializes concurrent CollectiveReduce ops on a
device by creating a control edge for every pair with no existing data path,
oriented from the higher instance_key to the lower one, then pruning edges that
follow from other edges. That prune is a transitive reduction, and the
transitive reduction of a finite DAG is unique, so the correct output is
determined by the input graph alone.
`all_paths` is documented at line 76 as full reachability but is not. It copies
all_paths[dst] as it stands when edge src -> dst is created, and nothing
propagates a successor acquired by dst afterwards back into src. A redundant
edge whose alternate path has length three or more is therefore invisible to
the prune.
TransitiveReductionIsExact exhibits this. Four CollectiveReduce ops on one
device, with data paths between instance keys 3 and 1 and between 4 and 2, so
the created control edges are 4 -> 3, 4 -> 1, 3 -> 2 and 2 -> 1. The path
4 -> 3 -> 2 -> 1 makes 4 -> 1 redundant, leaving {4 -> 3, 3 -> 2, 2 -> 1} as
the unique transitive reduction. The edges are created in the order
4 -> 3, 4 -> 1, 3 -> 2, 2 -> 1
so all_paths[3] is fixed at {2} before 2 acquires 1. The prune never sees
4 -> 3 -> 2 -> 1 and keeps 4 -> 1. Against the current implementation the test
reports four emitted edges where three are correct:
{("c3","c2"), ("c4","c1"), ("c4","c3"), ("c2","c1")}
The prune also removed a neighbour by overwriting its slot with nullptr and
skipped an already-nulled neighbour as a pruner, so once the closure is
incomplete the surviving set also depends on the iteration order of
absl::flat_hash_set<Node*>, which is keyed by pointer.
Every edge runs from a higher instance key to a lower one, so instance keys
strictly decrease along any path and ascending instance key is a reverse
topological order. Reachability is closed in one pass over that order, held as
a dense bit matrix over collective pairs rather than a flat_hash_set<Node*> per
node. Edge u -> v is then kept iff no other successor of u reaches v, a
predicate decided independently per edge, which removes the nulling and with it
the dependence on container iteration order.
Verified with bazel test //tensorflow/core/graph:collective_order_test, GCC
15.2.0 and Bazel 7.7.0 on Ubuntu under WSL2, CPU configuration. Against the
unpatched implementation 4 of 5 cases pass and TransitiveReductionIsExact
fails; with this change 5 of 5 pass. SimpleOrder, SimpleOrderAttr, SimpleOrder2
and Pruning pass in both runs, so no existing expectation changes.
Scratch for the reachability relation drops from one 8-byte Node* slot plus a
control byte per reachable pair at 7/8 load to one bit per pair: 20,736 B to
512 B at 64 collectives, 5,387,410 B to 131,072 B at 1,024.
Signed-off-by: teerth sharma <[email protected]>
There was a problem hiding this comment.
Code Review
This pull request optimizes the collective ordering logic by replacing the flat_hash_set-based path tracking with a dense bit matrix representation for reachability. It also ensures a correct transitive reduction of dependency edges that is independent of the iteration order of nodes, and adds a corresponding unit test. The feedback suggests optimizing the transitive reduction step by pre-retrieving neighbor indices to avoid redundant hash map lookups in the nested loop.
The redundancy test is quadratic in the number of neighbours, so looking up `collective_index` inside it made the hash lookups quadratic as well. Resolving each neighbour's index once before the test leaves O(k) lookups and O(k^2) integer comparisons. Verified with bazel test //tensorflow/core/graph:collective_order_test, GCC 15.2.0 and Bazel 7.7.0 on Ubuntu under WSL2: 5 of 5 cases pass. Signed-off-by: teerth sharma <[email protected]>
There was a problem hiding this comment.
Missing Dependency
- The file
tensorflow/core/graph/collective_order.ccnow includes#include "absl/algorithm/container.h"to useabsl::c_stable_sort. - The corresponding
BUILDfile (likelytensorflow/core/BUILDor wherever the target compiling this file is defined) is missing a dependency onabsl/algorithm(e.g.,//third_party/absl/algorithm:containeror similar depending on the environment). - Please update the BUILD dependencies to include this, otherwise it may fail to compile in environments with strict layering checks.
Performance Optimization in Transitive Reduction
- The nested loop used for identifying redundant edges iterates over all pairs of neighbors (
$O(|N|^2)$ where$|N|$ is the number of neighbors). For nodes with a very large number of neighbors, this can become a performance bottleneck (e.g., causing timeouts in large graphs). - It can be optimized to linear complexity in the number of neighbors by computing the union of all reachable nodes from all neighbors first, and then checking which neighbors are in this union.
- Here is a suggested replacement for the nested loop (lines ~183-192 in
collective_order.cc):
std::vector<uint64_t> combined_successors(words_per_row, 0);
// ... inside the loop over collectives ...
// Compute union of reaches of all neighbors.
std::fill(combined_successors.begin(), combined_successors.end(), 0);
for (const auto& [v, v_idx] : neighbors) {
const size_t v_row = static_cast<size_t>(v_idx) * words_per_row;
for (int w = 0; w < words_per_row; ++w) {
combined_successors[w] |= reaches[v_row + w];
}
}
redundant.clear();
for (const auto& [v, v_idx] : neighbors) {
if ((combined_successors[v_idx / 64] >> (v_idx % 64)) & 1) {
redundant.push_back(v);
}
}Highlights & Verification
- Correctness & Determinism: The replacement of incomplete path tracking with a dense bit-matrix reachability algorithm ensures that transitive reduction is exact and completely independent of container iteration order.
- Performance & Memory: The bit-matrix representation is significantly more memory-efficient than sets of pointers and allows for fast reachability checks.
Robust Testing
- The added regression test (
TransitiveReductionIsExact) correctly covers scenarios with alternate paths of length three or more, ensuring the specific defect is addressed and prevented from returning.
Generated Unit Test Code
Here is the code for the regression test and the graph initialization it depends on:
// Initialize the following graph, all on one device:
//
// a
// / \
// c3 c4
// | |
// id3 id4
// | |
// c1 c2
//
// Here ci denotes a collective node with `instance_key` i, and `id` is an
// identity node. The data dependencies are chosen so that exactly two of the
// six collective pairs already have a data path -- (c3, c1) and (c4, c2) --
// and the remaining four become control edges oriented from the higher
// instance key to the lower one:
//
// c4 -> c3, c4 -> c1, c3 -> c2, c2 -> c1
//
// c4 -> c1 is redundant: the path c4 -> c3 -> c2 -> c1 already orders them.
// The transitive reduction of a DAG is unique, so the only correct output is
// {c4 -> c3, c3 -> c2, c2 -> c1}.
std::unique_ptr<Graph> InitDiamondGraph() {
GraphDefBuilder builder(GraphDefBuilder::kFailImmediately);
const std::string dev0 = "/job:localhost/replica:0/task:0/device:CPU:0";
Node* a = ops::SourceOp("TestParams",
builder.opts().WithName("a").WithDevice(dev0));
Node* c3 = CollectiveReduceNode(&builder, a, "c3", dev0, 3);
Node* c4 = CollectiveReduceNode(&builder, a, "c4", dev0, 4);
Node* id3 = ops::UnaryOp(
"Identity", c3,
builder.opts().WithName("id3").WithDevice(dev0).WithAttr("T", DT_FLOAT));
Node* id4 = ops::UnaryOp(
"Identity", c4,
builder.opts().WithName("id4").WithDevice(dev0).WithAttr("T", DT_FLOAT));
CollectiveReduceNode(&builder, id3, "c1", dev0, 1);
CollectiveReduceNode(&builder, id4, "c2", dev0, 2);
std::unique_ptr<Graph> graph = std::make_unique<Graph>(OpRegistry::Global());
absl::Status s = GraphDefBuilderToGraph(builder, graph.get());
if (!s.ok()) {
LOG(FATAL) << "Error building graph " << s;
}
return graph;
}
// The emitted control edges must be the transitive reduction of the dependency
// graph. That object is unique for a DAG, so this is the only admissible
// output and it cannot depend on iteration order.
TEST(CollectiveOrderTest, TransitiveReductionIsExact) {
std::unique_ptr<Graph> graph = InitDiamondGraph();
TF_EXPECT_OK(OrderCollectives(graph.get(), GraphCollectiveOrder::kEdges));
VerifyGraph(*graph, {"c1", "c2", "c3", "c4"},
{{"c2", "c1"}, {"c3", "c2"}, {"c4", "c3"}});
}Declare `@com_google_absl//absl/algorithm:container` on `//tensorflow/core:graph`,
which compiles `collective_order.cc` through the `graph_srcs` filegroup and was
the target missing the edge for `absl::c_stable_sort`.
Replace the pairwise redundancy test with a union of the successors'
reachability rows. A successor lying in that union is reachable from another
successor, so its direct edge is implied. Every edge runs from a higher instance
key to a lower one, so the graph is acyclic and a row never contains its own
index; no self-exclusion is needed. Cost drops from O(|neighbours|^2) bit tests
to O(|neighbours| * words_per_row) word operations.
Add `<algorithm>` for `std::fill`, and `absl/status/status.h` and
`absl/strings/str_cat.h` for `absl::Status` and `absl::StrCat`, which the file
used without declaring.
Extend the test file from golden outputs to invariants:
DiamondGraphReductionIsMinimal no emitted edge is implied by the rest
ExistingGraphsAreMinimalAndAcyclic the three legacy fixtures satisfy both
IndependentCollectivesFormDescendingChain n unordered collectives yield the
n-1 chain, for n in {2,3,5,8}
DataOrderedCollectivesGetNoControlEdges collectives already ordered by data
get no control edges
SingleCollectiveEmitsNoEdges degenerate case
EmittedEdgesAreIndependentOfNodeAddresses two structurally identical graphs
at different heap addresses agree
OrderingTwiceAddsNothing idempotence
Minimality is checked by recomputing reachability in the test rather than
reusing the implementation's own relation, so a self-consistently wrong
algorithm does not satisfy it.
Verified with bazel test //tensorflow/core/graph:collective_order_test, GCC
15.2.0 and Bazel 7.7.0 on Ubuntu under WSL2, CPU configuration: 12 of 12 cases
pass. Against the pre-patch `collective_order.cc` restored from 491edf6
with the test file held constant, 10 of 12 pass and both
TransitiveReductionIsExact and DiamondGraphReductionIsMinimal fail, so the
minimality invariant reverse-validates the defect independently of the recorded
edge list. clang-format and buildifier report no findings on the four files.
Signed-off-by: teerth sharma <[email protected]>
I have addressed all raised concerns carefully, if I can help any other way or if there any other caveat blocking Merge from my end Do let me know I will fix any blockers from my end till then it LGTM |
Summary
CreateControlDependenciesintensorflow/core/graph/collective_order.ccserializes concurrentCollectiveReduceops on a device: it creates a control edge for every pair with no existing data path, oriented from the higherinstance_keyto the lower one, then prunes edges that follow from other edges. That prune is a transitive reduction, and the transitive reduction of a finite DAG is unique, so the correct output is determined by the input graph alone.all_pathsis documented at line 76 as full reachability but is not. Lines 107-111 copyall_paths[dst]as it stands when the edgesrc -> dstis created, and nothing propagates a successor acquired bydstafterwards back intosrc. A redundant edge whose alternate path has length three or more is therefore invisible to the prune, which keeps it.This change closes reachability exactly, in one pass, and decides each edge independently against the closed relation. The partition of work between
DiscoverDataDependencies,CreateControlDependenciesandInsertControlDependenciesis unchanged, as are theGraphCollectiveOrderenum, theOrderCollectivessignature, and thewait_forattribute encoding.The defect
Four
CollectiveReduceops on one device, with data paths between instance keys 3 and 1 and between 4 and 2. The created control edges are4 -> 3,4 -> 1,3 -> 2,2 -> 1. The path4 -> 3 -> 2 -> 1makes4 -> 1redundant, so the unique transitive reduction is{4 -> 3, 3 -> 2, 2 -> 1}.The edges are created in this order, recovered from the existing
VLOG(1)at line 103:all_paths[3]is fixed at{2}when3 -> 2is created, which precedes2 -> 1. Key 1 is never back-propagated into it. The prune never sees4 -> 3 -> 2 -> 1and retains4 -> 1, emitting four edges where three are correct:The extra edge over-serializes the collectives:
c1waits onc4directly in addition to the chain that already orders them.A length-two alternate path cannot trigger this, because
all_paths[v]always receiveswat the momentv -> wis created. The failure requires a pathu -> v -> x -> win which the pair(v, x)reaches the enumeration before(x, w), which is why it survived the existing coverage.Iteration-order dependence
The prune at lines 127-139 removed a neighbour by overwriting its slot with
nullptrand skipped an already-nulled neighbour as a pruner (if (n1 == nullptr) continue;). Once the closure is incomplete, which neighbours are nulled first selects the surviving set, and that order is the iteration order ofabsl::flat_hash_set<Node*>, keyed by pointer. Deciding each edge independently against a complete closure removes the nulling and with it the dependence on container iteration order.Correctness of the replacement
Every edge runs from a higher instance key to a lower one, so instance keys strictly decrease along any path and ascending instance key is a reverse topological order. Closing reachability in that order requires a single pass, after which edge
u -> vbelongs to the reduction iff no other successor ofureachesv.Reachability is held as a dense bit matrix over collective pairs rather than a
flat_hash_set<Node*>per node.Validation
bazel test //tensorflow/core/graph:collective_order_test, GCC 15.2.0 and Bazel 7.7.0 on Ubuntu under WSL2, CPU configuration, from491edf64e28.collective_order.ccTransitiveReductionIsExactfails with 4 emitted edges against 3 expectedSimpleOrder,SimpleOrderAttr,SimpleOrder2andPruningpass in both runs, so no existing expectation changes. The added test was confirmed to fail against the unpatched implementation before the fix was applied, with the pre-patchcollective_order.ccrestored from the parent commit and the test file held constant.Scratch
Per reachable pair,
absl::flat_hash_set<Node*>costs an 8-byte slot plus a control byte at a 7/8 maximum load factor; a bit matrix costs one bit.Limits
No wall-clock measurement is attached; the change is submitted as a correctness and determinism fix, not a performance one. The scratch figures are computed from the container's documented layout rather than from a heap profile. Validation ran on a single CPU configuration under WSL2, not on GPU or multi-host, and the collective ordering path itself is exercised here through
OrderCollectivesunit coverage rather than a distributed end-to-end run.Relates to #124405.