-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDirectMLX.h
4595 lines (3794 loc) · 193 KB
/
DirectMLX.h
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
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
// clang-format off
#pragma once
#include "DirectML.h"
#include <cstdint>
#include <cassert>
#include <vector>
#include <array>
#include <deque>
#include <memory>
#include <utility>
#include <type_traits>
#include <functional>
#include <stack>
#include <wrl/client.h> // For Microsoft::WRL::ComPtr
#if DMLX_USE_ABSEIL
#if __cpp_lib_span
#include <span>
#endif
#elif __cplusplus >= 201703L && __has_include(<optional>)
// stl optional is only available in cpp17 and above.
#include <optional>
#elif __has_include("dml_optional_extensions.h")
#include "dml_optional_extensions.h"
#define DMLX_OPTIONAL_EXTENDED
#endif
#if __cpp_exceptions
#include <stdexcept>
#endif
#if __cplusplus >= 201703L && __has_include(<string_view>)
#include <string_view>
#endif
/** Calculates the minimum number of bytes required to store a buffer tensor with the specified type, sizes, and
strides. The formula can be expressed as the following:
IndexOfLastElement = dot(Sizes - 1, Strides);
MinimumImpliedSizeInBytes = roundup((IndexOfLastElement + 1) * ElementSizeInBytes, 4)
In other words, the minimum size of a tensor is the index of the one-past-the-end element, multiplied by the
element size (e.g. 2 bytes for a FLOAT16 tensor). Additionally DirectML requires that all buffers bound must have
a total size which is DWORD-aligned, and hence the minimum implied size in bytes must be rounded up to the nearest
4-byte boundary.
*/
inline UINT64 DMLCalcBufferTensorSize(
DML_TENSOR_DATA_TYPE dataType,
UINT dimensionCount,
_In_reads_(dimensionCount) const UINT* sizes,
_In_reads_opt_(dimensionCount) const UINT* strides)
{
UINT elementSizeInBits = 0;
switch (dataType)
{
case DML_TENSOR_DATA_TYPE_FLOAT32:
case DML_TENSOR_DATA_TYPE_UINT32:
case DML_TENSOR_DATA_TYPE_INT32:
elementSizeInBits = 32;
break;
case DML_TENSOR_DATA_TYPE_FLOAT16:
case DML_TENSOR_DATA_TYPE_UINT16:
case DML_TENSOR_DATA_TYPE_INT16:
elementSizeInBits = 16;
break;
case DML_TENSOR_DATA_TYPE_UINT8:
case DML_TENSOR_DATA_TYPE_INT8:
elementSizeInBits = 8;
break;
#if DML_TARGET_VERSION >= 0x6300
case DML_TENSOR_DATA_TYPE_UINT4:
case DML_TENSOR_DATA_TYPE_INT4:
elementSizeInBits = 4;
break;
#endif
case DML_TENSOR_DATA_TYPE_FLOAT64:
case DML_TENSOR_DATA_TYPE_UINT64:
case DML_TENSOR_DATA_TYPE_INT64:
elementSizeInBits = 64;
break;
default:
return 0; // Invalid data type
}
UINT64 minimumImpliedSizeInBits = 0;
if (!strides)
{
minimumImpliedSizeInBits = sizes[0];
for (UINT i = 1; i < dimensionCount; ++i)
{
minimumImpliedSizeInBits *= sizes[i];
}
minimumImpliedSizeInBits *= elementSizeInBits;
}
else
{
UINT indexOfLastElement = 0;
for (UINT i = 0; i < dimensionCount; ++i)
{
indexOfLastElement += (sizes[i] - 1) * strides[i];
}
minimumImpliedSizeInBits = (static_cast<UINT64>(indexOfLastElement) + 1) * elementSizeInBits;
}
UINT64 minimumImpliedSizeInBytes = (minimumImpliedSizeInBits + 7) / 8;
// Round up to the nearest 4 bytes.
minimumImpliedSizeInBytes = (minimumImpliedSizeInBytes + 3) & ~3ull;
return minimumImpliedSizeInBytes;
}
namespace dml
{
namespace detail
{
// Provide non-member size() and data(). Defaults to standard library implementation (if available)
#if __cpp_lib_nonmember_container_access
template <typename C>
constexpr auto size(const C& c) -> decltype(c.size())
{
return std::size(c);
}
template <typename T, std::size_t N>
constexpr std::size_t size(const T(&array)[N]) noexcept
{
return std::size(array);
}
template <typename C>
constexpr auto data(C& c) -> decltype(c.data())
{
return std::data(c);
}
template <typename T, std::size_t N>
constexpr T* data(T(&array)[N]) noexcept
{
return std::data(array);
}
#else
template <typename C>
constexpr auto size(const C& c) -> decltype(c.size())
{
return c.size();
}
template <typename T, std::size_t N>
constexpr std::size_t size(const T(&array)[N]) noexcept
{
return N;
}
template <typename C>
constexpr auto data(C& c) -> decltype(c.data())
{
return c.data();
}
template <typename T, std::size_t N>
constexpr T* data(T(&array)[N]) noexcept
{
return array;
}
#endif
template <typename T>
class span
{
public:
span() = default;
constexpr span(std::initializer_list<T> i) : m_begin(i.begin()), m_end(i.end()) {}
constexpr span(T* begin, T* end) : m_begin(begin), m_end(end) {}
constexpr span(T* begin, size_t elementCount) : m_begin(begin), m_end(begin + elementCount) {}
template <typename ContiguousContainer>
constexpr span(ContiguousContainer&& container)
: m_begin(dml::detail::data(container)), m_end(m_begin + dml::detail::size(container)) {}
template <size_t N>
constexpr span(T(&a)[N]) noexcept : span(a, N) {}
T* data() noexcept { return m_begin; }
T* begin() noexcept { return m_begin; }
T* end() noexcept { return m_end; }
T const* data() const noexcept { return m_begin; }
T const* begin() const noexcept { return m_begin; }
T const* end() const noexcept { return m_end; }
bool empty() const noexcept { return m_end == m_begin; }
size_t size() const noexcept { return m_end - m_begin; }
size_t size_bytes() const noexcept { return sizeof(T) * size(); }
T& operator[](size_t index) const noexcept { return m_begin[index]; }
span<T> subspan(size_t index, size_t count) { return span<T>(m_begin + index, m_begin + index + count); }
protected:
T* m_begin = nullptr;
T* m_end = nullptr;
};
}
#if DMLX_USE_ABSEIL
template <typename T>
using Optional = absl::optional<T>;
constexpr absl::nullopt_t NullOpt = absl::nullopt;
template <typename T, size_t N>
using SmallVector = absl::InlinedVector<T, N>;
template <typename T>
using Span = absl::Span<T>;
using absl::make_unique;
#else
#ifndef DMLX_OPTIONAL_EXTENDED
template <typename T>
using Optional = std::optional<T>;
constexpr std::nullopt_t NullOpt = std::nullopt;
#endif
template <typename T, size_t N>
using SmallVector = std::vector<T>;
#if __cpp_lib_span
template <typename T>
using Span = std::span<T>;
#elif DMLX_USE_GSL
template <typename T>
using Span = gsl::span<T>;
#else
template <typename T>
using Span = dml::detail::span<T>;
#endif
using std::make_unique;
#endif
#if __cplusplus >= 201703L && __has_include(<string_view>)
using StringView = std::string_view;
#else
using StringView = const std::string&;
#endif
#if __cpp_lib_byte
using Byte = std::byte;
#else
using Byte = unsigned char;
#endif
#if __cpp_exceptions
#if DMLX_USE_WIL
#define DMLX_THROW_IF_FAILED(_hr) THROW_IF_FAILED(_hr)
#define DMLX_THROW(_hr) THROW_HR(_hr)
#else
#define DMLX_THROW_IF_FAILED(_hr) if (FAILED(_hr)) { throw std::runtime_error(#_hr); }
#define DMLX_THROW(_hr) throw std::runtime_error(#_hr);
#endif
#else
#define DMLX_THROW_IF_FAILED(_hr) if (FAILED(_hr)) { std::abort(); }
#define DMLX_THROW(_hr) { std::abort(); }
#endif
class Graph;
class Expression;
using TensorDimensions = SmallVector<uint32_t, 4>;
using TensorStrides = SmallVector<uint32_t, 4>;
// The custom properties returned by a TensorPolicy.
struct TensorProperties
{
Optional<TensorStrides> strides;
uint64_t totalTensorSizeInBytes;
uint32_t guaranteedBaseOffsetAlignment;
};
// Provides a way to customize the properties that DMLX automatically sets on tensors. Callers may provide their
// own TensorPolicy implementation to provide custom strides, total tensor sizes, and alignment. TensorPolicy
// objects can be set using Graph::SetTensorPolicy().
class TensorPolicy
{
public:
// A function type that returns a TensorProperties object given a tensor data type, flags, and sizes.
using Func = std::function<
TensorProperties (DML_TENSOR_DATA_TYPE dataType, DML_TENSOR_FLAGS flags, Span<const uint32_t> sizes)
>;
TensorPolicy() = default;
/*implicit*/ TensorPolicy(Func impl)
: m_impl(impl)
{}
TensorProperties Get(
DML_TENSOR_DATA_TYPE dataType,
DML_TENSOR_FLAGS flags,
Span<const uint32_t> sizes) const
{
// Empty/uninitialized policy falls back to default.
if (!m_impl)
{
return ComputeDefault(dataType, flags, sizes);
}
return m_impl(dataType, flags, sizes);
}
// Returns the default tensor policy, which doesn't produce any changes to tensor layout, has no guaranteed
// alignment, and which uses DMLCalcBufferTensorSize to compute the total tensor size.
static TensorPolicy Default()
{
return TensorPolicy();
}
// A tensor policy that returns strides which produce tensors with a layout transposed to dimension order
// (0, 2, ..., n, 1). This is often referred to as "NHWC" or "interleaved channel" layout. This is useful,
// for example, when applied to 2D Convolution to produce outputs in an NHWC layout (as opposed to NCHW, which
// is the DirectML default for 2D Convolution).
//
// Examples of the transposes produced by this policy:
// NCW -> NWC
// NCHW -> NHWC
// NCDHW -> NDHWC
static TensorPolicy InterleavedChannel()
{
return TensorPolicy(&ComputeInterleavedChannel);
}
private:
static TensorProperties ComputeDefault(
DML_TENSOR_DATA_TYPE dataType,
DML_TENSOR_FLAGS /*flags*/,
Span<const uint32_t> sizes)
{
uint32_t dimensionCount = static_cast<uint32_t>(sizes.size());
TensorProperties props;
props.strides = NullOpt; // no strides
props.totalTensorSizeInBytes = DMLCalcBufferTensorSize(dataType, dimensionCount, sizes.data(), nullptr);
props.guaranteedBaseOffsetAlignment = 0;
return props;
}
static TensorProperties ComputeInterleavedChannel(
DML_TENSOR_DATA_TYPE dataType,
DML_TENSOR_FLAGS /*flags*/,
Span<const uint32_t> sizes)
{
uint32_t dimensionCount = static_cast<uint32_t>(sizes.size());
TensorStrides strides(dimensionCount);
enum Axes { N, C, /* spatial dimensions ... */ };
// N dimension strides
if (dimensionCount >= 1)
{
strides[N] = 1;
for (uint32_t i = 1; i < dimensionCount; ++i)
{
strides[N] *= sizes[i];
}
}
// C dimension strides
if (dimensionCount >= 2)
{
strides[C] = 1;
}
// Spatial dimension strides
if (dimensionCount >= 3)
{
uint32_t stride = sizes[C];
for (uint32_t i = dimensionCount - 1; i >= 2; --i)
{
strides[i] = stride;
stride *= sizes[i];
}
}
TensorProperties props;
props.strides = std::move(strides);
props.totalTensorSizeInBytes = DMLCalcBufferTensorSize(dataType, dimensionCount, sizes.data(), props.strides->data());
props.guaranteedBaseOffsetAlignment = 0;
return props;
}
Func m_impl;
};
struct TensorDesc
{
public:
using Dimensions = TensorDimensions;
using Strides = TensorStrides;
DML_TENSOR_DATA_TYPE dataType = DML_TENSOR_DATA_TYPE_UNKNOWN;
DML_TENSOR_FLAGS flags = DML_TENSOR_FLAG_NONE;
Dimensions sizes;
Optional<Strides> strides;
uint64_t totalTensorSizeInBytes = 0;
uint32_t guaranteedBaseOffsetAlignment = 0;
TensorDesc() = default;
TensorDesc(DML_TENSOR_DATA_TYPE dataType, Dimensions sizes, const TensorPolicy& policy = {})
: TensorDesc(dataType, DML_TENSOR_FLAG_NONE, sizes, policy)
{}
TensorDesc(DML_TENSOR_DATA_TYPE dataType, DML_TENSOR_FLAGS flags, Dimensions sizes, const TensorPolicy& policy = {})
{
TensorProperties props = policy.Get(dataType, flags, sizes);
Initialize(
dataType,
flags,
std::move(sizes),
std::move(props.strides),
props.totalTensorSizeInBytes,
props.guaranteedBaseOffsetAlignment);
}
TensorDesc(
DML_TENSOR_DATA_TYPE dataType,
DML_TENSOR_FLAGS flags,
Dimensions sizes,
Optional<Dimensions> strides,
uint64_t totalTensorSizeInBytes,
uint32_t guaranteedBaseOffsetAlignment)
{
Initialize(dataType, flags, std::move(sizes), std::move(strides), totalTensorSizeInBytes, guaranteedBaseOffsetAlignment);
}
/* implicit */ TensorDesc(const DML_TENSOR_DESC& desc)
: TensorDesc(*static_cast<const DML_BUFFER_TENSOR_DESC*>(desc.Desc))
{
assert(desc.Type == DML_TENSOR_TYPE_BUFFER);
assert(desc.Desc != nullptr);
}
/* implicit */ TensorDesc(const DML_BUFFER_TENSOR_DESC& desc)
{
this->dataType = desc.DataType;
this->flags = desc.Flags;
this->sizes.assign(desc.Sizes, desc.Sizes + desc.DimensionCount);
if (desc.Strides)
{
this->strides.emplace();
this->strides->assign(desc.Strides, desc.Strides + desc.DimensionCount);
}
this->totalTensorSizeInBytes = desc.TotalTensorSizeInBytes;
this->guaranteedBaseOffsetAlignment = desc.GuaranteedBaseOffsetAlignment;
}
// Returns an equivalent DML_TENSOR_DESC or DML_BUFFER_TENSOR_DESC. The returned object contains pointers
// into the TensorDesc, so it is only valid as long as the TensorDesc itself is alive.
template <typename T>
T* AsPtr()
{
// "sizeof(T) == -1" is always false; this is just to make the static_assert dependent on the template
// parameter and therefore not evaluated until template instantiation
static_assert(sizeof(T) == -1, "Invalid type");
}
template <>
DML_BUFFER_TENSOR_DESC* AsPtr<DML_BUFFER_TENSOR_DESC>()
{
assert(!strides || sizes.size() == strides->size());
m_bufferDesc.DataType = this->dataType;
m_bufferDesc.Flags = this->flags;
m_bufferDesc.DimensionCount = static_cast<UINT>(sizes.size());
m_bufferDesc.Sizes = this->sizes.data();
m_bufferDesc.Strides = this->strides ? this->strides->data() : nullptr;
m_bufferDesc.TotalTensorSizeInBytes = this->totalTensorSizeInBytes;
m_bufferDesc.GuaranteedBaseOffsetAlignment = this->guaranteedBaseOffsetAlignment;
return &m_bufferDesc;
}
template <>
DML_TENSOR_DESC* AsPtr<DML_TENSOR_DESC>()
{
m_tensorDesc = DML_TENSOR_DESC{ DML_TENSOR_TYPE_BUFFER, AsPtr<DML_BUFFER_TENSOR_DESC>() };
return &m_tensorDesc;
}
private:
DML_BUFFER_TENSOR_DESC m_bufferDesc;
DML_TENSOR_DESC m_tensorDesc;
void Initialize(
DML_TENSOR_DATA_TYPE tensorDataType,
DML_TENSOR_FLAGS tensorFlags,
Dimensions tensorSizes,
Optional<Dimensions> tensorStrides,
uint64_t totalTensorSizeInBytesVal,
uint32_t guaranteedBaseOffsetAlignmentVal)
{
assert(!tensorStrides || tensorStrides->size() == static_cast<uint32_t>(tensorSizes.size()));
this->dataType = tensorDataType;
this->flags = tensorFlags;
this->sizes = std::move(tensorSizes);
this->strides = std::move(tensorStrides);
this->totalTensorSizeInBytes = totalTensorSizeInBytesVal;
this->guaranteedBaseOffsetAlignment = guaranteedBaseOffsetAlignmentVal;
}
};
namespace detail
{
class GraphBuilder;
class NodeOutput;
// A node in the graph which represents a graph input.
struct InputNode
{
uint32_t inputIndex;
};
// A node in the graph which represents a DML operator.
struct OperatorNode
{
Microsoft::WRL::ComPtr<IDMLOperator> op;
// The inputs to this node
std::vector<NodeOutput*> inputs;
std::string name;
};
// Used for representing reshapes and type punning
struct ReinterpretNode
{
NodeOutput* input;
};
// A node in the graph that represents data available during graph compilation.
struct ConstantNode
{
// This node does not own the memory to avoid copying large amounts of data.
Span<const Byte> data;
std::string name;
};
enum class NodeType
{
Invalid,
Input,
Operator,
Reinterpret,
Constant,
};
// Identifies a node in the graph.
struct NodeID
{
NodeType type;
uint32_t index; // The index of this node in the GraphBuilder
};
// Represents one of the outputs of a node.
class NodeOutput
{
public:
NodeOutput(GraphBuilder* owner, NodeID node, uint32_t outputIndex, TensorDesc tensorDesc)
: m_owner(owner)
, m_node(node)
, m_outputIndex(outputIndex)
, m_tensorDesc(std::move(tensorDesc))
{}
// Retrieves the GraphBuilder that owns this object.
GraphBuilder* GetGraphBuilder() const { return m_owner; }
NodeID GetNode() const { return m_node; }
uint32_t GetOutputIndex() const { return m_outputIndex; }
const TensorDesc& GetOutputDesc() const { return m_tensorDesc; }
private:
GraphBuilder* m_owner;
NodeID m_node;
// An operator can have multiple outputs; this index identifies which one of the operator's outputs this
// NodeOutput represents.
uint32_t m_outputIndex;
TensorDesc m_tensorDesc;
};
struct GraphDesc
{
uint32_t inputCount;
uint32_t outputCount;
std::vector<DML_OPERATOR_GRAPH_NODE_DESC> operatorNodes;
#if DML_TARGET_VERSION >= 0x6200
std::vector<DML_CONSTANT_DATA_GRAPH_NODE_DESC> constantNodes;
#endif // DML_TARGET_VERSION >= 0x6200
std::vector<DML_INPUT_GRAPH_EDGE_DESC> inputEdges;
std::vector<DML_OUTPUT_GRAPH_EDGE_DESC> outputEdges;
std::vector<DML_INTERMEDIATE_GRAPH_EDGE_DESC> intermediateEdges;
// Offset of the first operator node in the merged node list.
constexpr uint32_t BaseOperatorNodeIndexInMergedNodes() const
{
return 0;
}
// Offset of the first constant node in the merged node list.
uint32_t BaseConstantNodeIndexInMergedNodes() const
{
return static_cast<uint32_t>(operatorNodes.size());
}
// Merges the operator and constant nodes into a single list of graph nodes, with all operator nodes
// inserted before the constant nodes. The returned array is only valid so long as this instance of
// GraphDesc is alive and not copied.
std::vector<DML_GRAPH_NODE_DESC> Nodes() const
{
const size_t operatorNodeCount = operatorNodes.size();
#if DML_TARGET_VERSION >= 0x6200
const size_t constantNodeCount = constantNodes.size();
#else
const uint32_t constantNodeCount = 0;
#endif // DML_TARGET_VERSION >= 0x6200
std::vector<DML_GRAPH_NODE_DESC> nodes(operatorNodeCount + constantNodeCount);
auto nodesOperatorNodeSpan = dml::Span<DML_GRAPH_NODE_DESC>(nodes.data() + BaseOperatorNodeIndexInMergedNodes(), operatorNodeCount);
for (size_t i = 0; i < nodesOperatorNodeSpan.size(); ++i)
{
nodesOperatorNodeSpan[i] = { DML_GRAPH_NODE_TYPE_OPERATOR, &operatorNodes[i] };
}
#if DML_TARGET_VERSION >= 0x6200
auto nodesConstantNodeSpan = dml::Span<DML_GRAPH_NODE_DESC>(nodes.data() + BaseConstantNodeIndexInMergedNodes(), constantNodeCount);
for (size_t i = 0; i < nodesConstantNodeSpan.size(); ++i)
{
nodesConstantNodeSpan[i] = { DML_GRAPH_NODE_TYPE_CONSTANT, &constantNodes[i] };
}
#endif // DML_TARGET_VERSION >= 0x6200
return nodes;
}
template <typename T>
std::vector<DML_GRAPH_EDGE_DESC> Edges(DML_GRAPH_EDGE_TYPE type, Span<const T> edgesImpl) const
{
std::vector<DML_GRAPH_EDGE_DESC> edges(edgesImpl.size());
for (size_t i = 0; i < edges.size(); ++i)
{
edges[i] = { type, &edgesImpl[i] };
}
return edges;
}
std::vector<DML_GRAPH_EDGE_DESC> InputEdges() const
{
return Edges(DML_GRAPH_EDGE_TYPE_INPUT, Span<const DML_INPUT_GRAPH_EDGE_DESC>(inputEdges));
}
std::vector<DML_GRAPH_EDGE_DESC> OutputEdges() const
{
return Edges(DML_GRAPH_EDGE_TYPE_OUTPUT, Span<const DML_OUTPUT_GRAPH_EDGE_DESC>(outputEdges));
}
std::vector<DML_GRAPH_EDGE_DESC> IntermediateEdges() const
{
return Edges(DML_GRAPH_EDGE_TYPE_INTERMEDIATE, Span<const DML_INTERMEDIATE_GRAPH_EDGE_DESC>(intermediateEdges));
}
};
class GraphBuilder
{
public:
GraphBuilder(IDMLDevice* device, TensorPolicy tensorPolicy = {})
: m_device(device)
, m_tensorPolicy(tensorPolicy)
{}
IDMLDevice* GetDevice() const
{
return m_device.Get();
}
void PushName(StringView name)
{
m_nameSubLengths.push(m_name.size());
if (!m_name.empty())
{
m_name += "_";
}
m_name += name;
}
void PopName()
{
if (!m_nameSubLengths.empty())
{
m_name.resize(m_nameSubLengths.top());
m_nameSubLengths.pop();
}
}
void SetTensorPolicy(TensorPolicy policy) { m_tensorPolicy = std::move(policy); }
const TensorPolicy& GetTensorPolicy() const { return m_tensorPolicy; }
TensorPolicy& GetTensorPolicy() { return m_tensorPolicy; }
// Creates a DML operator node owned by this graph builder and returns a NodeInfo identifier. The
// inputs to this node must be supplied in the correct order matching the DML operator.
NodeID CreateOperatorNode(DML_OPERATOR_TYPE type, const void* desc, Span<NodeOutput* const> inputs);
NodeID CreateInputNode(uint32_t inputIndex);
NodeID CreateReinterpretNode(NodeOutput* input);
#if DML_TARGET_VERSION >= 0x6200
NodeID CreateConstantNode(Span<const Byte> data);
#endif // DML_TARGET_VERSION >= 0x6200
NodeOutput* CreateNodeOutput(NodeID node, uint32_t outputIndex, TensorDesc tensorDesc);
GraphDesc GetGraphDesc(Span<const Expression> outputs) const;
private:
Microsoft::WRL::ComPtr<IDMLDevice> m_device;
TensorPolicy m_tensorPolicy;
std::vector<InputNode> m_inputNodes;
std::vector<OperatorNode> m_operatorNodes;
std::vector<ReinterpretNode> m_reinterpretNodes;
std::vector<ConstantNode> m_constantNodes;
std::deque<NodeOutput> m_nodeOutputs; // deque doesn't invalidate references to elements when it resizes
std::string m_name;
std::stack<size_t> m_nameSubLengths;
};
} // namespace detail
class Expression
{
public:
/*implicit*/ Expression(detail::NodeOutput* nodeOutput = nullptr)
: m_nodeOutput(nodeOutput)
{}
// Returns a struct containing the required properties of the tensor to hold the output of this expression,
// once evaluated.
const TensorDesc& GetOutputDesc() const { return Impl()->GetOutputDesc(); }
// For internal use only
detail::NodeOutput* Impl() const { return m_nodeOutput; }
explicit operator bool() const
{
return m_nodeOutput != nullptr;
}
private:
detail::NodeOutput* m_nodeOutput; // weak; this is owned by the GraphBuilder
};
class NameScope
{
public:
detail::GraphBuilder* m_builder = nullptr;
NameScope(detail::GraphBuilder* builder, StringView name) : m_builder(builder)
{
if (m_builder) m_builder->PushName(name);
}
~NameScope()
{
if (m_builder) m_builder->PopName();
}
};
class Graph
{
public:
explicit Graph(IDMLDevice* device, TensorPolicy tensorPolicy = {})
: m_graphBuilder(make_unique<detail::GraphBuilder>(device, tensorPolicy))
{}
// For internal use only
detail::GraphBuilder* Impl() { return m_graphBuilder.get(); }
// Sets/gets the tensor policy. If not set, defaults to TensorPolicy::Default(). Tensor policies can be used
// to control properties (such as strides) on output tensors produced by this Graph.
void SetTensorPolicy(TensorPolicy policy) { m_graphBuilder->SetTensorPolicy(std::move(policy)); }
const TensorPolicy& GetTensorPolicy() const { return m_graphBuilder->GetTensorPolicy(); }
TensorPolicy& GetTensorPolicy() { return m_graphBuilder->GetTensorPolicy(); }
NameScope CreateNameScope(StringView name) { return NameScope(m_graphBuilder.get(), name); }
void PushName(StringView name) { m_graphBuilder->PushName(name); }
void PopName() { m_graphBuilder->PopName(); }
Microsoft::WRL::ComPtr<IDMLCompiledOperator> Compile(
DML_EXECUTION_FLAGS flags,
Span<const Expression> outputs,
uint32_t inputCount = 0) const
{
detail::GraphDesc graph = m_graphBuilder->GetGraphDesc(outputs);
// If supplied, the requested number of inputs to the compiled operator can be larger than the actual
// number of input nodes on the graph (e.g. in the case of unused empty inputs), but never smaller.
assert(inputCount == 0 || inputCount >= graph.inputCount);
std::vector<DML_GRAPH_NODE_DESC> graphNodes = graph.Nodes();
std::vector<DML_GRAPH_EDGE_DESC> inputEdges = graph.InputEdges();
std::vector<DML_GRAPH_EDGE_DESC> outputEdges = graph.OutputEdges();
std::vector<DML_GRAPH_EDGE_DESC> intermediateEdges = graph.IntermediateEdges();
DML_GRAPH_DESC graphDesc = {};
graphDesc.InputCount = inputCount ? inputCount : graph.inputCount;
graphDesc.OutputCount = graph.outputCount;
graphDesc.NodeCount = static_cast<UINT>(graphNodes.size());
graphDesc.Nodes = graphNodes.data();
graphDesc.InputEdgeCount = static_cast<UINT>(inputEdges.size());
graphDesc.InputEdges = inputEdges.data();
graphDesc.OutputEdgeCount = static_cast<UINT>(outputEdges.size());
graphDesc.OutputEdges = outputEdges.data();
graphDesc.IntermediateEdgeCount = static_cast<UINT>(intermediateEdges.size());
graphDesc.IntermediateEdges = intermediateEdges.data();
Microsoft::WRL::ComPtr<IDMLDevice1> device1;
DMLX_THROW_IF_FAILED(m_graphBuilder->GetDevice()->QueryInterface(IID_PPV_ARGS(&device1)));
Microsoft::WRL::ComPtr<IDMLCompiledOperator> compiledGraph;
DMLX_THROW_IF_FAILED(device1->CompileGraph(&graphDesc, flags, IID_PPV_ARGS(&compiledGraph)));
return compiledGraph;
}
private:
std::unique_ptr<detail::GraphBuilder> m_graphBuilder;
};
// Represents an activation to be fused with an existing operator. The meaning of param1 and param2 depend on the
// activation to be fused.
//
// For HARD_SIGMOID, LINEAR, PARAMETRIC_SOFTPLUS, and SCALED_TANH: param1 = Alpha and param2 = Beta
// For ELU, LEAKY_RELU, THRESHOLDED_RELU, and CELU: param1 = Alpha. param2 is unused.
// For SCALED_ELU, param1 = Alpha and param2 = Gamma.
// For SHRINK, param1 = Bias and param2 = Threshold
// For SOFTPLUS, param1 = Steepness.
// For all other activations, both param1 and param2 are unused.
struct FusedActivation
{
DML_OPERATOR_TYPE activation = DML_OPERATOR_INVALID;
float param1 = 0.0f;
float param2 = 0.0f;
FusedActivation() = default;
explicit FusedActivation(DML_OPERATOR_TYPE activation, float param1 = 0.0f, float param2 = 0.0f)
: activation(activation), param1(param1), param2(param2)
{}
static FusedActivation None()
{
return FusedActivation();
}
static FusedActivation Elu(float alpha = 1.0f)
{
return FusedActivation(DML_OPERATOR_ACTIVATION_ELU, alpha);
}
static FusedActivation HardSigmoid(float alpha = 0.2f, float beta = 0.5f)
{
return FusedActivation(DML_OPERATOR_ACTIVATION_HARD_SIGMOID, alpha, beta);
}
static FusedActivation Identity()
{
return FusedActivation(DML_OPERATOR_ACTIVATION_IDENTITY);
}
static FusedActivation LeakyRelu(float alpha = 0.01f)
{
return FusedActivation(DML_OPERATOR_ACTIVATION_LEAKY_RELU, alpha);
}
static FusedActivation Linear(float alpha, float beta)
{
return FusedActivation(DML_OPERATOR_ACTIVATION_LINEAR, alpha, beta);
}
static FusedActivation ParametricSoftplus(float alpha, float beta)
{
return FusedActivation(DML_OPERATOR_ACTIVATION_PARAMETRIC_SOFTPLUS, alpha, beta);
}
static FusedActivation Relu()
{
return FusedActivation(DML_OPERATOR_ACTIVATION_RELU);
}
static FusedActivation ScaledElu(float alpha = 1.67326319217681884765625f, float gamma = 1.05070102214813232421875f)
{
return FusedActivation(DML_OPERATOR_ACTIVATION_SCALED_ELU, alpha, gamma);
}
static FusedActivation ScaledTanh(float alpha = 1.0f, float beta = 0.5f)
{
return FusedActivation(DML_OPERATOR_ACTIVATION_SCALED_TANH, alpha, beta);
}
static FusedActivation Sigmoid()
{
return FusedActivation(DML_OPERATOR_ACTIVATION_SIGMOID);
}
static FusedActivation Softplus(float steepness = 1.0f)
{
return FusedActivation(DML_OPERATOR_ACTIVATION_SOFTPLUS, steepness);
}
static FusedActivation Softsign()
{
return FusedActivation(DML_OPERATOR_ACTIVATION_SOFTSIGN);
}
static FusedActivation Tanh()
{
return FusedActivation(DML_OPERATOR_ACTIVATION_TANH);
}
static FusedActivation ThresholdedRelu(float alpha = 1.0f)
{
return FusedActivation(DML_OPERATOR_ACTIVATION_THRESHOLDED_RELU, alpha);
}
static FusedActivation Shrink(float bias = 0.0f, float threshold = 0.5f)
{
return FusedActivation(DML_OPERATOR_ACTIVATION_SHRINK, bias, threshold);
}
static FusedActivation Celu(float alpha = 1.0f)
{
return FusedActivation(DML_OPERATOR_ACTIVATION_CELU, alpha);
}
#if DML_TARGET_VERSION >= 0x5100
static FusedActivation Gelu()
{
return FusedActivation(DML_OPERATOR_ACTIVATION_GELU);
}
#endif // DML_TARGET_VERSION >= 0x5100
};
// Implementation detail helper for determining if a list of expressions share the same GraphBuilder.
namespace detail
{
inline bool HasSameOwner(Span<const Expression> exprs)
{
if (exprs.size() == 0)
{
return true;
}
detail::GraphBuilder* owner = exprs.begin()->Impl()->GetGraphBuilder();
for (Expression expr : exprs)
{
if (expr.Impl()->GetGraphBuilder() != owner)
{
return false;
}
}
return true;
}
inline bool HasSameOwner(std::initializer_list<Expression> exprs)
{
Span<const Expression> span(exprs.begin(), exprs.size());
return HasSameOwner(span);
}
inline bool HasSameDataType(Span<const Expression> exprs)
{