Skip to content

Fix transitive reduction of collective control edges - #124410

Merged
copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
teerthsharma:fix/collective-order-transitive-reduction
Aug 5, 2026
Merged

copybara-service[bot] merged 3 commits into
tensorflow:masterfrom
teerthsharma:fix/collective-order-transitive-reduction

Conversation

@teerthsharma

Copy link
Copy Markdown
Contributor

Summary

CreateControlDependencies in tensorflow/core/graph/collective_order.cc serializes concurrent CollectiveReduce ops on a device: it creates a control edge for every pair with no existing data path, oriented from the higher instance_key to 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_paths is documented at line 76 as full reachability but is not. Lines 107-111 copy all_paths[dst] as it stands when the 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, 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, CreateControlDependencies and InsertControlDependencies is unchanged, as are the GraphCollectiveOrder enum, the OrderCollectives signature, and the wait_for attribute encoding.

The defect

Four CollectiveReduce ops on one device, with data paths between instance keys 3 and 1 and between 4 and 2. The created control edges are 4 -> 3, 4 -> 1, 3 -> 2, 2 -> 1. The path 4 -> 3 -> 2 -> 1 makes 4 -> 1 redundant, 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:

4 -> 3
4 -> 1
3 -> 2
2 -> 1

all_paths[3] is fixed at {2} when 3 -> 2 is created, which precedes 2 -> 1. Key 1 is never back-propagated into it. The prune never sees 4 -> 3 -> 2 -> 1 and retains 4 -> 1, emitting four edges where three are correct:

{("c3","c2"), ("c4","c1"), ("c4","c3"), ("c2","c1")}

The extra edge over-serializes the collectives: c1 waits on c4 directly in addition to the chain that already orders them.

A length-two alternate path cannot trigger this, because all_paths[v] always receives w at the moment v -> w is created. The failure requires a path u -> v -> x -> w in 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 nullptr and 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 of absl::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 -> v belongs to the reduction iff no other successor of u reaches v.

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, from 491edf64e28.

run collective_order.cc result
before current 4 of 5 pass; TransitiveReductionIsExact fails with 4 emitted edges against 3 expected
after this change 5 of 5 pass

SimpleOrder, SimpleOrderAttr, SimpleOrder2 and Pruning pass 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-patch collective_order.cc restored 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.

collectives reachable pairs before after
64 2,016 20,736 B 512 B
256 32,640 335,725 B 8,192 B
1,024 523,776 5,387,410 B 131,072 B

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 OrderCollectives unit coverage rather than a distributed end-to-end run.

Relates to #124405.

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]>

@gemini-code-assist gemini-code-assist Bot 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.

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]>
@nithyak0204
nithyak0204 requested a review from a team July 31, 2026 05:32
@google-ml-butler google-ml-butler Bot added the awaiting review Pull request awaiting review label Jul 31, 2026
@nithyak0204 nithyak0204 added the comp:core issues related to core part of tensorflow label Jul 31, 2026
@github-project-automation github-project-automation Bot moved this to Assigned Reviewer in PR Queue Jul 31, 2026

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

Missing Dependency

  • The file tensorflow/core/graph/collective_order.cc now includes #include "absl/algorithm/container.h" to use absl::c_stable_sort.
  • The corresponding BUILD file (likely tensorflow/core/BUILD or wherever the target compiling this file is defined) is missing a dependency on absl/algorithm (e.g., //third_party/absl/algorithm:container or 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"}});
}

@github-project-automation github-project-automation Bot moved this from Assigned Reviewer to Reviewer Requested Changes in PR Queue Aug 2, 2026
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]>
@teerthsharma
teerthsharma requested a review from dmiltr3 August 2, 2026 18:20
@teerthsharma

teerthsharma commented Aug 3, 2026 •

Copy link
Copy Markdown
Contributor Author

Missing Dependency

  • The file tensorflow/core/graph/collective_order.cc now includes #include "absl/algorithm/container.h" to use absl::c_stable_sort.

  • The corresponding BUILD file (likely tensorflow/core/BUILD or wherever the target compiling this file is defined) is missing a dependency on absl/algorithm (e.g., //third_party/absl/algorithm:container or 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"}});

}

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

@google-ml-butler google-ml-butler Bot added kokoro:force-run Tests on submitted change ready to pull PR ready for merge process labels Aug 3, 2026
@github-project-automation github-project-automation Bot moved this from Reviewer Requested Changes to Approved by Reviewer in PR Queue Aug 3, 2026
@kokoro-team kokoro-team removed the kokoro:force-run Tests on submitted change label Aug 3, 2026
@nithyak0204 nithyak0204 removed the awaiting review Pull request awaiting review label Aug 4, 2026
@copybara-service
copybara-service Bot merged commit dadfe69 into tensorflow:master Aug 5, 2026
17 checks passed
@github-project-automation github-project-automation Bot moved this from Approved by Reviewer to Merged in PR Queue Aug 5, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp:core issues related to core part of tensorflow ready to pull PR ready for merge process size:M CL Change Size: Medium

Projects

Status: Merged

Development

Successfully merging this pull request may close these issues.

5 participants