File: SubgraphMatcherTest.cc

package info (click to toggle)
pytorch 1.13.1%2Bdfsg-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 139,252 kB
  • sloc: cpp: 1,100,274; python: 706,454; ansic: 83,052; asm: 7,618; java: 3,273; sh: 2,841; javascript: 612; makefile: 323; xml: 269; ruby: 185; yacc: 144; objc: 68; lex: 44
file content (646 lines) | stat: -rw-r--r-- 18,925 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
#include <algorithm>
#include <functional>

#include "test_util.h"

#include "nomnigraph/Transformations/SubgraphMatcher.h"

#include <gtest/gtest.h>

namespace nom {

namespace matcher {

using NodeType = std::string;
using Criteria = std::string;
using TestGraph = Graph<NodeType>;
using TestMatchGraph = MatchGraph<TestGraph>;
using TestMatchPredicate = MatchPredicate<TestGraph>;

// Have just one TestMatchGraph in the tests to make it less verbose to create
// the match graphs.
TestMatchGraph graph;
// Call reset before creating a new TestMatchGraph.
void reset() {
  graph = TestMatchGraph();
}

// Node matches a criteria (string) if the data string is the same as the
// criteria. Special case: "*" will match any thing.
TestMatchPredicate testMatchPredicate(const Criteria& criteria) {
  return TestMatchPredicate([criteria](TestGraph::NodeRef node) {
    return criteria == "*" || criteria == node->data();
  });
}

Criteria any() {
  return Criteria("*");
}

// Helper methods to make it less verbose to create match graphs.
TestMatchGraph::NodeRef Tree(
    const Criteria& root,
    const std::vector<TestMatchGraph::NodeRef>& children = {},
    int count = 1) {
  auto result =
      graph.createNode(std::move(testMatchPredicate(root).count(count)));
  for (auto& child : children) {
    graph.createEdge(result, child);
  }
  return result;
}

TestMatchGraph::NodeRef NonTerminal(const Criteria& root, int count = 1) {
  return graph.createNode(
      std::move(testMatchPredicate(root).count(count).nonTerminal()));
}

std::map<std::string, std::string> TestGraphNodePrinter(
    TestGraph::NodeRef node) {
  std::map<std::string, std::string> labelMap;
  labelMap["label"] = node->data();
  return labelMap;
};

// Attempts to create a realistic dataflow graph that shows a fuse procedure.
struct DataFlowTestGraph {
  const int numInputs = 4;

  TestGraph graph;

  TestGraph::NodeRef opB;
  TestGraph::NodeRef opF;
  TestGraph::NodeRef opC;
  TestGraph::NodeRef opG;
  TestGraph::NodeRef dataOut;

  // Realistic data flow test graph.
  /*


                          +---------------+
                          |               |
                          |  +---------+  |  +---------+
    +---------------------+  | input_A |  |  | input_B |
    |                        +---------+  |  +---------+
    |                          |          |    |
    |                          |          |    |
    |                          v          v    v
  +---------++---------+     +-------------------------+     +--------+
  | input_C || input_D | --> |           opC           | --> | dataC2 |
  +---------++---------+     +-------------------------+     +--------+
                               |
                               |
                               v
                             +---------+
                             |  dataC  | -+
                             +---------+  |
                               |          |
                               |          |
                               v          |
                             +---------+  |
                             |   opB   | <+
                             +---------+
                               |
                               |
                               v
                             +---------+
                             |  dataB  |
                             +---------+
                               |
                               |
                               v
                             +---------+
                             |   opF   |
                             +---------+
                               |
                               |
                               v
                             +---------+
                             |  dataF  |
                             +---------+
                               |
                               |
                               v
             +---------+     +---------+
             |  dataI  | --> |   opG   |
             +---------+     +---------+
                               |
                               |
                               v
                             +---------+
                             | dataOut |
                             +---------+
  */
  DataFlowTestGraph() {
    opC = graph.createNode("opC");

    for (int i = 0; i < numInputs; i++) {
      auto dataInput = graph.createNode("input");
      graph.createEdge(dataInput, opC);
    }

    auto dataC = graph.createNode("dataC");
    auto dataC2 = graph.createNode("dataC2");
    graph.createEdge(opC, dataC);
    graph.createEdge(opC, dataC2);

    opB = graph.createNode("opB");
    // There are 2 edges
    graph.createEdge(dataC, opB);
    graph.createEdge(dataC, opB);

    auto dataB = graph.createNode("dataB");
    graph.createEdge(opB, dataB);

    opF = graph.createNode("opF");
    graph.createEdge(dataB, opF);

    auto dataF = graph.createNode("dataF");
    graph.createEdge(opF, dataF);

    auto dataI = graph.createNode("dataI");

    opG = graph.createNode("opG");
    graph.createEdge(dataF, opG);
    graph.createEdge(dataI, opG);

    dataOut = graph.createNode("dataOut");
    graph.createEdge(opG, dataOut);

    // Use nom::converters::convertToDotString(&graph, TestGraphNodePrinter)
    // to visualize the graph.
  }
};

struct DataFlowTestGraphCriteria {
  TestMatchGraph::NodeRef matchOpCOutput;
  TestMatchGraph::NodeRef matchOpG;

  DataFlowTestGraphCriteria() {
    auto matchOpCInputs =
        graph.createNode(std::move(testMatchPredicate(Criteria("input"))
                                       .starCount()
                                       .nonTerminal()
                                       .excludeFromSubgraph()));
    auto matchOpC = graph.createNode(testMatchPredicate("opC"));
    graph.createEdge(matchOpCInputs, matchOpC);

    matchOpCOutput = graph.createNode(testMatchPredicate(any()));
    graph.createEdge(matchOpC, matchOpCOutput);

    auto matchOpB = graph.createNode(testMatchPredicate("opB"));
    graph.createEdge(matchOpCOutput, matchOpB);
    graph.createEdge(matchOpCOutput, matchOpB);

    auto matchOpBOutput = graph.createNode(testMatchPredicate(any()));
    graph.createEdge(matchOpB, matchOpBOutput);

    auto matchOpF = graph.createNode(testMatchPredicate("opF"));
    graph.createEdge(matchOpBOutput, matchOpF);

    auto matchOpFOutput = graph.createNode(testMatchPredicate(any()));
    graph.createEdge(matchOpF, matchOpFOutput);

    matchOpG = graph.createNode(testMatchPredicate("opG"));
    auto matchDataI = graph.createNode(std::move(
        testMatchPredicate(any()).nonTerminal().excludeFromSubgraph()));
    graph.createEdge(matchOpFOutput, matchOpG);
    graph.createEdge(matchDataI, matchOpG);
  }
};

TestGraph::NodeRef getInNode(TestGraph::NodeRef node, int index) {
  return node->getInEdges()[index]->tail();
}

bool isSubgraphMatch(
    TestGraph::NodeRef nodeRef,
    const TestMatchGraph::NodeRef& criteria,
    bool invertGraphTraversal = true) {
  return graph.isSubgraphMatch(nodeRef, criteria, invertGraphTraversal)
      .isMatch();
}
} // namespace matcher

} // namespace nom

using namespace nom::matcher;

// Simple test cases for node matching criteria.
TEST(SubgraphMatcher, IsNodeMatch) {
  TestGraph g;
  auto n1 = g.createNode("Hello");
  auto n2 = g.createNode("Le");
  g.createEdge(n1, n2);

  EXPECT_TRUE(graph.isNodeMatch(n1, testMatchPredicate("Hello")));
  EXPECT_FALSE(graph.isNodeMatch(n1, testMatchPredicate("G")));
  EXPECT_TRUE(graph.isNodeMatch(n2, testMatchPredicate("Le")));
  EXPECT_FALSE(graph.isNodeMatch(n2, testMatchPredicate("le")));
}

// Test subtree matching with a simple tree graph.
TEST(SubgraphMatcher, IsSubtreeMatch) {
  TestGraph graph;
  auto n1 = graph.createNode("1");
  auto n2 = graph.createNode("2");
  auto n3 = graph.createNode("3");
  auto n4 = graph.createNode("4");
  auto n5 = graph.createNode("5");
  auto n6 = graph.createNode("6");
  auto n7 = graph.createNode("7");

  graph.createEdge(n1, n2);
  graph.createEdge(n2, n3);
  graph.createEdge(n2, n4);
  graph.createEdge(n1, n5);
  graph.createEdge(n5, n6);
  graph.createEdge(n5, n7);
  /*       N1
         /     \
      N2         N5
    /    \     /    \
  N3     N4   N6   N7
  */

  reset();
  auto subtree = Tree(any(), {Tree(any()), Tree(any())});
  EXPECT_FALSE(isSubgraphMatch(n1, subtree, false));
  EXPECT_FALSE(isSubgraphMatch(n4, subtree, false));

  EXPECT_TRUE(isSubgraphMatch(n2, subtree, false));
  EXPECT_TRUE(isSubgraphMatch(n5, subtree, false));

  reset();
  subtree = Tree(Criteria("5"), {Tree(any()), Tree(any())});
  EXPECT_FALSE(isSubgraphMatch(n2, subtree, false));
  EXPECT_TRUE(isSubgraphMatch(n5, subtree, false));

  reset();
  subtree = Tree(any(), {Tree(any()), Tree(Criteria("4"))});
  EXPECT_TRUE(isSubgraphMatch(n2, subtree, false));
  EXPECT_FALSE(isSubgraphMatch(n5, subtree, false));

  reset();
  // Accepts non terminal node
  subtree = Tree(any(), {NonTerminal(any()), NonTerminal(any())});
  EXPECT_TRUE(isSubgraphMatch(n1, subtree, false));
  EXPECT_TRUE(isSubgraphMatch(n2, subtree, false));
  EXPECT_TRUE(isSubgraphMatch(n5, subtree, false));
  EXPECT_FALSE(isSubgraphMatch(n3, subtree, false));
  EXPECT_FALSE(isSubgraphMatch(n4, subtree, false));
  EXPECT_FALSE(isSubgraphMatch(n6, subtree, false));
  EXPECT_FALSE(isSubgraphMatch(n7, subtree, false));
}

// Test subtree matching in which * (repeated) matching of children is allowed.
TEST(SubgraphMatcher, IsSubtreeMatchRepeated) {
  TestGraph graph;
  auto n1 = graph.createNode("1");
  auto n2 = graph.createNode("2");
  auto n3A = graph.createNode("3");
  auto n3B = graph.createNode("3");
  auto n4 = graph.createNode("4");
  auto n5A = graph.createNode("5");
  auto n5B = graph.createNode("5");
  auto n5C = graph.createNode("5");
  graph.createEdge(n1, n2);
  graph.createEdge(n1, n3A);
  graph.createEdge(n1, n3B);
  graph.createEdge(n1, n4);
  graph.createEdge(n1, n4);
  graph.createEdge(n1, n5A);
  graph.createEdge(n1, n5B);
  graph.createEdge(n1, n5C);

  reset();
  auto subtree = Tree(any(), {Tree(Criteria("2"))});
  EXPECT_FALSE(isSubgraphMatch(n1, subtree, false));

  reset();
  subtree =
      Tree(any(), {Tree(Criteria("2"), {}, TestMatchPredicate::kStarCount)});
  EXPECT_FALSE(isSubgraphMatch(n1, subtree, false));

  reset();
  // clang-format off
  subtree = Tree(any(), {
    Tree(Criteria("2")),
    Tree(Criteria("3"), {}, 2),
    Tree(Criteria("4"), {}, 2),
    Tree(Criteria("5"), {}, 3)
  });
  EXPECT_TRUE(isSubgraphMatch(n1, subtree, false));

  reset();
  subtree = Tree(any(), {
    Tree(Criteria("2")),
    Tree(Criteria("3"), {}, 2),
    Tree(Criteria("4"), {}, 2),
    Tree(Criteria("5"), {}, 4)
  });
  // Failes because exepected 4 matches of n5 but found 3.
  EXPECT_FALSE(isSubgraphMatch(n1, subtree, false));

  reset();
  subtree = Tree(any(), {
    Tree(Criteria("2")),
    Tree(Criteria("3"), {}, 2),
    Tree(Criteria("4"), {}, 2),
    Tree(Criteria("5"), {}, TestMatchPredicate::kStarCount)
  });
  EXPECT_TRUE(isSubgraphMatch(n1, subtree, false));

  reset();
  subtree = Tree(any(), {
    Tree(Criteria("2")),
    Tree(Criteria("3"), {}, TestMatchPredicate::kStarCount),
    Tree(Criteria("4"), {}, 2),
    Tree(Criteria("5"), {}, TestMatchPredicate::kStarCount)
  });
  EXPECT_TRUE(isSubgraphMatch(n1, subtree, false));

  reset();
  subtree = Tree(any(), {
    Tree(Criteria("2")),
    Tree(Criteria("3"), {}, TestMatchPredicate::kStarCount),
  });
  // Fails because there are unmatched edges.
  EXPECT_FALSE(isSubgraphMatch(n1, subtree, false));

  reset();
  subtree = Tree(any(), {
    Tree(Criteria("2")),
    Tree(Criteria("3"), {}, 2),
    Tree(Criteria("4")),
    Tree(Criteria("5"), {}, 3)
  });
  // Fails because the count is wrong; we have 2 edges to node N4 while
  // the pattern expects only 1.
  EXPECT_FALSE(isSubgraphMatch(n1, subtree, false));
  // clang-format on
}

TEST(SubgraphMatcher, DagMatching) {
  reset();

  // clang-format off
  auto n4match = Tree(Criteria("4"), {
    Tree(Criteria("5"))
  });
  auto subgraph = Tree(Criteria("1"), {
    Tree(Criteria("2"), {
      n4match
    }),
    Tree(Criteria("3"), {
      n4match
    }),
  });
  // clang-format on

  {
    TestGraph graph;
    auto n1 = graph.createNode("1");
    auto n2 = graph.createNode("2");
    auto n3 = graph.createNode("3");
    auto n4 = graph.createNode("4");
    auto n5 = graph.createNode("5");

    graph.createEdge(n1, n2);
    graph.createEdge(n1, n3);
    graph.createEdge(n2, n4);
    graph.createEdge(n3, n4);
    graph.createEdge(n4, n5);

    /*       N1
           /     \
        N2         N3
            \   /
             N4
             |
             N5
    */

    EXPECT_TRUE(isSubgraphMatch(n1, subgraph, false));
  }

  {
    TestGraph graph;
    auto n1 = graph.createNode("1");
    auto n2 = graph.createNode("2");
    auto n3 = graph.createNode("3");
    auto n4A = graph.createNode("4");
    auto n4B = graph.createNode("4");
    auto n5 = graph.createNode("5");

    graph.createEdge(n1, n2);
    graph.createEdge(n1, n3);
    graph.createEdge(n2, n4A);
    graph.createEdge(n3, n4B);
    graph.createEdge(n4A, n5);
    graph.createEdge(n4B, n5);

    /*       N1
           /    \
        N2       N3
        /          \
       N4A        N4B
          \     /
            N5
    */

    // This should fail because n4A and n4B are not the same node.
    EXPECT_FALSE(isSubgraphMatch(n1, subgraph, false));
  }
}

TEST(SubgraphMatcher, DagMatchingMultiEdges) {
  reset();

  // clang-format off
  auto n2match = Tree(Criteria("2"));
  auto subgraph = Tree(Criteria("1"), {
    n2match,
    n2match
  });
  // clang-format on

  {
    TestGraph graph;
    auto n1 = graph.createNode("1");
    auto n2 = graph.createNode("2");

    graph.createEdge(n1, n2);
    graph.createEdge(n1, n2);

    EXPECT_TRUE(isSubgraphMatch(n1, subgraph, false));
  }

  {
    TestGraph graph;
    auto n1 = graph.createNode("1");
    auto n2A = graph.createNode("2");
    auto n2B = graph.createNode("2");

    graph.createEdge(n1, n2A);
    graph.createEdge(n1, n2B);

    EXPECT_FALSE(isSubgraphMatch(n1, subgraph, false));
  }
}

TEST(SubgraphMatcher, DagMatchingRandomLargeGraph) {
  reset();
  // clang-format off
  auto n4match = Tree(any(), {
    NonTerminal(any(), 1)
  });
  auto subtree = Tree(any(), {
    Tree(any(), {
      n4match
    }),
    Tree(any(), {
      n4match
    }),
  });
  // clang-format on
  /*       N1
         /     \
      N2         N3
          \   /
           N4
           |
           N5
  */

  // Look for the diamond pattern in a random large graph.
  TestGraph graph;
  std::vector<nom::Graph<std::string>::NodeRef> nodes;

  // Here we create a test graph and then randomly embed the above
  // pattern into the graph repeatedly (numPatterns times).
  // The actual number of match will be less than numPatterns because the
  // embedded patterns can overlap which become unmatched subgraphs.
  const int numNodes = 50000;
  const int numPatterns = 5000;

  for (int i = 0; i < numNodes; i++) {
    auto node = graph.createNode("Node");
    nodes.emplace_back(node);
  }

  TestRandom random(517);
  for (int i = 0; i < numPatterns; i++) {
    std::vector<int> nodeIdx;
    for (int k = 0; k < 5; k++) {
      // NOLINTNEXTLINE(performance-inefficient-vector-operation)
      nodeIdx.emplace_back(random.nextInt() % numNodes);
    }
    graph.createEdge(nodes[nodeIdx[0]], nodes[nodeIdx[1]]);
    graph.createEdge(nodes[nodeIdx[0]], nodes[nodeIdx[2]]);
    graph.createEdge(nodes[nodeIdx[1]], nodes[nodeIdx[3]]);
    graph.createEdge(nodes[nodeIdx[2]], nodes[nodeIdx[3]]);
    graph.createEdge(nodes[nodeIdx[3]], nodes[nodeIdx[4]]);
  }
  EXPECT_EQ(graph.getEdgesCount(), 5 * numPatterns);

  int countMatch = 0;
  for (auto node : graph.getMutableNodes()) {
    if (isSubgraphMatch(node, subtree, false)) {
      countMatch++;
    }
  }
  EXPECT_EQ(countMatch, 1072);
}

TEST(SubgraphMatcher, IsSubtreeMatchRealistic) {
  reset();
  auto graph = DataFlowTestGraph();
  auto subtree = DataFlowTestGraphCriteria().matchOpG;

  EXPECT_FALSE(isSubgraphMatch(graph.opF, subtree));
  EXPECT_FALSE(isSubgraphMatch(graph.opC, subtree));
  EXPECT_FALSE(isSubgraphMatch(graph.opB, subtree));
  EXPECT_FALSE(isSubgraphMatch(graph.dataOut, subtree));

  EXPECT_TRUE(isSubgraphMatch(graph.opG, subtree));
}

TEST(SubgraphMatcher, ReplaceGraphRealistic) {
  reset();
  auto testGraph = DataFlowTestGraph();
  auto subtree = DataFlowTestGraphCriteria();

  graph.replaceSubgraph(
      testGraph.graph,
      subtree.matchOpG,
      [subtree](
          TestGraph& g,
          TestGraph::NodeRef opG,
          const TestMatchGraph::SubgraphMatchResultType& matchResult) {
        auto fusedNode = g.createNode("opFused");
        auto opC = getInNode(
            matchResult.getMatchNodeMap()->at(subtree.matchOpCOutput), 0);
        g.replaceOutEdges(opG, fusedNode);
        g.replaceInEdges(opG, fusedNode);
        g.replaceInEdges(opC, fusedNode);
        g.deleteNodes(matchResult.getMatchedSubgraph()->getNodes());
        return true;
      });

  // Now the nodes are:
  // - NumInputs input nodes
  // - dataI node
  // - fused node
  // - output node
  // - dataC2 node
  auto nodes = testGraph.graph.getMutableNodes();

  // Test that the graph is transformed as expected.
  EXPECT_EQ(nodes.size(), testGraph.numInputs + 4);
  // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
  TestGraph::NodeRef opFused;
  // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
  TestGraph::NodeRef dataI;
  // NOLINTNEXTLINE(cppcoreguidelines-init-variables)
  TestGraph::NodeRef dataOut;
  for (auto node : nodes) {
    if (node->data() == "opFused") {
      opFused = node;
    } else if (node->data() == "dataOut") {
      dataOut = node;
    } else if (node->data() == "dataI") {
      dataI = node;
    }
  }

  EXPECT_EQ(getInNode(dataOut, 0), opFused);

  EXPECT_EQ(opFused->getInEdges().size(), testGraph.numInputs + 1);
  EXPECT_EQ(getInNode(opFused, 0), dataI);
  for (int i = 1; i <= testGraph.numInputs; i++) {
    EXPECT_EQ(getInNode(opFused, i)->data(), "input");
  }

  // Use nom::converters::convertToDotString(&graph.graph, TestGraphNodePrinter)
  // to visualize. The transformed graph looks like This
  /*

                +---------++---------+
                | input_A || input_D |
                +---------++---------+
                  |          |
                  |          |
                  v          v
+---------+     +--------------------+     +---------+
| input_B | --> |      opFused       | <-- | input_C |
+---------+     +--------------------+     +---------+
                  |          ^
                  |          |
                  v          |
                +---------++---------+
                | dataOut ||  dataI  |
                +---------++---------+
   */
}