-
Notifications
You must be signed in to change notification settings - Fork 769
/
Copy pathgraph_impl.hpp
1655 lines (1467 loc) · 65.1 KB
/
graph_impl.hpp
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.hpp --- 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
//
//===----------------------------------------------------------------------===//
#pragma once
#include <sycl/detail/cg_types.hpp>
#include <sycl/detail/os_util.hpp>
#include <sycl/ext/oneapi/experimental/graph.hpp>
#include <sycl/ext/oneapi/experimental/raw_kernel_arg.hpp>
#include <sycl/handler.hpp>
#include <detail/accessor_impl.hpp>
#include <detail/cg.hpp>
#include <detail/event_impl.hpp>
#include <detail/host_task.hpp>
#include <detail/kernel_impl.hpp>
#include <detail/sycl_mem_obj_t.hpp>
#include <cstring>
#include <deque>
#include <fstream>
#include <functional>
#include <iomanip>
#include <list>
#include <set>
#include <shared_mutex>
namespace sycl {
inline namespace _V1 {
namespace detail {
class SYCLMemObjT;
}
namespace ext {
namespace oneapi {
namespace experimental {
namespace detail {
inline node_type getNodeTypeFromCG(sycl::detail::CGType CGType) {
using sycl::detail::CG;
switch (CGType) {
case sycl::detail::CGType::None:
return node_type::empty;
case sycl::detail::CGType::Kernel:
return node_type::kernel;
case sycl::detail::CGType::CopyAccToPtr:
case sycl::detail::CGType::CopyPtrToAcc:
case sycl::detail::CGType::CopyAccToAcc:
case sycl::detail::CGType::CopyUSM:
return node_type::memcpy;
case sycl::detail::CGType::Memset2DUSM:
return node_type::memset;
case sycl::detail::CGType::Fill:
case sycl::detail::CGType::FillUSM:
return node_type::memfill;
case sycl::detail::CGType::PrefetchUSM:
return node_type::prefetch;
case sycl::detail::CGType::AdviseUSM:
return node_type::memadvise;
case sycl::detail::CGType::Barrier:
case sycl::detail::CGType::BarrierWaitlist:
return node_type::ext_oneapi_barrier;
case sycl::detail::CGType::CodeplayHostTask:
return node_type::host_task;
case sycl::detail::CGType::ExecCommandBuffer:
return node_type::subgraph;
case sycl::detail::CGType::EnqueueNativeCommand:
return node_type::native_command;
default:
assert(false && "Invalid Graph Node Type");
return node_type::empty;
}
}
/// Implementation of node class from SYCL_EXT_ONEAPI_GRAPH.
class node_impl : public std::enable_shared_from_this<node_impl> {
public:
using id_type = uint64_t;
/// Unique identifier for this node.
id_type MID = getNextNodeID();
/// List of successors to this node.
std::vector<std::weak_ptr<node_impl>> MSuccessors;
/// List of predecessors to this node.
///
/// Using weak_ptr here to prevent circular references between nodes.
std::vector<std::weak_ptr<node_impl>> MPredecessors;
/// Type of the command-group for the node.
sycl::detail::CGType MCGType = sycl::detail::CGType::None;
/// User facing type of the node.
node_type MNodeType = node_type::empty;
/// Command group object which stores all args etc needed to enqueue the node
std::shared_ptr<sycl::detail::CG> MCommandGroup;
/// Stores the executable graph impl associated with this node if it is a
/// subgraph node.
std::shared_ptr<exec_graph_impl> MSubGraphImpl;
/// Used for tracking visited status during cycle checks and node scheduling.
size_t MTotalVisitedEdges = 0;
/// Partition number needed to assign a Node to a a partition.
/// Note : This number is only used during the partitionning process and
/// cannot be used to find out the partion of a node outside of this process.
int MPartitionNum = -1;
/// Add successor to the node.
/// @param Node Node to add as a successor.
void registerSuccessor(const std::shared_ptr<node_impl> &Node) {
if (std::find_if(MSuccessors.begin(), MSuccessors.end(),
[Node](const std::weak_ptr<node_impl> &Ptr) {
return Ptr.lock() == Node;
}) != MSuccessors.end()) {
return;
}
MSuccessors.push_back(Node);
Node->registerPredecessor(shared_from_this());
}
/// Add predecessor to the node.
/// @param Node Node to add as a predecessor.
void registerPredecessor(const std::shared_ptr<node_impl> &Node) {
if (std::find_if(MPredecessors.begin(), MPredecessors.end(),
[&Node](const std::weak_ptr<node_impl> &Ptr) {
return Ptr.lock() == Node;
}) != MPredecessors.end()) {
return;
}
MPredecessors.push_back(Node);
}
/// Construct an empty node.
node_impl() {}
/// Construct a node representing a command-group.
/// @param NodeType Type of the command-group.
/// @param CommandGroup The CG which stores the command information for this
/// node.
node_impl(node_type NodeType,
const std::shared_ptr<sycl::detail::CG> &CommandGroup)
: MCGType(CommandGroup->getType()), MNodeType(NodeType),
MCommandGroup(CommandGroup) {
if (NodeType == node_type::subgraph) {
MSubGraphImpl =
static_cast<sycl::detail::CGExecCommandBuffer *>(MCommandGroup.get())
->MExecGraph;
}
}
/// Construct a node from another node. This will perform a deep-copy of the
/// command group object associated with this node.
node_impl(node_impl &Other)
: enable_shared_from_this(Other), MSuccessors(Other.MSuccessors),
MPredecessors(Other.MPredecessors), MCGType(Other.MCGType),
MNodeType(Other.MNodeType), MCommandGroup(Other.getCGCopy()),
MSubGraphImpl(Other.MSubGraphImpl) {}
/// Copy-assignment operator. This will perform a deep-copy of the
/// command group object associated with this node.
node_impl &operator=(node_impl &Other) {
if (this != &Other) {
MSuccessors = Other.MSuccessors;
MPredecessors = Other.MPredecessors;
MCGType = Other.MCGType;
MNodeType = Other.MNodeType;
MCommandGroup = Other.getCGCopy();
MSubGraphImpl = Other.MSubGraphImpl;
}
return *this;
}
/// Checks if this node should be a dependency of another node based on
/// accessor requirements. This is calculated using access modes if a
/// requirement to the same buffer is found inside this node.
/// @param IncomingReq Incoming requirement.
/// @return True if a dependency is needed, false if not.
bool hasRequirementDependency(sycl::detail::AccessorImplHost *IncomingReq) {
if (!MCommandGroup)
return false;
access_mode InMode = IncomingReq->MAccessMode;
switch (InMode) {
case access_mode::read:
case access_mode::read_write:
case access_mode::atomic:
break;
// These access modes don't care about existing buffer data, so we don't
// need a dependency.
case access_mode::write:
case access_mode::discard_read_write:
case access_mode::discard_write:
return false;
}
for (sycl::detail::AccessorImplHost *CurrentReq :
MCommandGroup->getRequirements()) {
if (IncomingReq->MSYCLMemObj == CurrentReq->MSYCLMemObj) {
access_mode CurrentMode = CurrentReq->MAccessMode;
// Since we have an incoming read requirement, we only care
// about requirements on this node if they are write
if (CurrentMode != access_mode::read) {
return true;
}
}
}
// No dependency necessary
return false;
}
/// Query if this is an empty node.
/// Barrier nodes are also considered empty nodes since they do not embed any
/// workload but only dependencies
/// @return True if this is an empty node, false otherwise.
bool isEmpty() const {
return ((MCGType == sycl::detail::CGType::None) ||
(MCGType == sycl::detail::CGType::Barrier));
}
/// Get a deep copy of this node's command group
/// @return A unique ptr to the new command group object.
std::unique_ptr<sycl::detail::CG> getCGCopy() const {
switch (MCGType) {
case sycl::detail::CGType::Kernel: {
auto CGCopy = createCGCopy<sycl::detail::CGExecKernel>();
rebuildArgStorage(CGCopy->MArgs, MCommandGroup->getArgsStorage(),
CGCopy->getArgsStorage());
return std::move(CGCopy);
}
case sycl::detail::CGType::CopyAccToPtr:
case sycl::detail::CGType::CopyPtrToAcc:
case sycl::detail::CGType::CopyAccToAcc:
return createCGCopy<sycl::detail::CGCopy>();
case sycl::detail::CGType::Fill:
return createCGCopy<sycl::detail::CGFill>();
case sycl::detail::CGType::UpdateHost:
return createCGCopy<sycl::detail::CGUpdateHost>();
case sycl::detail::CGType::CopyUSM:
return createCGCopy<sycl::detail::CGCopyUSM>();
case sycl::detail::CGType::FillUSM:
return createCGCopy<sycl::detail::CGFillUSM>();
case sycl::detail::CGType::PrefetchUSM:
return createCGCopy<sycl::detail::CGPrefetchUSM>();
case sycl::detail::CGType::AdviseUSM:
return createCGCopy<sycl::detail::CGAdviseUSM>();
case sycl::detail::CGType::Copy2DUSM:
return createCGCopy<sycl::detail::CGCopy2DUSM>();
case sycl::detail::CGType::Fill2DUSM:
return createCGCopy<sycl::detail::CGFill2DUSM>();
case sycl::detail::CGType::Memset2DUSM:
return createCGCopy<sycl::detail::CGMemset2DUSM>();
case sycl::detail::CGType::EnqueueNativeCommand:
case sycl::detail::CGType::CodeplayHostTask: {
// The unique_ptr to the `sycl::detail::HostTask`, which is also used for
// a EnqueueNativeCommand command, in the HostTask CG prevents from
// copying the CG. We overcome this restriction by creating a new CG with
// the same data.
auto CommandGroupPtr =
static_cast<sycl::detail::CGHostTask *>(MCommandGroup.get());
sycl::detail::HostTask HostTask = *CommandGroupPtr->MHostTask.get();
auto HostTaskSPtr = std::make_shared<sycl::detail::HostTask>(HostTask);
sycl::detail::CG::StorageInitHelper Data(
CommandGroupPtr->getArgsStorage(), CommandGroupPtr->getAccStorage(),
CommandGroupPtr->getSharedPtrStorage(),
CommandGroupPtr->getRequirements(), CommandGroupPtr->getEvents());
std::vector<sycl::detail::ArgDesc> NewArgs = CommandGroupPtr->MArgs;
rebuildArgStorage(NewArgs, CommandGroupPtr->getArgsStorage(),
Data.MArgsStorage);
sycl::detail::code_location Loc(CommandGroupPtr->MFileName.data(),
CommandGroupPtr->MFunctionName.data(),
CommandGroupPtr->MLine,
CommandGroupPtr->MColumn);
return std::make_unique<sycl::detail::CGHostTask>(
sycl::detail::CGHostTask(
std::move(HostTaskSPtr), CommandGroupPtr->MQueue,
CommandGroupPtr->MContext, std::move(NewArgs), std::move(Data),
CommandGroupPtr->getType(), Loc));
}
case sycl::detail::CGType::Barrier:
case sycl::detail::CGType::BarrierWaitlist:
// Barrier nodes are stored in the graph with only the base CG class,
// since they are treated internally as empty nodes.
return createCGCopy<sycl::detail::CG>();
case sycl::detail::CGType::CopyToDeviceGlobal:
return createCGCopy<sycl::detail::CGCopyToDeviceGlobal>();
case sycl::detail::CGType::CopyFromDeviceGlobal:
return createCGCopy<sycl::detail::CGCopyFromDeviceGlobal>();
case sycl::detail::CGType::ReadWriteHostPipe:
return createCGCopy<sycl::detail::CGReadWriteHostPipe>();
case sycl::detail::CGType::CopyImage:
return createCGCopy<sycl::detail::CGCopyImage>();
case sycl::detail::CGType::SemaphoreSignal:
return createCGCopy<sycl::detail::CGSemaphoreSignal>();
case sycl::detail::CGType::SemaphoreWait:
return createCGCopy<sycl::detail::CGSemaphoreWait>();
case sycl::detail::CGType::ProfilingTag:
return createCGCopy<sycl::detail::CGProfilingTag>();
case sycl::detail::CGType::ExecCommandBuffer:
return createCGCopy<sycl::detail::CGExecCommandBuffer>();
case sycl::detail::CGType::AsyncAlloc:
return createCGCopy<sycl::detail::CGAsyncAlloc>();
case sycl::detail::CGType::AsyncFree:
return createCGCopy<sycl::detail::CGAsyncFree>();
case sycl::detail::CGType::None:
return nullptr;
}
return nullptr;
}
/// Tests if the caller is similar to Node, this is only used for testing.
/// @param Node The node to check for similarity.
/// @param CompareContentOnly Skip comparisons related to graph structure,
/// compare only the type and command groups of the nodes
/// @return True if the two nodes are similar
bool isSimilar(const std::shared_ptr<node_impl> &Node,
bool CompareContentOnly = false) const {
if (!CompareContentOnly) {
if (MSuccessors.size() != Node->MSuccessors.size())
return false;
if (MPredecessors.size() != Node->MPredecessors.size())
return false;
}
if (MCGType != Node->MCGType)
return false;
switch (MCGType) {
case sycl::detail::CGType::Kernel: {
sycl::detail::CGExecKernel *ExecKernelA =
static_cast<sycl::detail::CGExecKernel *>(MCommandGroup.get());
sycl::detail::CGExecKernel *ExecKernelB =
static_cast<sycl::detail::CGExecKernel *>(Node->MCommandGroup.get());
return ExecKernelA->MKernelName.compare(ExecKernelB->MKernelName) == 0;
}
case sycl::detail::CGType::CopyUSM: {
sycl::detail::CGCopyUSM *CopyA =
static_cast<sycl::detail::CGCopyUSM *>(MCommandGroup.get());
sycl::detail::CGCopyUSM *CopyB =
static_cast<sycl::detail::CGCopyUSM *>(Node->MCommandGroup.get());
return (CopyA->getSrc() == CopyB->getSrc()) &&
(CopyA->getDst() == CopyB->getDst()) &&
(CopyA->getLength() == CopyB->getLength());
}
case sycl::detail::CGType::CopyAccToAcc:
case sycl::detail::CGType::CopyAccToPtr:
case sycl::detail::CGType::CopyPtrToAcc: {
sycl::detail::CGCopy *CopyA =
static_cast<sycl::detail::CGCopy *>(MCommandGroup.get());
sycl::detail::CGCopy *CopyB =
static_cast<sycl::detail::CGCopy *>(Node->MCommandGroup.get());
return (CopyA->getSrc() == CopyB->getSrc()) &&
(CopyA->getDst() == CopyB->getDst());
}
default:
assert(false && "Unexpected command group type!");
return false;
}
}
/// Recursive Depth first traversal of linked nodes.
/// to print node information and connection to Stream.
/// @param Stream Where to print node information.
/// @param Visited Vector of the already visited nodes.
/// @param Verbose If true, print additional information about the nodes such
/// as kernel args or memory access where applicable.
void printDotRecursive(std::fstream &Stream,
std::vector<node_impl *> &Visited, bool Verbose) {
// if Node has been already visited, we skip it
if (std::find(Visited.begin(), Visited.end(), this) != Visited.end())
return;
Visited.push_back(this);
printDotCG(Stream, Verbose);
for (const auto &Dep : MPredecessors) {
auto NodeDep = Dep.lock();
Stream << " \"" << NodeDep.get() << "\" -> \"" << this << "\""
<< std::endl;
}
for (std::weak_ptr<node_impl> Succ : MSuccessors) {
if (MPartitionNum == Succ.lock()->MPartitionNum)
Succ.lock()->printDotRecursive(Stream, Visited, Verbose);
}
}
/// Test if the node contains a N-D copy
/// @return true if the op is a N-D copy
bool isNDCopyNode() const {
if ((MCGType != sycl::detail::CGType::CopyAccToAcc) &&
(MCGType != sycl::detail::CGType::CopyAccToPtr) &&
(MCGType != sycl::detail::CGType::CopyPtrToAcc)) {
return false;
}
auto Copy = static_cast<sycl::detail::CGCopy *>(MCommandGroup.get());
auto ReqSrc = static_cast<sycl::detail::Requirement *>(Copy->getSrc());
auto ReqDst = static_cast<sycl::detail::Requirement *>(Copy->getDst());
return (ReqSrc->MDims > 1) || (ReqDst->MDims > 1);
}
template <int Dimensions>
void updateNDRange(nd_range<Dimensions> ExecutionRange) {
if (MCGType != sycl::detail::CGType::Kernel) {
throw sycl::exception(
sycl::errc::invalid,
"Cannot update execution range of nodes which are not kernel nodes");
}
auto &NDRDesc =
static_cast<sycl::detail::CGExecKernel *>(MCommandGroup.get())
->MNDRDesc;
if (NDRDesc.Dims != Dimensions) {
throw sycl::exception(sycl::errc::invalid,
"Cannot update execution range of a node with an "
"execution range of different dimensions than what "
"the node was originally created with.");
}
NDRDesc = sycl::detail::NDRDescT{ExecutionRange};
}
template <int Dimensions> void updateRange(range<Dimensions> ExecutionRange) {
if (MCGType != sycl::detail::CGType::Kernel) {
throw sycl::exception(
sycl::errc::invalid,
"Cannot update execution range of nodes which are not kernel nodes");
}
auto &NDRDesc =
static_cast<sycl::detail::CGExecKernel *>(MCommandGroup.get())
->MNDRDesc;
if (NDRDesc.Dims != Dimensions) {
throw sycl::exception(sycl::errc::invalid,
"Cannot update execution range of a node with an "
"execution range of different dimensions than what "
"the node was originally created with.");
}
NDRDesc = sycl::detail::NDRDescT{ExecutionRange};
}
/// Update this node with the command-group from another node.
/// @param Other The other node to update, must be of the same node type.
void updateFromOtherNode(const std::shared_ptr<node_impl> &Other) {
assert(MNodeType == Other->MNodeType);
MCommandGroup = Other->getCGCopy();
}
id_type getID() const { return MID; }
/// Returns true if this node can be updated
bool isUpdatable() const {
switch (MNodeType) {
case node_type::kernel:
case node_type::host_task:
case node_type::ext_oneapi_barrier:
case node_type::empty:
return true;
default:
return false;
}
}
private:
void rebuildArgStorage(std::vector<sycl::detail::ArgDesc> &Args,
const std::vector<std::vector<char>> &OldArgStorage,
std::vector<std::vector<char>> &NewArgStorage) const {
// Clear the arg storage so we can rebuild it
NewArgStorage.clear();
// Loop over all the args, any std_layout ones need their pointers updated
// to point to the new arg storage.
for (auto &Arg : Args) {
if (Arg.MType != sycl::detail::kernel_param_kind_t::kind_std_layout) {
continue;
}
// Find which ArgStorage Arg.MPtr is pointing to
for (auto &ArgStorage : OldArgStorage) {
if (ArgStorage.data() != Arg.MPtr) {
continue;
}
NewArgStorage.emplace_back(Arg.MSize);
// Memcpy contents from old storage to new storage
std::memcpy(NewArgStorage.back().data(), ArgStorage.data(), Arg.MSize);
// Update MPtr to point to the new storage instead of the old
Arg.MPtr = NewArgStorage.back().data();
break;
}
}
}
// Gets the next unique identifier for a node, should only be used when
// constructing nodes.
static id_type getNextNodeID() {
static id_type nextID = 0;
// Return the value then increment the next ID
return nextID++;
}
/// Prints Node information to Stream.
/// @param Stream Where to print the Node information
/// @param Verbose If true, print additional information about the nodes
/// such as kernel args or memory access where applicable.
void printDotCG(std::ostream &Stream, bool Verbose) {
Stream << "\"" << this << "\" [style=bold, label=\"";
Stream << "ID = " << this << "\\n";
Stream << "TYPE = ";
switch (MCGType) {
case sycl::detail::CGType::None:
Stream << "None \\n";
break;
case sycl::detail::CGType::Kernel: {
Stream << "CGExecKernel \\n";
sycl::detail::CGExecKernel *Kernel =
static_cast<sycl::detail::CGExecKernel *>(MCommandGroup.get());
Stream << "NAME = " << Kernel->MKernelName << "\\n";
if (Verbose) {
Stream << "ARGS = \\n";
for (size_t i = 0; i < Kernel->MArgs.size(); i++) {
auto Arg = Kernel->MArgs[i];
std::string Type = "Undefined";
if (Arg.MType == sycl::detail::kernel_param_kind_t::kind_accessor) {
Type = "Accessor";
} else if (Arg.MType ==
sycl::detail::kernel_param_kind_t::kind_std_layout) {
Type = "STD_Layout";
} else if (Arg.MType ==
sycl::detail::kernel_param_kind_t::kind_sampler) {
Type = "Sampler";
} else if (Arg.MType ==
sycl::detail::kernel_param_kind_t::kind_pointer) {
Type = "Pointer";
auto Fill = Stream.fill();
Stream << i << ") Type: " << Type << " Ptr: " << Arg.MPtr << "(0x"
<< std::hex << std::setfill('0');
for (int i = Arg.MSize - 1; i >= 0; --i) {
Stream << std::setw(2)
<< static_cast<int16_t>(
(static_cast<unsigned char *>(Arg.MPtr))[i]);
}
Stream.fill(Fill);
Stream << std::dec << ")\\n";
continue;
} else if (Arg.MType == sycl::detail::kernel_param_kind_t::
kind_specialization_constants_buffer) {
Type = "Specialization Constants Buffer";
} else if (Arg.MType ==
sycl::detail::kernel_param_kind_t::kind_stream) {
Type = "Stream";
} else if (Arg.MType ==
sycl::detail::kernel_param_kind_t::kind_invalid) {
Type = "Invalid";
}
Stream << i << ") Type: " << Type << " Ptr: " << Arg.MPtr << "\\n";
}
}
break;
}
case sycl::detail::CGType::CopyAccToPtr:
Stream << "CGCopy Device-to-Host \\n";
if (Verbose) {
sycl::detail::CGCopy *Copy =
static_cast<sycl::detail::CGCopy *>(MCommandGroup.get());
Stream << "Src: " << Copy->getSrc() << " Dst: " << Copy->getDst()
<< "\\n";
}
break;
case sycl::detail::CGType::CopyPtrToAcc:
Stream << "CGCopy Host-to-Device \\n";
if (Verbose) {
sycl::detail::CGCopy *Copy =
static_cast<sycl::detail::CGCopy *>(MCommandGroup.get());
Stream << "Src: " << Copy->getSrc() << " Dst: " << Copy->getDst()
<< "\\n";
}
break;
case sycl::detail::CGType::CopyAccToAcc:
Stream << "CGCopy Device-to-Device \\n";
if (Verbose) {
sycl::detail::CGCopy *Copy =
static_cast<sycl::detail::CGCopy *>(MCommandGroup.get());
Stream << "Src: " << Copy->getSrc() << " Dst: " << Copy->getDst()
<< "\\n";
}
break;
case sycl::detail::CGType::Fill:
Stream << "CGFill \\n";
if (Verbose) {
sycl::detail::CGFill *Fill =
static_cast<sycl::detail::CGFill *>(MCommandGroup.get());
Stream << "Ptr: " << Fill->MPtr << "\\n";
}
break;
case sycl::detail::CGType::UpdateHost:
Stream << "CGCUpdateHost \\n";
if (Verbose) {
sycl::detail::CGUpdateHost *Host =
static_cast<sycl::detail::CGUpdateHost *>(MCommandGroup.get());
Stream << "Ptr: " << Host->getReqToUpdate() << "\\n";
}
break;
case sycl::detail::CGType::CopyUSM:
Stream << "CGCopyUSM \\n";
if (Verbose) {
sycl::detail::CGCopyUSM *CopyUSM =
static_cast<sycl::detail::CGCopyUSM *>(MCommandGroup.get());
Stream << "Src: " << CopyUSM->getSrc() << " Dst: " << CopyUSM->getDst()
<< " Length: " << CopyUSM->getLength() << "\\n";
}
break;
case sycl::detail::CGType::FillUSM:
Stream << "CGFillUSM \\n";
if (Verbose) {
sycl::detail::CGFillUSM *FillUSM =
static_cast<sycl::detail::CGFillUSM *>(MCommandGroup.get());
Stream << "Dst: " << FillUSM->getDst()
<< " Length: " << FillUSM->getLength() << " Pattern: ";
for (auto byte : FillUSM->getPattern())
Stream << byte;
Stream << "\\n";
}
break;
case sycl::detail::CGType::PrefetchUSM:
Stream << "CGPrefetchUSM \\n";
if (Verbose) {
sycl::detail::CGPrefetchUSM *Prefetch =
static_cast<sycl::detail::CGPrefetchUSM *>(MCommandGroup.get());
Stream << "Dst: " << Prefetch->getDst()
<< " Length: " << Prefetch->getLength() << "\\n";
}
break;
case sycl::detail::CGType::AdviseUSM:
Stream << "CGAdviseUSM \\n";
if (Verbose) {
sycl::detail::CGAdviseUSM *AdviseUSM =
static_cast<sycl::detail::CGAdviseUSM *>(MCommandGroup.get());
Stream << "Dst: " << AdviseUSM->getDst()
<< " Length: " << AdviseUSM->getLength() << "\\n";
}
break;
case sycl::detail::CGType::CodeplayHostTask:
Stream << "CGHostTask \\n";
break;
case sycl::detail::CGType::Barrier:
Stream << "CGBarrier \\n";
break;
case sycl::detail::CGType::Copy2DUSM:
Stream << "CGCopy2DUSM \\n";
if (Verbose) {
sycl::detail::CGCopy2DUSM *Copy2DUSM =
static_cast<sycl::detail::CGCopy2DUSM *>(MCommandGroup.get());
Stream << "Src:" << Copy2DUSM->getSrc()
<< " Dst: " << Copy2DUSM->getDst() << "\\n";
}
break;
case sycl::detail::CGType::Fill2DUSM:
Stream << "CGFill2DUSM \\n";
if (Verbose) {
sycl::detail::CGFill2DUSM *Fill2DUSM =
static_cast<sycl::detail::CGFill2DUSM *>(MCommandGroup.get());
Stream << "Dst: " << Fill2DUSM->getDst() << "\\n";
}
break;
case sycl::detail::CGType::Memset2DUSM:
Stream << "CGMemset2DUSM \\n";
if (Verbose) {
sycl::detail::CGMemset2DUSM *Memset2DUSM =
static_cast<sycl::detail::CGMemset2DUSM *>(MCommandGroup.get());
Stream << "Dst: " << Memset2DUSM->getDst() << "\\n";
}
break;
case sycl::detail::CGType::ReadWriteHostPipe:
Stream << "CGReadWriteHostPipe \\n";
break;
case sycl::detail::CGType::CopyToDeviceGlobal:
Stream << "CGCopyToDeviceGlobal \\n";
if (Verbose) {
sycl::detail::CGCopyToDeviceGlobal *CopyToDeviceGlobal =
static_cast<sycl::detail::CGCopyToDeviceGlobal *>(
MCommandGroup.get());
Stream << "Src: " << CopyToDeviceGlobal->getSrc()
<< " Dst: " << CopyToDeviceGlobal->getDeviceGlobalPtr() << "\\n";
}
break;
case sycl::detail::CGType::CopyFromDeviceGlobal:
Stream << "CGCopyFromDeviceGlobal \\n";
if (Verbose) {
sycl::detail::CGCopyFromDeviceGlobal *CopyFromDeviceGlobal =
static_cast<sycl::detail::CGCopyFromDeviceGlobal *>(
MCommandGroup.get());
Stream << "Src: " << CopyFromDeviceGlobal->getDeviceGlobalPtr()
<< " Dst: " << CopyFromDeviceGlobal->getDest() << "\\n";
}
break;
case sycl::detail::CGType::ExecCommandBuffer:
Stream << "CGExecCommandBuffer \\n";
break;
case sycl::detail::CGType::EnqueueNativeCommand:
Stream << "CGNativeCommand \\n";
break;
default:
Stream << "Other \\n";
break;
}
Stream << "\"];" << std::endl;
}
/// Creates a copy of the node's CG by casting to it's actual type, then using
/// that to copy construct and create a new unique ptr from that copy.
/// @tparam CGT The derived type of the CG.
/// @return A new unique ptr to the copied CG.
template <typename CGT> std::unique_ptr<CGT> createCGCopy() const {
return std::make_unique<CGT>(*static_cast<CGT *>(MCommandGroup.get()));
}
};
class partition {
public:
/// Constructor.
partition() : MSchedule(), MCommandBuffers() {}
/// List of root nodes.
std::set<std::weak_ptr<node_impl>, std::owner_less<std::weak_ptr<node_impl>>>
MRoots;
/// Execution schedule of nodes in the graph.
std::list<std::shared_ptr<node_impl>> MSchedule;
/// Map of devices to command buffers.
std::unordered_map<sycl::device, ur_exp_command_buffer_handle_t>
MCommandBuffers;
/// List of predecessors to this partition.
std::vector<std::shared_ptr<partition>> MPredecessors;
/// True if the graph of this partition is a single path graph
/// and in-order optmization can be applied on it.
bool MIsInOrderGraph = false;
/// @return True if the partition contains a host task
bool isHostTask() const {
return (MRoots.size() && ((*MRoots.begin()).lock()->MCGType ==
sycl::detail::CGType::CodeplayHostTask));
}
/// Checks if the graph is single path, i.e. each node has a single successor.
/// @return True if the graph is a single path
bool checkIfGraphIsSinglePath() {
if (MRoots.size() > 1) {
return false;
}
for (const auto &Node : MSchedule) {
// In version 1.3.28454 of the L0 driver, 2D Copy ops cannot not
// be enqueued in an in-order cmd-list (causing execution to stall).
// The 2D Copy test should be removed from here when the bug is fixed.
if ((Node->MSuccessors.size() > 1) || (Node->isNDCopyNode())) {
return false;
}
}
return true;
}
/// Add nodes to MSchedule.
void schedule();
};
/// Implementation details of command_graph<modifiable>.
class graph_impl : public std::enable_shared_from_this<graph_impl> {
public:
using ReadLock = std::shared_lock<std::shared_mutex>;
using WriteLock = std::unique_lock<std::shared_mutex>;
/// Protects all the fields that can be changed by class' methods.
mutable std::shared_mutex MMutex;
/// Constructor.
/// @param SyclContext Context to use for graph.
/// @param SyclDevice Device to create nodes with.
/// @param PropList Optional list of properties.
graph_impl(const sycl::context &SyclContext, const sycl::device &SyclDevice,
const sycl::property_list &PropList = {});
~graph_impl();
/// Remove node from list of root nodes.
/// @param Root Node to remove from list of root nodes.
void removeRoot(const std::shared_ptr<node_impl> &Root);
/// Verifies the CG is valid to add to the graph and returns set of
/// dependent nodes if so.
/// @param CommandGroup The command group to verify and retrieve edges for.
/// @return Set of dependent nodes in the graph.
std::set<std::shared_ptr<node_impl>>
getCGEdges(const std::shared_ptr<sycl::detail::CG> &CommandGroup) const;
/// Identifies the sycl buffers used in the command-group and marks them
/// as used in the graph.
/// @param CommandGroup The command-group to check for buffer usage in.
void markCGMemObjs(const std::shared_ptr<sycl::detail::CG> &CommandGroup);
/// Create a kernel node in the graph.
/// @param NodeType User facing type of the node.
/// @param CommandGroup The CG which stores all information for this node.
/// @param Deps Dependencies of the created node.
/// @return Created node in the graph.
std::shared_ptr<node_impl> add(node_type NodeType,
std::shared_ptr<sycl::detail::CG> CommandGroup,
std::vector<std::shared_ptr<node_impl>> &Deps);
/// Create a CGF node in the graph.
/// @param CGF Command-group function to create node with.
/// @param Args Node arguments.
/// @param Deps Dependencies of the created node.
/// @return Created node in the graph.
std::shared_ptr<node_impl> add(std::function<void(handler &)> CGF,
const std::vector<sycl::detail::ArgDesc> &Args,
std::vector<std::shared_ptr<node_impl>> &Deps);
/// Create an empty node in the graph.
/// @param Deps List of predecessor nodes.
/// @return Created node in the graph.
std::shared_ptr<node_impl> add(std::vector<std::shared_ptr<node_impl>> &Deps);
/// Create an empty node in the graph.
/// @param Events List of events associated to this node.
/// @return Created node in the graph.
std::shared_ptr<node_impl>
add(const std::vector<sycl::detail::EventImplPtr> Events);
/// Create a dynamic command-group node in the graph.
/// @param DynCGImpl Dynamic command-group used to create node.
/// @param Deps List of predecessor nodes.
/// @return Created node in the graph.
std::shared_ptr<node_impl>
add(std::shared_ptr<dynamic_command_group_impl> &DynCGImpl,
std::vector<std::shared_ptr<node_impl>> &Deps);
/// Add a queue to the set of queues which are currently recording to this
/// graph.
/// @param RecordingQueue Queue to add to set.
void
addQueue(const std::shared_ptr<sycl::detail::queue_impl> &RecordingQueue) {
MRecordingQueues.insert(RecordingQueue);
}
/// Remove a queue from the set of queues which are currently recording to
/// this graph.
/// @param RecordingQueue Queue to remove from set.
void
removeQueue(const std::shared_ptr<sycl::detail::queue_impl> &RecordingQueue) {
MRecordingQueues.erase(RecordingQueue);
}
/// Remove all queues which are recording to this graph, also sets all queues
/// cleared back to the executing state.
///
/// @return True if any queues were removed.
bool clearQueues();
/// Associate a sycl event with a node in the graph.
/// @param EventImpl Event to associate with a node in map.
/// @param NodeImpl Node to associate with event in map.
void addEventForNode(std::shared_ptr<sycl::detail::event_impl> EventImpl,
std::shared_ptr<node_impl> NodeImpl) {
if (!(EventImpl->hasCommandGraph()))
EventImpl->setCommandGraph(shared_from_this());
MEventsMap[EventImpl] = NodeImpl;
}
/// Find the sycl event associated with a node.
/// @param NodeImpl Node to find event for.
/// @return Event associated with node.
std::shared_ptr<sycl::detail::event_impl>
getEventForNode(std::shared_ptr<node_impl> NodeImpl) const {
ReadLock Lock(MMutex);
if (auto EventImpl = std::find_if(
MEventsMap.begin(), MEventsMap.end(),
[NodeImpl](auto &it) { return it.second == NodeImpl; });
EventImpl != MEventsMap.end()) {
return EventImpl->first;
}
throw sycl::exception(
sycl::make_error_code(errc::invalid),
"No event has been recorded for the specified graph node");
}
/// Find the node associated with a SYCL event. Throws if no node is found for
/// the given event.
/// @param EventImpl Event to find the node for.
/// @return Node associated with the event.
std::shared_ptr<node_impl>
getNodeForEvent(std::shared_ptr<sycl::detail::event_impl> EventImpl) {
ReadLock Lock(MMutex);
if (auto NodeFound = MEventsMap.find(EventImpl);
NodeFound != std::end(MEventsMap)) {
return NodeFound->second;
}
throw sycl::exception(
sycl::make_error_code(errc::invalid),
"No node in this graph is associated with this event");
}
/// Query for the context tied to this graph.
/// @return Context associated with graph.
sycl::context getContext() const { return MContext; }
/// Query for the device_impl tied to this graph.
/// @return device_impl shared ptr reference associated with graph.
const DeviceImplPtr &getDeviceImplPtr() const {
return getSyclObjImpl(MDevice);
}
/// Query for the device tied to this graph.
/// @return Device associated with graph.
sycl::device getDevice() const { return MDevice; }
/// List of root nodes.
std::set<std::weak_ptr<node_impl>, std::owner_less<std::weak_ptr<node_impl>>>
MRoots;
/// Storage for all nodes contained within a graph. Nodes are connected to
/// each other via weak_ptrs and so do not extend each other's lifetimes.
/// This storage allows easy iteration over all nodes in the graph, rather
/// than needing an expensive depth first search.
std::vector<std::shared_ptr<node_impl>> MNodeStorage;
/// Find the last node added to this graph from an in-order queue.
/// @param Queue In-order queue to find the last node added to the graph from.
/// @return Last node in this graph added from \p Queue recording, or empty
/// shared pointer if none.
std::shared_ptr<node_impl>
getLastInorderNode(std::shared_ptr<sycl::detail::queue_impl> Queue) {
std::weak_ptr<sycl::detail::queue_impl> QueueWeakPtr(Queue);
if (0 == MInorderQueueMap.count(QueueWeakPtr)) {
return {};
}
return MInorderQueueMap[QueueWeakPtr];
}
/// Track the last node added to this graph from an in-order queue.
/// @param Queue In-order queue to register \p Node for.
/// @param Node Last node that was added to this graph from \p Queue.
void setLastInorderNode(std::shared_ptr<sycl::detail::queue_impl> Queue,
std::shared_ptr<node_impl> Node) {
std::weak_ptr<sycl::detail::queue_impl> QueueWeakPtr(Queue);
MInorderQueueMap[QueueWeakPtr] = Node;
}
/// Prints the contents of the graph to a text file in DOT format.
/// @param FilePath Path to the output file.
/// @param Verbose If true, print additional information about the nodes such
/// as kernel args or memory access where applicable.
void printGraphAsDot(const std::string FilePath, bool Verbose) const {
/// Vector of nodes visited during the graph printing
std::vector<node_impl *> VisitedNodes;
std::fstream Stream(FilePath, std::ios::out);
Stream << "digraph dot {" << std::endl;
for (std::weak_ptr<node_impl> Node : MRoots)
Node.lock()->printDotRecursive(Stream, VisitedNodes, Verbose);
Stream << "}" << std::endl;
Stream.close();
}
/// Make an edge between two nodes in the graph. Performs some mandatory
/// error checks as well as an optional check for cycles introduced by making
/// this edge.
/// @param Src The source of the new edge.
/// @param Dest The destination of the new edge.
void makeEdge(std::shared_ptr<node_impl> Src,
std::shared_ptr<node_impl> Dest);
/// Throws an invalid exception if this function is called
/// while a queue is recording commands to the graph.
/// @param ExceptionMsg Message to append to the exception message
void throwIfGraphRecordingQueue(const std::string ExceptionMsg) const {
if (MRecordingQueues.size()) {
throw sycl::exception(make_error_code(sycl::errc::invalid),
ExceptionMsg +
" cannot be called when a queue "
"is currently recording commands to a graph.");
}