forked from intel/llvm
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathgraph_impl.cpp
2356 lines (2057 loc) · 88 KB
/
graph_impl.cpp
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
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//==--------- graph_impl.cpp - SYCL graph extension -----------------------==//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#define __SYCL_GRAPH_IMPL_CPP
#include <stack>
#include <detail/graph_impl.hpp>
#include <detail/handler_impl.hpp>
#include <detail/kernel_arg_mask.hpp>
#include <detail/program_manager/program_manager.hpp>
#include <detail/queue_impl.hpp>
#include <detail/scheduler/commands.hpp>
#include <detail/sycl_mem_obj_t.hpp>
#include <sycl/detail/common.hpp>
#ifdef __INTEL_PREVIEW_BREAKING_CHANGES
#include <sycl/detail/string_view.hpp>
#endif
#include <sycl/feature_test.hpp>
#include <sycl/queue.hpp>
namespace sycl {
inline namespace _V1 {
namespace ext {
namespace oneapi {
namespace experimental {
namespace detail {
namespace {
/// Topologically sorts the graph in order to schedule nodes for execution.
/// This implementation is based on Kahn's algorithm which uses a Breadth-first
/// search approach.
/// For performance reasons, this function uses the MTotalVisitedEdges
/// member variable of the node_impl class. It's the caller responsibility to
/// make sure that MTotalVisitedEdges is set to 0 for all nodes in the graph
/// before calling this function.
/// @param[in] Roots List of root nodes.
/// @param[out] SortedNodes The graph nodes sorted in topological order.
/// @param[in] PartitionBounded If set to true, the topological sort is stopped
/// at partition borders. Hence, nodes belonging to a partition different from
/// the NodeImpl partition are not processed.
void sortTopological(std::set<std::weak_ptr<node_impl>,
std::owner_less<std::weak_ptr<node_impl>>> &Roots,
std::list<std::shared_ptr<node_impl>> &SortedNodes,
bool PartitionBounded) {
std::stack<std::weak_ptr<node_impl>> Source;
for (auto &Node : Roots) {
Source.push(Node);
}
while (!Source.empty()) {
auto Node = Source.top().lock();
Source.pop();
SortedNodes.push_back(Node);
for (auto &SuccWP : Node->MSuccessors) {
auto Succ = SuccWP.lock();
if (PartitionBounded && (Succ->MPartitionNum != Node->MPartitionNum)) {
continue;
}
auto &TotalVisitedEdges = Succ->MTotalVisitedEdges;
++TotalVisitedEdges;
if (TotalVisitedEdges == Succ->MPredecessors.size()) {
Source.push(Succ);
}
}
}
}
/// Propagates the partition number `PartitionNum` to predecessors.
/// Propagation stops when a host task is encountered or when no predecessors
/// remain or when we encounter a node that has already been processed and has a
/// partition number lower that the one propagated here. Indeed,
/// partition numbers reflect the execution order. Hence, the partition number
/// of a node can be decreased but not increased. Moreover, as predecessors of a
/// node are either in the same partition or a partition with a smaller number,
/// we do not need to continue propagating the partition number if we encounter
/// a node with a smaller partition number.
/// @param Node Node to assign to the partition.
/// @param PartitionNum Number to propagate.
void propagatePartitionUp(std::shared_ptr<node_impl> Node, int PartitionNum) {
if (((Node->MPartitionNum != -1) && (Node->MPartitionNum <= PartitionNum)) ||
(Node->MCGType == sycl::detail::CGType::CodeplayHostTask)) {
return;
}
Node->MPartitionNum = PartitionNum;
for (auto &Predecessor : Node->MPredecessors) {
propagatePartitionUp(Predecessor.lock(), PartitionNum);
}
}
/// Propagates the partition number `PartitionNum` to successors.
/// Propagation stops when an host task is encountered or when no successors
/// remain.
/// @param Node Node to assign to the partition.
/// @param PartitionNum Number to propagate.
/// @param HostTaskList List of host tasks that have already been processed and
/// are encountered as successors to the node Node.
void propagatePartitionDown(
std::shared_ptr<node_impl> Node, int PartitionNum,
std::list<std::shared_ptr<node_impl>> &HostTaskList) {
if (Node->MCGType == sycl::detail::CGType::CodeplayHostTask) {
if (Node->MPartitionNum != -1) {
HostTaskList.push_front(Node);
}
return;
}
Node->MPartitionNum = PartitionNum;
for (auto &Successor : Node->MSuccessors) {
propagatePartitionDown(Successor.lock(), PartitionNum, HostTaskList);
}
}
/// Tests if the node is a root of its partition (i.e. no predecessors that
/// belong to the same partition)
/// @param Node node to test
/// @return True is `Node` is a root of its partition
bool isPartitionRoot(std::shared_ptr<node_impl> Node) {
for (auto &Predecessor : Node->MPredecessors) {
if (Predecessor.lock()->MPartitionNum == Node->MPartitionNum) {
return false;
}
}
return true;
}
/// Takes a vector of weak_ptrs to node_impls and returns a vector of node
/// objects created from those impls, in the same order.
std::vector<node> createNodesFromImpls(
const std::vector<std::weak_ptr<detail::node_impl>> &Impls) {
std::vector<node> Nodes{};
Nodes.reserve(Impls.size());
for (std::weak_ptr<detail::node_impl> Impl : Impls) {
Nodes.push_back(sycl::detail::createSyclObjFromImpl<node>(Impl.lock()));
}
return Nodes;
}
/// Takes a vector of shared_ptrs to node_impls and returns a vector of node
/// objects created from those impls, in the same order.
std::vector<node> createNodesFromImpls(
const std::vector<std::shared_ptr<detail::node_impl>> &Impls) {
std::vector<node> Nodes{};
Nodes.reserve(Impls.size());
for (std::shared_ptr<detail::node_impl> Impl : Impls) {
Nodes.push_back(sycl::detail::createSyclObjFromImpl<node>(Impl));
}
return Nodes;
}
} // anonymous namespace
void partition::schedule() {
if (MSchedule.empty()) {
// There is no need to reset MTotalVisitedEdges before calling
// sortTopological because this function is only called once per partition.
sortTopological(MRoots, MSchedule, true);
}
}
void exec_graph_impl::makePartitions() {
int CurrentPartition = -1;
std::list<std::shared_ptr<node_impl>> HostTaskList;
// find all the host-tasks in the graph
for (auto &Node : MNodeStorage) {
if (Node->MCGType == sycl::detail::CGType::CodeplayHostTask) {
HostTaskList.push_back(Node);
}
}
MContainsHostTask = HostTaskList.size() > 0;
// Annotate nodes
// The first step in graph partitioning is to annotate all nodes of the graph
// with a temporary partition or group number. This step allows us to group
// the graph nodes into sets of nodes with kind of meta-dependencies that must
// be enforced by the runtime. For example, Group 2 depends on Groups 0 and 1,
// which means that we should not try to run Group 2 before Groups 0 and 1
// have finished executing. Since host-tasks are currently the only tasks that
// require runtime dependency handling, groups of nodes are created from
// host-task nodes. We therefore loop over all the host-task nodes, and for
// each node:
// - Its predecessors are assigned to group number `n-1`
// - The node itself constitutes a group, group number `n`
// - Its successors are assigned to group number `n+1`
// Since running multiple partitions slows down the whole graph execution, we
// then try to reduce the number of partitions by merging them when possible.
// Typically, the grouping algorithm can create two successive partitions
// of target nodes in the following case:
// A host-task `A` is added to the graph. Later, another host task `B` is
// added to the graph. Consequently, the node `A` is stored before the node
// `B` in the node storage vector. Now, if `A` is placed as a successor of `B`
// (using make_edge function to make node `A` dependent on node `B`.) In this
// case, the host-task node `A` must be reprocessed after the node `B` and the
// group that includes the predecessor of `B` can be merged with the group of
// the predecessors of the node `A`.
while (HostTaskList.size() > 0) {
auto Node = HostTaskList.front();
HostTaskList.pop_front();
CurrentPartition++;
for (auto &Predecessor : Node->MPredecessors) {
propagatePartitionUp(Predecessor.lock(), CurrentPartition);
}
CurrentPartition++;
Node->MPartitionNum = CurrentPartition;
CurrentPartition++;
auto TmpSize = HostTaskList.size();
for (auto &Successor : Node->MSuccessors) {
propagatePartitionDown(Successor.lock(), CurrentPartition, HostTaskList);
}
if (HostTaskList.size() > TmpSize) {
// At least one HostTask has been re-numbered so group merge opportunities
for (const auto &HT : HostTaskList) {
auto HTPartitionNum = HT->MPartitionNum;
if (HTPartitionNum != -1) {
// can merge predecessors of node `Node` with predecessors of node
// `HT` (HTPartitionNum-1) since HT must be reprocessed
for (const auto &NodeImpl : MNodeStorage) {
if (NodeImpl->MPartitionNum == Node->MPartitionNum - 1) {
NodeImpl->MPartitionNum = HTPartitionNum - 1;
}
}
} else {
break;
}
}
}
}
// Create partitions
int PartitionFinalNum = 0;
for (int i = -1; i <= CurrentPartition; i++) {
const std::shared_ptr<partition> &Partition = std::make_shared<partition>();
for (auto &Node : MNodeStorage) {
if (Node->MPartitionNum == i) {
MPartitionNodes[Node] = PartitionFinalNum;
if (isPartitionRoot(Node)) {
Partition->MRoots.insert(Node);
}
}
}
if (Partition->MRoots.size() > 0) {
Partition->schedule();
Partition->MIsInOrderGraph = Partition->checkIfGraphIsSinglePath();
MPartitions.push_back(Partition);
PartitionFinalNum++;
}
}
// Add an empty partition if there is no partition, i.e. empty graph
if (MPartitions.size() == 0) {
MPartitions.push_back(std::make_shared<partition>());
}
// Make global schedule list
for (const auto &Partition : MPartitions) {
MSchedule.insert(MSchedule.end(), Partition->MSchedule.begin(),
Partition->MSchedule.end());
}
// Compute partition dependencies
for (const auto &Partition : MPartitions) {
for (auto const &Root : Partition->MRoots) {
auto RootNode = Root.lock();
for (const auto &Dep : RootNode->MPredecessors) {
auto NodeDep = Dep.lock();
Partition->MPredecessors.push_back(
MPartitions[MPartitionNodes[NodeDep]]);
}
}
}
// Reset node groups (if node have to be re-processed - e.g. subgraph)
for (auto &Node : MNodeStorage) {
Node->MPartitionNum = -1;
}
}
static void checkGraphPropertiesAndThrow(const property_list &Properties) {
auto CheckDataLessProperties = [](int PropertyKind) {
#define __SYCL_DATA_LESS_PROP(NS_QUALIFIER, PROP_NAME, ENUM_VAL) \
case NS_QUALIFIER::PROP_NAME::getKind(): \
return true;
#define __SYCL_MANUALLY_DEFINED_PROP(NS_QUALIFIER, PROP_NAME)
switch (PropertyKind) {
#include <sycl/ext/oneapi/experimental/detail/properties/graph_properties.def>
default:
return false;
}
};
// No properties with data for graph now.
auto NoAllowedPropertiesCheck = [](int) { return false; };
sycl::detail::PropertyValidator::checkPropsAndThrow(
Properties, CheckDataLessProperties, NoAllowedPropertiesCheck);
}
graph_impl::graph_impl(const sycl::context &SyclContext,
const sycl::device &SyclDevice,
const sycl::property_list &PropList)
: MContext(SyclContext), MDevice(SyclDevice), MRecordingQueues(),
MEventsMap(), MInorderQueueMap(),
MID(NextAvailableID.fetch_add(1, std::memory_order_relaxed)) {
checkGraphPropertiesAndThrow(PropList);
if (PropList.has_property<property::graph::no_cycle_check>()) {
MSkipCycleChecks = true;
}
if (PropList.has_property<property::graph::assume_buffer_outlives_graph>()) {
MAllowBuffers = true;
}
if (!SyclDevice.has(aspect::ext_oneapi_limited_graph) &&
!SyclDevice.has(aspect::ext_oneapi_graph)) {
std::stringstream Stream;
Stream << SyclDevice.get_backend();
std::string BackendString = Stream.str();
throw sycl::exception(
sycl::make_error_code(errc::invalid),
BackendString + " backend is not supported by SYCL Graph extension.");
}
}
graph_impl::~graph_impl() {
try {
clearQueues();
for (auto &MemObj : MMemObjs) {
MemObj->markNoLongerBeingUsedInGraph();
}
} catch (std::exception &e) {
__SYCL_REPORT_EXCEPTION_TO_STREAM("exception in ~graph_impl", e);
}
}
std::shared_ptr<node_impl> graph_impl::addNodesToExits(
const std::list<std::shared_ptr<node_impl>> &NodeList) {
// Find all input and output nodes from the node list
std::vector<std::shared_ptr<node_impl>> Inputs;
std::vector<std::shared_ptr<node_impl>> Outputs;
for (auto &NodeImpl : NodeList) {
if (NodeImpl->MPredecessors.size() == 0) {
Inputs.push_back(NodeImpl);
}
if (NodeImpl->MSuccessors.size() == 0) {
Outputs.push_back(NodeImpl);
}
}
// Find all exit nodes in the current graph and register the Inputs as
// successors
for (auto &NodeImpl : MNodeStorage) {
if (NodeImpl->MSuccessors.size() == 0) {
for (auto &Input : Inputs) {
NodeImpl->registerSuccessor(Input);
}
}
}
// Add all the new nodes to the node storage
for (auto &Node : NodeList) {
MNodeStorage.push_back(Node);
addEventForNode(std::make_shared<sycl::detail::event_impl>(), Node);
}
return this->add(Outputs);
}
void graph_impl::addRoot(const std::shared_ptr<node_impl> &Root) {
MRoots.insert(Root);
}
void graph_impl::removeRoot(const std::shared_ptr<node_impl> &Root) {
MRoots.erase(Root);
}
std::set<std::shared_ptr<node_impl>> graph_impl::getCGEdges(
const std::shared_ptr<sycl::detail::CG> &CommandGroup) const {
const auto &Requirements = CommandGroup->getRequirements();
if (!MAllowBuffers && Requirements.size()) {
throw sycl::exception(make_error_code(errc::invalid),
"Cannot use buffers in a graph without passing the "
"assume_buffer_outlives_graph property on "
"Graph construction.");
}
if (CommandGroup->getType() == sycl::detail::CGType::Kernel) {
auto CGKernel =
static_cast<sycl::detail::CGExecKernel *>(CommandGroup.get());
if (CGKernel->hasStreams()) {
throw sycl::exception(
make_error_code(errc::invalid),
"Using sycl streams in a graph node is unsupported.");
}
}
// Add any nodes specified by event dependencies into the dependency list
std::set<std::shared_ptr<node_impl>> UniqueDeps;
for (auto &Dep : CommandGroup->getEvents()) {
if (auto NodeImpl = MEventsMap.find(Dep); NodeImpl == MEventsMap.end()) {
throw sycl::exception(sycl::make_error_code(errc::invalid),
"Event dependency from handler::depends_on does "
"not correspond to a node within the graph");
} else {
UniqueDeps.insert(NodeImpl->second);
}
}
// A unique set of dependencies obtained by checking requirements and events
for (auto &Req : Requirements) {
// Look through the graph for nodes which share this requirement
for (auto &Node : MNodeStorage) {
if (Node->hasRequirementDependency(Req)) {
bool ShouldAddDep = true;
// If any of this node's successors have this requirement then we skip
// adding the current node as a dependency.
for (auto &Succ : Node->MSuccessors) {
if (Succ.lock()->hasRequirementDependency(Req)) {
ShouldAddDep = false;
break;
}
}
if (ShouldAddDep) {
UniqueDeps.insert(Node);
}
}
}
}
return UniqueDeps;
}
void graph_impl::markCGMemObjs(
const std::shared_ptr<sycl::detail::CG> &CommandGroup) {
const auto &Requirements = CommandGroup->getRequirements();
for (auto &Req : Requirements) {
auto MemObj = static_cast<sycl::detail::SYCLMemObjT *>(Req->MSYCLMemObj);
bool WasInserted = MMemObjs.insert(MemObj).second;
if (WasInserted) {
MemObj->markBeingUsedInGraph();
}
}
}
std::shared_ptr<node_impl>
graph_impl::add(std::vector<std::shared_ptr<node_impl>> &Deps) {
const std::shared_ptr<node_impl> &NodeImpl = std::make_shared<node_impl>();
MNodeStorage.push_back(NodeImpl);
addDepsToNode(NodeImpl, Deps);
// Add an event associated with this explicit node for mixed usage
addEventForNode(std::make_shared<sycl::detail::event_impl>(), NodeImpl);
return NodeImpl;
}
std::shared_ptr<node_impl>
graph_impl::add(std::function<void(handler &)> CGF,
const std::vector<sycl::detail::ArgDesc> &Args,
std::vector<std::shared_ptr<node_impl>> &Deps) {
(void)Args;
sycl::handler Handler{shared_from_this()};
// save code location if one was set in TLS.
// idealy it would be nice to capture user's call code location
// by adding a parameter to the graph.add function, but this will
// break the API. At least capture code location from TLS, user
// can set it before calling graph.add
sycl::detail::tls_code_loc_t Tls;
Handler.saveCodeLoc(Tls.query(), Tls.isToplevel());
CGF(Handler);
if (Handler.getType() == sycl::detail::CGType::Barrier) {
throw sycl::exception(
make_error_code(errc::invalid),
"The sycl_ext_oneapi_enqueue_barrier feature is not available with "
"SYCL Graph Explicit API. Please use empty nodes instead.");
}
Handler.finalize();
node_type NodeType =
Handler.impl->MUserFacingNodeType !=
ext::oneapi::experimental::node_type::empty
? Handler.impl->MUserFacingNodeType
: ext::oneapi::experimental::detail::getNodeTypeFromCG(
Handler.getType());
auto NodeImpl =
this->add(NodeType, std::move(Handler.impl->MGraphNodeCG), Deps);
// Add an event associated with this explicit node for mixed usage
addEventForNode(std::make_shared<sycl::detail::event_impl>(), NodeImpl);
// Retrieve any dynamic parameters which have been registered in the CGF and
// register the actual nodes with them.
auto &DynamicParams = Handler.impl->MDynamicParameters;
if (NodeType != node_type::kernel && DynamicParams.size() > 0) {
throw sycl::exception(sycl::make_error_code(errc::invalid),
"dynamic_parameters cannot be registered with graph "
"nodes which do not represent kernel executions");
}
for (auto &[DynamicParam, ArgIndex] : DynamicParams) {
DynamicParam->registerNode(NodeImpl, ArgIndex);
}
return NodeImpl;
}
std::shared_ptr<node_impl>
graph_impl::add(const std::vector<sycl::detail::EventImplPtr> Events) {
std::vector<std::shared_ptr<node_impl>> Deps;
// Add any nodes specified by event dependencies into the dependency list
for (const auto &Dep : Events) {
if (auto NodeImpl = MEventsMap.find(Dep); NodeImpl != MEventsMap.end()) {
Deps.push_back(NodeImpl->second);
} else {
throw sycl::exception(sycl::make_error_code(errc::invalid),
"Event dependency from handler::depends_on does "
"not correspond to a node within the graph");
}
}
return this->add(Deps);
}
std::shared_ptr<node_impl>
graph_impl::add(node_type NodeType,
std::shared_ptr<sycl::detail::CG> CommandGroup,
std::vector<std::shared_ptr<node_impl>> &Deps) {
// A unique set of dependencies obtained by checking requirements and events
std::set<std::shared_ptr<node_impl>> UniqueDeps = getCGEdges(CommandGroup);
// Track and mark the memory objects being used by the graph.
markCGMemObjs(CommandGroup);
// Add any deps determined from requirements and events into the dependency
// list
Deps.insert(Deps.end(), UniqueDeps.begin(), UniqueDeps.end());
const std::shared_ptr<node_impl> &NodeImpl =
std::make_shared<node_impl>(NodeType, std::move(CommandGroup));
MNodeStorage.push_back(NodeImpl);
addDepsToNode(NodeImpl, Deps);
return NodeImpl;
}
std::shared_ptr<node_impl>
graph_impl::add(std::shared_ptr<dynamic_command_group_impl> &DynCGImpl,
std::vector<std::shared_ptr<detail::node_impl>> &Deps) {
// Set of Dependent nodes based on CG event and accessor dependencies.
std::set<std::shared_ptr<node_impl>> DynCGDeps =
getCGEdges(DynCGImpl->MCommandGroups[0]);
for (unsigned i = 1; i < DynCGImpl->getNumCGs(); i++) {
auto &CG = DynCGImpl->MCommandGroups[i];
auto CGEdges = getCGEdges(CG);
if (CGEdges != DynCGDeps) {
throw sycl::exception(make_error_code(sycl::errc::invalid),
"Command-groups in dynamic command-group don't have"
"equivalent dependencies to other graph nodes.");
}
}
// Track and mark the memory objects being used by the graph.
for (auto &CG : DynCGImpl->MCommandGroups) {
markCGMemObjs(CG);
}
// Get active dynamic command-group CG and use to create a node object
const auto &ActiveKernel = DynCGImpl->getActiveCG();
node_type NodeType =
ext::oneapi::experimental::detail::getNodeTypeFromCG(DynCGImpl->MCGType);
std::shared_ptr<detail::node_impl> NodeImpl =
add(NodeType, ActiveKernel, Deps);
// Add an event associated with this explicit node for mixed usage
addEventForNode(std::make_shared<sycl::detail::event_impl>(), NodeImpl);
// Track the dynamic command-group used inside the node object
DynCGImpl->MNodes.push_back(NodeImpl);
return NodeImpl;
}
bool graph_impl::clearQueues() {
bool AnyQueuesCleared = false;
for (auto &Queue : MRecordingQueues) {
if (auto ValidQueue = Queue.lock(); ValidQueue) {
ValidQueue->setCommandGraph(nullptr);
AnyQueuesCleared = true;
}
}
MRecordingQueues.clear();
return AnyQueuesCleared;
}
bool graph_impl::checkForCycles() {
std::list<std::shared_ptr<node_impl>> SortedNodes;
sortTopological(MRoots, SortedNodes, false);
// If after a topological sort, not all the nodes in the graph are sorted,
// then there must be at least one cycle in the graph. This is guaranteed
// by Kahn's algorithm, which sortTopological() implements.
bool CycleFound = SortedNodes.size() != MNodeStorage.size();
// Reset the MTotalVisitedEdges variable to prepare for the next cycle check.
for (auto &Node : MNodeStorage) {
Node->MTotalVisitedEdges = 0;
}
return CycleFound;
}
void graph_impl::makeEdge(std::shared_ptr<node_impl> Src,
std::shared_ptr<node_impl> Dest) {
throwIfGraphRecordingQueue("make_edge()");
if (Src == Dest) {
throw sycl::exception(
make_error_code(sycl::errc::invalid),
"make_edge() cannot be called when Src and Dest are the same.");
}
bool SrcFound = false;
bool DestFound = false;
for (const auto &Node : MNodeStorage) {
SrcFound |= Node == Src;
DestFound |= Node == Dest;
if (SrcFound && DestFound) {
break;
}
}
if (!SrcFound) {
throw sycl::exception(make_error_code(sycl::errc::invalid),
"Src must be a node inside the graph.");
}
if (!DestFound) {
throw sycl::exception(make_error_code(sycl::errc::invalid),
"Dest must be a node inside the graph.");
}
bool DestWasGraphRoot = Dest->MPredecessors.size() == 0;
// We need to add the edges first before checking for cycles
Src->registerSuccessor(Dest);
bool DestLostRootStatus = DestWasGraphRoot && Dest->MPredecessors.size() == 1;
if (DestLostRootStatus) {
// Dest is no longer a Root node, so we need to remove it from MRoots.
MRoots.erase(Dest);
}
// We can skip cycle checks if either Dest has no successors (cycle not
// possible) or cycle checks have been disabled with the no_cycle_check
// property;
if (Dest->MSuccessors.empty() || !MSkipCycleChecks) {
bool CycleFound = checkForCycles();
if (CycleFound) {
// Remove the added successor and predecessor.
Src->MSuccessors.pop_back();
Dest->MPredecessors.pop_back();
if (DestLostRootStatus) {
// Add Dest back into MRoots.
MRoots.insert(Dest);
}
throw sycl::exception(make_error_code(sycl::errc::invalid),
"Command graphs cannot contain cycles.");
}
}
removeRoot(Dest); // remove receiver from root node list
}
std::vector<sycl::detail::EventImplPtr> graph_impl::getExitNodesEvents(
std::weak_ptr<sycl::detail::queue_impl> RecordedQueue) {
std::vector<sycl::detail::EventImplPtr> Events;
auto RecordedQueueSP = RecordedQueue.lock();
for (auto &Node : MNodeStorage) {
if (Node->MSuccessors.empty()) {
auto EventForNode = getEventForNode(Node);
if (EventForNode->getSubmittedQueue() == RecordedQueueSP) {
Events.push_back(getEventForNode(Node));
}
}
}
return Events;
}
void graph_impl::beginRecording(
std::shared_ptr<sycl::detail::queue_impl> Queue) {
graph_impl::WriteLock Lock(MMutex);
if (!Queue->hasCommandGraph()) {
Queue->setCommandGraph(shared_from_this());
addQueue(Queue);
}
}
// Check if nodes are empty and if so loop back through predecessors until we
// find the real dependency.
void exec_graph_impl::findRealDeps(
std::vector<ur_exp_command_buffer_sync_point_t> &Deps,
std::shared_ptr<node_impl> CurrentNode, int ReferencePartitionNum) {
if (CurrentNode->isEmpty()) {
for (auto &N : CurrentNode->MPredecessors) {
auto NodeImpl = N.lock();
findRealDeps(Deps, NodeImpl, ReferencePartitionNum);
}
} else {
// Verify if CurrentNode belong the the same partition
if (MPartitionNodes[CurrentNode] == ReferencePartitionNum) {
// Verify that the sync point has actually been set for this node.
auto SyncPoint = MSyncPoints.find(CurrentNode);
assert(SyncPoint != MSyncPoints.end() &&
"No sync point has been set for node dependency.");
// Check if the dependency has already been added.
if (std::find(Deps.begin(), Deps.end(), SyncPoint->second) ==
Deps.end()) {
Deps.push_back(SyncPoint->second);
}
}
}
}
ur_exp_command_buffer_sync_point_t
exec_graph_impl::enqueueNodeDirect(sycl::context Ctx,
sycl::detail::DeviceImplPtr DeviceImpl,
ur_exp_command_buffer_handle_t CommandBuffer,
std::shared_ptr<node_impl> Node) {
std::vector<ur_exp_command_buffer_sync_point_t> Deps;
for (auto &N : Node->MPredecessors) {
findRealDeps(Deps, N.lock(), MPartitionNodes[Node]);
}
ur_exp_command_buffer_sync_point_t NewSyncPoint;
ur_exp_command_buffer_command_handle_t NewCommand = 0;
#ifdef XPTI_ENABLE_INSTRUMENTATION
int32_t StreamID = xptiRegisterStream(sycl::detail::SYCL_STREAM_NAME);
sycl::detail::CGExecKernel *CGExec =
static_cast<sycl::detail::CGExecKernel *>(Node->MCommandGroup.get());
sycl::detail::code_location CodeLoc(CGExec->MFileName.c_str(),
CGExec->MFunctionName.c_str(),
CGExec->MLine, CGExec->MColumn);
auto [CmdTraceEvent, InstanceID] = emitKernelInstrumentationData(
StreamID, CGExec->MSyclKernel, CodeLoc, CGExec->MIsTopCodeLoc,
CGExec->MKernelName.c_str(), nullptr, CGExec->MNDRDesc,
CGExec->MKernelBundle, CGExec->MArgs);
if (CmdTraceEvent)
sycl::detail::emitInstrumentationGeneral(
StreamID, InstanceID, CmdTraceEvent, xpti::trace_task_begin, nullptr);
#endif
ur_result_t Res = sycl::detail::enqueueImpCommandBufferKernel(
Ctx, DeviceImpl, CommandBuffer,
*static_cast<sycl::detail::CGExecKernel *>((Node->MCommandGroup.get())),
Deps, &NewSyncPoint, MIsUpdatable ? &NewCommand : nullptr, nullptr);
if (MIsUpdatable) {
MCommandMap[Node] = NewCommand;
}
if (Res != UR_RESULT_SUCCESS) {
throw sycl::exception(errc::invalid,
"Failed to add kernel to UR command-buffer");
}
#ifdef XPTI_ENABLE_INSTRUMENTATION
if (CmdTraceEvent)
sycl::detail::emitInstrumentationGeneral(
StreamID, InstanceID, CmdTraceEvent, xpti::trace_task_end, nullptr);
#endif
return NewSyncPoint;
}
ur_exp_command_buffer_sync_point_t exec_graph_impl::enqueueNode(
sycl::context Ctx, std::shared_ptr<sycl::detail::device_impl> DeviceImpl,
ur_exp_command_buffer_handle_t CommandBuffer,
std::shared_ptr<node_impl> Node) {
// Queue which will be used for allocation operations for accessors.
// Will also be used in native commands to return to the user in
// `interop_handler::get_native_queue()` calls.
auto AllocaQueue = std::make_shared<sycl::detail::queue_impl>(
DeviceImpl, sycl::detail::getSyclObjImpl(Ctx), sycl::async_handler{},
sycl::property_list{});
std::vector<ur_exp_command_buffer_sync_point_t> Deps;
for (auto &N : Node->MPredecessors) {
findRealDeps(Deps, N.lock(), MPartitionNodes[Node]);
}
sycl::detail::EventImplPtr Event =
sycl::detail::Scheduler::getInstance().addCG(
Node->getCGCopy(), AllocaQueue, /*EventNeeded=*/true, CommandBuffer,
Deps);
if (MIsUpdatable) {
MCommandMap[Node] = Event->getCommandBufferCommand();
}
return Event->getSyncPoint();
}
void exec_graph_impl::createCommandBuffers(
sycl::device Device, std::shared_ptr<partition> &Partition) {
ur_exp_command_buffer_handle_t OutCommandBuffer;
ur_exp_command_buffer_desc_t Desc{
UR_STRUCTURE_TYPE_EXP_COMMAND_BUFFER_DESC, nullptr, MIsUpdatable,
Partition->MIsInOrderGraph && !MEnableProfiling, MEnableProfiling};
auto ContextImpl = sycl::detail::getSyclObjImpl(MContext);
const sycl::detail::AdapterPtr &Adapter = ContextImpl->getAdapter();
auto DeviceImpl = sycl::detail::getSyclObjImpl(Device);
ur_result_t Res =
Adapter->call_nocheck<sycl::detail::UrApiKind::urCommandBufferCreateExp>(
ContextImpl->getHandleRef(), DeviceImpl->getHandleRef(), &Desc,
&OutCommandBuffer);
if (Res != UR_RESULT_SUCCESS) {
throw sycl::exception(errc::invalid, "Failed to create UR command-buffer");
}
Partition->MCommandBuffers[Device] = OutCommandBuffer;
for (const auto &Node : Partition->MSchedule) {
// Empty nodes are not processed as other nodes, but only their
// dependencies are propagated in findRealDeps
if (Node->isEmpty())
continue;
sycl::detail::CGType type = Node->MCGType;
// If the node is a kernel with no special requirements we can enqueue it
// directly.
if (type == sycl::detail::CGType::Kernel &&
Node->MCommandGroup->getRequirements().size() +
static_cast<sycl::detail::CGExecKernel *>(
Node->MCommandGroup.get())
->MStreams.size() ==
0) {
MSyncPoints[Node] =
enqueueNodeDirect(MContext, DeviceImpl, OutCommandBuffer, Node);
} else {
MSyncPoints[Node] =
enqueueNode(MContext, DeviceImpl, OutCommandBuffer, Node);
}
// Append Node requirements to overall graph requirements
MRequirements.insert(MRequirements.end(),
Node->MCommandGroup->getRequirements().begin(),
Node->MCommandGroup->getRequirements().end());
// Also store the actual accessor to make sure they are kept alive when
// commands are submitted
MAccessors.insert(MAccessors.end(),
Node->MCommandGroup->getAccStorage().begin(),
Node->MCommandGroup->getAccStorage().end());
}
Res = Adapter
->call_nocheck<sycl::detail::UrApiKind::urCommandBufferFinalizeExp>(
OutCommandBuffer);
if (Res != UR_RESULT_SUCCESS) {
throw sycl::exception(errc::invalid,
"Failed to finalize UR command-buffer");
}
}
exec_graph_impl::exec_graph_impl(sycl::context Context,
const std::shared_ptr<graph_impl> &GraphImpl,
const property_list &PropList)
: MSchedule(), MGraphImpl(GraphImpl), MSyncPoints(),
MDevice(GraphImpl->getDevice()), MContext(Context), MRequirements(),
MExecutionEvents(),
MIsUpdatable(PropList.has_property<property::graph::updatable>()),
MEnableProfiling(
PropList.has_property<property::graph::enable_profiling>()),
MID(NextAvailableID.fetch_add(1, std::memory_order_relaxed)) {
checkGraphPropertiesAndThrow(PropList);
// If the graph has been marked as updatable then check if the backend
// actually supports that. Devices supporting aspect::ext_oneapi_graph must
// have support for graph update.
if (MIsUpdatable) {
bool SupportsUpdate = MGraphImpl->getDevice().has(aspect::ext_oneapi_graph);
if (!SupportsUpdate) {
throw sycl::exception(sycl::make_error_code(errc::feature_not_supported),
"Device does not support Command Graph update");
}
}
// Copy nodes from GraphImpl and merge any subgraph nodes into this graph.
duplicateNodes();
}
exec_graph_impl::~exec_graph_impl() {
try {
const sycl::detail::AdapterPtr &Adapter =
sycl::detail::getSyclObjImpl(MContext)->getAdapter();
MSchedule.clear();
// We need to wait on all command buffer executions before we can release
// them.
for (auto &Event : MExecutionEvents) {
Event->wait(Event);
}
for (const auto &Partition : MPartitions) {
Partition->MSchedule.clear();
for (const auto &Iter : Partition->MCommandBuffers) {
if (auto CmdBuf = Iter.second; CmdBuf) {
ur_result_t Res = Adapter->call_nocheck<
sycl::detail::UrApiKind::urCommandBufferReleaseExp>(CmdBuf);
(void)Res;
assert(Res == UR_RESULT_SUCCESS);
}
}
}
} catch (std::exception &e) {
__SYCL_REPORT_EXCEPTION_TO_STREAM("exception in ~exec_graph_impl", e);
}
}
sycl::event
exec_graph_impl::enqueue(const std::shared_ptr<sycl::detail::queue_impl> &Queue,
sycl::detail::CG::StorageInitHelper CGData) {
WriteLock Lock(MMutex);
// Map of the partitions to their execution events
std::unordered_map<std::shared_ptr<partition>, sycl::detail::EventImplPtr>
PartitionsExecutionEvents;
auto CreateNewEvent([&]() {
auto NewEvent = std::make_shared<sycl::detail::event_impl>(Queue);
NewEvent->setContextImpl(Queue->getContextImplPtr());
NewEvent->setStateIncomplete();
return NewEvent;
});
sycl::detail::EventImplPtr NewEvent;
std::vector<sycl::detail::EventImplPtr> BackupCGDataMEvents;
if (MPartitions.size() > 1) {
BackupCGDataMEvents = CGData.MEvents;
}
for (uint32_t currentPartitionsNum = 0;
currentPartitionsNum < MPartitions.size(); currentPartitionsNum++) {
auto CurrentPartition = MPartitions[currentPartitionsNum];
// restore initial MEvents to add only needed additional depenencies
if (currentPartitionsNum > 0) {
CGData.MEvents = BackupCGDataMEvents;
}
for (auto const &DepPartition : CurrentPartition->MPredecessors) {
CGData.MEvents.push_back(PartitionsExecutionEvents[DepPartition]);
}
auto CommandBuffer = CurrentPartition->MCommandBuffers[Queue->get_device()];
if (CommandBuffer) {
// if previous submissions are incompleted, we automatically
// add completion events of previous submissions as dependencies.
// With Level-Zero backend we cannot resubmit a command-buffer until the
// previous one has already completed.
// Indeed, since a command-list does not accept a list a dependencies at
// submission, we circumvent this lack by adding a barrier that waits on a
// specific event and then define the conditions to signal this event in
// another command-list. Consequently, if a second submission is
// performed, the signal conditions of this single event are redefined by
// this second submission. Thus, this can lead to an undefined behaviour
// and potential hangs. We have therefore to expliclty wait in the host
// for previous submission to complete before resubmitting the
// command-buffer for level-zero backend.
// TODO : add a check to release this constraint and allow multiple
// concurrent submissions if the exec_graph has been updated since the
// last submission.
for (std::vector<sycl::detail::EventImplPtr>::iterator It =
MExecutionEvents.begin();
It != MExecutionEvents.end();) {
auto Event = *It;
if (!Event->isCompleted()) {
if (Queue->get_device().get_backend() ==
sycl::backend::ext_oneapi_level_zero) {
Event->wait(Event);
} else {
auto &AttachedEventsList = Event->getPostCompleteEvents();