-
Notifications
You must be signed in to change notification settings - Fork 1.1k
Expand file tree
/
Copy pathVGFSetup.cpp
More file actions
3731 lines (3473 loc) · 126 KB
/
Copy pathVGFSetup.cpp
File metadata and controls
3731 lines (3473 loc) · 126 KB
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 2025-2026 Arm Limited and/or its affiliates.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*/
/*
* VGF functions which prepare a graph for execution by allocating the
* appropriate vulkan structures.
*/
#include <executorch/backends/arm/runtime/VGFSetup.h>
#include <cstdlib>
#include <limits>
#ifdef ET_EVENT_TRACER_ENABLED
#include <executorch/runtime/core/event_tracer_hooks_delegate.h>
#endif
#include <vgf/decoder.hpp>
#if __has_include(<vgf/version.h>)
#include <vgf/version.h>
#endif
#include <vgf/vulkan_helpers.generated.hpp>
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <limits>
#include <optional>
#include <type_traits>
#include <unordered_map>
using namespace mlsdk;
#if defined(MLSDK_VGF_LIBRARY_API_VERSION_MAJOR) && \
defined(MLSDK_VGF_LIBRARY_API_VERSION_MINOR)
#define EXECUTORCH_ARM_VGF_HAS_DECODER_V10_APIS \
((MLSDK_VGF_LIBRARY_API_VERSION_MAJOR > 0) || \
(MLSDK_VGF_LIBRARY_API_VERSION_MAJOR == 0 && \
MLSDK_VGF_LIBRARY_API_VERSION_MINOR >= 10))
#else
#define EXECUTORCH_ARM_VGF_HAS_DECODER_V10_APIS 0
#endif
namespace executorch {
namespace backends {
namespace vgf {
/* static function to map format to byte count */
static uint32_t get_format_size(VkFormat format);
// SPV_ARM_tensor does not support rank-0 representations according to the spec.
// Use an unsqueezed dimension when the resource table contains an empty
// shape. Tensors are output as rank 0 when copied back from the vgf backend.
namespace {
constexpr int64_t kScalarSentinelDimension = 1;
static bool is_image_descriptor_type(VkDescriptorType descriptor_type);
static bool is_tensor_like_descriptor_type(VkDescriptorType descriptor_type);
enum class FormatScalarKind {
Bool,
Uint,
Sint,
Float,
};
struct FormatInfo {
uint32_t component_count = 0;
uint32_t bytes_per_component = 0;
FormatScalarKind scalar_kind = FormatScalarKind::Uint;
};
struct AliasLogicalContract {
bool initialized = false;
vector<int64_t> shape;
vector<int64_t> stride;
size_t logical_byte_size = 0;
uint32_t scalar_bytes = 0;
FormatScalarKind scalar_kind = FormatScalarKind::Uint;
bool image_initialized = false;
uint32_t image_component_count = 0;
};
static size_t element_count_from_shape(const vector<int64_t>& shape) {
if (shape.empty()) {
return 1;
}
size_t count = 1;
for (auto dim : shape) {
if (dim <= 0) {
return 0;
}
count *= static_cast<size_t>(dim);
}
return count;
}
#ifdef ET_EVENT_TRACER_ENABLED
class ScopedVgfProfileEvent {
public:
ScopedVgfProfileEvent(
executorch::runtime::EventTracer* event_tracer,
const char* name)
: event_tracer_(event_tracer),
entry_(executorch::runtime::event_tracer_start_profiling_delegate(
event_tracer_,
name,
/*delegate_debug_id=*/-1)) {}
~ScopedVgfProfileEvent() {
executorch::runtime::event_tracer_end_profiling_delegate(
event_tracer_, entry_);
}
private:
executorch::runtime::EventTracer* event_tracer_;
executorch::runtime::EventTracerEntry entry_;
};
#endif
#define VGF_CONCAT_INNER(a, b) a##b
#define VGF_CONCAT(a, b) VGF_CONCAT_INNER(a, b)
#ifdef ET_EVENT_TRACER_ENABLED
#define VGF_PROFILE_SCOPE(event_tracer, name) \
ScopedVgfProfileEvent VGF_CONCAT(_vgf_profile_scope_, __LINE__)( \
event_tracer, name)
#else
#define VGF_PROFILE_SCOPE(event_tracer, name) (void)(event_tracer)
#endif
static vector<int64_t> normalize_stride(
const vector<int64_t>& shape,
const vector<int64_t>& stride) {
if (!stride.empty()) {
return stride;
}
vector<int64_t> contiguous_stride(shape.size(), 1);
int64_t running = 1;
for (size_t idx = shape.size(); idx > 0; --idx) {
contiguous_stride[idx - 1] = running;
running *= shape[idx - 1];
}
return contiguous_stride;
}
static uint32_t get_format_component_count(VkFormat format) {
switch (format) {
case VK_FORMAT_R8_BOOL_ARM:
case VK_FORMAT_R8_UINT:
case VK_FORMAT_R8_SINT:
case VK_FORMAT_R16_UINT:
case VK_FORMAT_R16_SINT:
case VK_FORMAT_R16_SFLOAT:
case VK_FORMAT_R32_UINT:
case VK_FORMAT_R32_SINT:
case VK_FORMAT_R32_SFLOAT:
case VK_FORMAT_R64_SINT:
return 1;
case VK_FORMAT_R8G8_UINT:
case VK_FORMAT_R8G8_SINT:
case VK_FORMAT_R16G16_UINT:
case VK_FORMAT_R16G16_SINT:
case VK_FORMAT_R16G16_SFLOAT:
case VK_FORMAT_R32G32_UINT:
case VK_FORMAT_R32G32_SINT:
case VK_FORMAT_R32G32_SFLOAT:
return 2;
case VK_FORMAT_R8G8B8A8_UINT:
case VK_FORMAT_R8G8B8A8_SINT:
case VK_FORMAT_R16G16B16A16_UINT:
case VK_FORMAT_R16G16B16A16_SINT:
case VK_FORMAT_R16G16B16A16_SFLOAT:
case VK_FORMAT_R32G32B32A32_UINT:
case VK_FORMAT_R32G32B32A32_SINT:
case VK_FORMAT_R32G32B32A32_SFLOAT:
return 4;
default:
ET_LOG(
Error,
"Unsupported image VkFormat %u for component count",
static_cast<uint32_t>(format));
return 0;
}
}
static bool get_format_info(VkFormat format, FormatInfo* info) {
switch (format) {
case VK_FORMAT_R8_BOOL_ARM:
*info = FormatInfo{1, 1, FormatScalarKind::Bool};
return true;
case VK_FORMAT_R8_UINT:
*info = FormatInfo{1, 1, FormatScalarKind::Uint};
return true;
case VK_FORMAT_R8_SINT:
*info = FormatInfo{1, 1, FormatScalarKind::Sint};
return true;
case VK_FORMAT_R16_UINT:
*info = FormatInfo{1, 2, FormatScalarKind::Uint};
return true;
case VK_FORMAT_R16_SINT:
*info = FormatInfo{1, 2, FormatScalarKind::Sint};
return true;
case VK_FORMAT_R16_SFLOAT:
*info = FormatInfo{1, 2, FormatScalarKind::Float};
return true;
case VK_FORMAT_R32_UINT:
*info = FormatInfo{1, 4, FormatScalarKind::Uint};
return true;
case VK_FORMAT_R32_SINT:
*info = FormatInfo{1, 4, FormatScalarKind::Sint};
return true;
case VK_FORMAT_R32_SFLOAT:
*info = FormatInfo{1, 4, FormatScalarKind::Float};
return true;
case VK_FORMAT_R64_SINT:
*info = FormatInfo{1, 8, FormatScalarKind::Sint};
return true;
case VK_FORMAT_R8G8_UINT:
*info = FormatInfo{2, 1, FormatScalarKind::Uint};
return true;
case VK_FORMAT_R8G8_SINT:
*info = FormatInfo{2, 1, FormatScalarKind::Sint};
return true;
case VK_FORMAT_R16G16_UINT:
*info = FormatInfo{2, 2, FormatScalarKind::Uint};
return true;
case VK_FORMAT_R16G16_SINT:
*info = FormatInfo{2, 2, FormatScalarKind::Sint};
return true;
case VK_FORMAT_R16G16_SFLOAT:
*info = FormatInfo{2, 2, FormatScalarKind::Float};
return true;
case VK_FORMAT_R32G32_UINT:
*info = FormatInfo{2, 4, FormatScalarKind::Uint};
return true;
case VK_FORMAT_R32G32_SINT:
*info = FormatInfo{2, 4, FormatScalarKind::Sint};
return true;
case VK_FORMAT_R32G32_SFLOAT:
*info = FormatInfo{2, 4, FormatScalarKind::Float};
return true;
case VK_FORMAT_R8G8B8A8_UINT:
*info = FormatInfo{4, 1, FormatScalarKind::Uint};
return true;
case VK_FORMAT_R8G8B8A8_SINT:
*info = FormatInfo{4, 1, FormatScalarKind::Sint};
return true;
case VK_FORMAT_R16G16B16A16_UINT:
*info = FormatInfo{4, 2, FormatScalarKind::Uint};
return true;
case VK_FORMAT_R16G16B16A16_SINT:
*info = FormatInfo{4, 2, FormatScalarKind::Sint};
return true;
case VK_FORMAT_R16G16B16A16_SFLOAT:
*info = FormatInfo{4, 2, FormatScalarKind::Float};
return true;
case VK_FORMAT_R32G32B32A32_UINT:
*info = FormatInfo{4, 4, FormatScalarKind::Uint};
return true;
case VK_FORMAT_R32G32B32A32_SINT:
*info = FormatInfo{4, 4, FormatScalarKind::Sint};
return true;
case VK_FORMAT_R32G32B32A32_SFLOAT:
*info = FormatInfo{4, 4, FormatScalarKind::Float};
return true;
default:
ET_LOG(Error, "Unsupported VkFormat %u", static_cast<uint32_t>(format));
return false;
}
}
static bool validate_image_shape_and_format(
const vector<int64_t>& shape,
VkFormat format,
VkExtent3D* image_extent,
size_t* staging_size = nullptr) {
const uint32_t format_component_count = get_format_component_count(format);
const size_t bytes_per_pixel = get_format_size(format);
if (format_component_count == 0 || bytes_per_pixel == 0) {
return false;
}
int64_t height = 0;
int64_t width = 0;
int64_t channels = 0;
if (shape.size() == 4) {
if (shape[0] != 1) {
ET_LOG(Error, "Only batch size 1 images are currently supported");
return false;
}
height = shape[1];
width = shape[2];
channels = shape[3];
} else if (shape.size() == 3) {
height = shape[0];
width = shape[1];
channels = shape[2];
} else {
ET_LOG(Error, "Unsupported image shape rank %zu", shape.size());
return false;
}
if (height <= 0 || width <= 0 || channels <= 0) {
ET_LOG(
Error,
"Image shape dimensions must be positive, got [%lld, %lld, %lld]",
static_cast<long long>(height),
static_cast<long long>(width),
static_cast<long long>(channels));
return false;
}
if (static_cast<uint32_t>(channels) != format_component_count) {
ET_LOG(
Error,
"Image channel count %lld does not match VkFormat %u component count %u",
static_cast<long long>(channels),
static_cast<uint32_t>(format),
format_component_count);
return false;
}
image_extent->width = static_cast<uint32_t>(width);
image_extent->height = static_cast<uint32_t>(height);
image_extent->depth = 1;
if (staging_size != nullptr) {
const size_t pixel_count = static_cast<size_t>(image_extent->width) *
static_cast<size_t>(image_extent->height) *
static_cast<size_t>(image_extent->depth);
if (pixel_count > std::numeric_limits<size_t>::max() / bytes_per_pixel) {
ET_LOG(Error, "Image staging allocation size overflow");
return false;
}
*staging_size = pixel_count * bytes_per_pixel;
}
return true;
}
static bool validate_alias_group_logical_contract(
uint32_t alias_group_id,
uint32_t resource_index,
VkDescriptorType descriptor_type,
VkFormat format,
const vector<int64_t>& shape,
const vector<int64_t>& stride,
AliasLogicalContract* contract) {
FormatInfo format_info;
if (!get_format_info(format, &format_info)) {
return false;
}
size_t logical_byte_size = 0;
if (is_image_descriptor_type(descriptor_type)) {
VkExtent3D image_extent = {};
if (!validate_image_shape_and_format(
shape, format, &image_extent, &logical_byte_size)) {
return false;
}
} else if (is_tensor_like_descriptor_type(descriptor_type)) {
if (format_info.component_count != 1) {
ET_LOG(
Error,
"Alias group %u tensor-like resource %u must use a scalar VkFormat",
alias_group_id,
resource_index);
return false;
}
logical_byte_size =
element_count_from_shape(shape) * get_format_size(format);
} else {
ET_LOG(
Error,
"Alias group %u contains unsupported descriptor type %u for resource %u",
alias_group_id,
static_cast<uint32_t>(descriptor_type),
resource_index);
return false;
}
const vector<int64_t> normalized_stride = normalize_stride(shape, stride);
if (!contract->initialized) {
contract->initialized = true;
contract->shape = shape;
contract->stride = normalized_stride;
contract->logical_byte_size = logical_byte_size;
contract->scalar_bytes = format_info.bytes_per_component;
contract->scalar_kind = format_info.scalar_kind;
} else {
if (contract->shape != shape || contract->stride != normalized_stride) {
ET_LOG(
Error,
"Alias group %u has mismatched logical layout at resource %u",
alias_group_id,
resource_index);
return false;
}
if (contract->logical_byte_size != logical_byte_size) {
ET_LOG(
Error,
"Alias group %u has mismatched logical byte size at resource %u",
alias_group_id,
resource_index);
return false;
}
if (contract->scalar_bytes != format_info.bytes_per_component ||
contract->scalar_kind != format_info.scalar_kind) {
ET_LOG(
Error,
"Alias group %u has mismatched scalar format at resource %u",
alias_group_id,
resource_index);
return false;
}
}
if (is_image_descriptor_type(descriptor_type)) {
if (!contract->image_initialized) {
contract->image_initialized = true;
contract->image_component_count = format_info.component_count;
} else if (contract->image_component_count != format_info.component_count) {
ET_LOG(
Error,
"Alias group %u has mismatched image channel packing at resource %u",
alias_group_id,
resource_index);
return false;
}
}
if (contract->image_initialized && !shape.empty() &&
static_cast<uint32_t>(shape.back()) != contract->image_component_count) {
ET_LOG(
Error,
"Alias group %u shape channel dimension does not match image packing at resource %u",
alias_group_id,
resource_index);
return false;
}
return true;
}
static VkDescriptorType resolve_descriptor_type(
unique_ptr<vgflib::ModelResourceTableDecoder>& resource_decoder,
uint32_t index) {
auto descriptor_type = resource_decoder->getDescriptorType(index);
if (descriptor_type.has_value()) {
return vgflib::ToVkDescriptorType(descriptor_type.value());
}
ET_LOG(
Info,
"Resource %u has no explicit descriptor type; assuming VK_DESCRIPTOR_TYPE_TENSOR_ARM",
index);
return VK_DESCRIPTOR_TYPE_TENSOR_ARM;
}
static VkPipelineStageFlags2 vgf_execution_stage_mask() {
return VK_PIPELINE_STAGE_2_COMPUTE_SHADER_BIT |
VK_PIPELINE_STAGE_2_DATA_GRAPH_BIT_ARM;
}
static VkAccessFlags2 vgf_execution_read_access_mask() {
return VK_ACCESS_2_SHADER_READ_BIT | VK_ACCESS_2_DATA_GRAPH_READ_BIT_ARM;
}
static VkAccessFlags2 vgf_execution_write_access_mask() {
return VK_ACCESS_2_SHADER_WRITE_BIT | VK_ACCESS_2_DATA_GRAPH_WRITE_BIT_ARM;
}
static bool is_image_descriptor_type(VkDescriptorType descriptor_type) {
return descriptor_type == VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER ||
descriptor_type == VK_DESCRIPTOR_TYPE_SAMPLED_IMAGE ||
descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_IMAGE;
}
static bool is_tensor_like_descriptor_type(VkDescriptorType descriptor_type) {
return descriptor_type == VK_DESCRIPTOR_TYPE_TENSOR_ARM ||
descriptor_type == VK_DESCRIPTOR_TYPE_STORAGE_BUFFER;
}
static VkResult submit_and_wait_with_fence(
VkDevice device,
VkQueue queue,
const VkSubmitInfo* submit_info) {
VkFence fence = VK_NULL_HANDLE;
const VkFenceCreateInfo fence_info = {
.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
};
VkResult result = vkCreateFence(device, &fence_info, nullptr, &fence);
if (result != VK_SUCCESS) {
ET_LOG(Error, "Failed to create Vulkan fence, error %d", result);
return result;
}
result = vkQueueSubmit(queue, 1, submit_info, fence);
if (result != VK_SUCCESS) {
ET_LOG(Error, "Vulkan queue submit failed, error %d", result);
vkDestroyFence(device, fence, nullptr);
return result;
}
result = vkWaitForFences(
device, 1, &fence, VK_TRUE, std::numeric_limits<uint64_t>::max());
vkDestroyFence(device, fence, nullptr);
return result;
}
static void record_image_layout_transition(
VkCommandBuffer command_buffer,
VkImage image,
VkImageLayout old_layout,
VkImageLayout new_layout) {
const VkImageMemoryBarrier2 image_barrier = {
.sType = VK_STRUCTURE_TYPE_IMAGE_MEMORY_BARRIER_2,
.pNext = nullptr,
.srcStageMask = old_layout == VK_IMAGE_LAYOUT_UNDEFINED
? VK_PIPELINE_STAGE_2_NONE
: (VK_PIPELINE_STAGE_2_TRANSFER_BIT | vgf_execution_stage_mask()),
.srcAccessMask = old_layout == VK_IMAGE_LAYOUT_UNDEFINED
? VK_ACCESS_2_NONE
: (VK_ACCESS_2_TRANSFER_READ_BIT | VK_ACCESS_2_TRANSFER_WRITE_BIT |
vgf_execution_read_access_mask() |
vgf_execution_write_access_mask()),
.dstStageMask =
VK_PIPELINE_STAGE_2_TRANSFER_BIT | vgf_execution_stage_mask(),
.dstAccessMask = VK_ACCESS_2_TRANSFER_READ_BIT |
VK_ACCESS_2_TRANSFER_WRITE_BIT | vgf_execution_read_access_mask() |
vgf_execution_write_access_mask(),
.oldLayout = old_layout,
.newLayout = new_layout,
.srcQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.dstQueueFamilyIndex = VK_QUEUE_FAMILY_IGNORED,
.image = image,
.subresourceRange =
{
.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT,
.baseMipLevel = 0,
.levelCount = 1,
.baseArrayLayer = 0,
.layerCount = 1,
},
};
const VkDependencyInfo dependency_info = {
.sType = VK_STRUCTURE_TYPE_DEPENDENCY_INFO,
.pNext = nullptr,
.memoryBarrierCount = 0,
.pMemoryBarriers = nullptr,
.bufferMemoryBarrierCount = 0,
.pBufferMemoryBarriers = nullptr,
.imageMemoryBarrierCount = 1,
.pImageMemoryBarriers = &image_barrier,
};
vkCmdPipelineBarrier2(command_buffer, &dependency_info);
}
} // namespace
void destroy_tensor(
VkDevice device,
VkTensorViewARM tensor_view,
VkTensorARM tensor) {
vkDestroyTensorViewARM(device, tensor_view, nullptr);
vkDestroyTensorARM(device, tensor, nullptr);
}
void destroy_buffer(VkDevice device, VkBuffer buffer) {
vkDestroyBuffer(device, buffer, nullptr);
}
void free_image(
VkDevice device,
VkImageView image_view,
VkImage image,
VkSampler sampler,
VkDeviceMemory memory) {
if (sampler != VK_NULL_HANDLE) {
vkDestroySampler(device, sampler, nullptr);
}
if (image_view != VK_NULL_HANDLE) {
vkDestroyImageView(device, image_view, nullptr);
}
if (image != VK_NULL_HANDLE) {
vkDestroyImage(device, image, nullptr);
}
if (memory != VK_NULL_HANDLE) {
vkFreeMemory(device, memory, nullptr);
}
}
static bool find_memory_index_from_bits(
VkPhysicalDevice vk_physical,
uint32_t memory_type_bits,
VkMemoryPropertyFlags aims,
uint32_t* memory_type_out) {
VkPhysicalDeviceMemoryProperties mem_properties;
vkGetPhysicalDeviceMemoryProperties(vk_physical, &mem_properties);
for (uint32_t i = 0; i < mem_properties.memoryTypeCount; ++i) {
if ((memory_type_bits & (0x1u << i)) != 0) {
if ((mem_properties.memoryTypes[i].propertyFlags & aims) == aims) {
*memory_type_out = i;
return true;
}
}
}
return false;
}
bool VgfRepr::init_timestamp_queries() {
const char* enable = std::getenv("EXECUTORCH_VGF_ENABLE_TIMESTAMP_QUERIES");
if (enable == nullptr || enable[0] == '\0') {
ET_LOG(Info, "VGF timestamp queries disabled");
return true;
}
if (timestamp_queries_enabled || vk_timestamp_query_pool != VK_NULL_HANDLE) {
return true;
}
if (vk_queue_family_index == UINT32_MAX) {
ET_LOG(Info, "VGF timestamp queries disabled: unknown queue family index");
return true;
}
uint32_t queue_family_count = 0;
vkGetPhysicalDeviceQueueFamilyProperties(
vk_physical, &queue_family_count, nullptr);
if (vk_queue_family_index >= queue_family_count) {
ET_LOG(
Info,
"VGF timestamp queries disabled: queue family index %u is out of range",
vk_queue_family_index);
return true;
}
vector<VkQueueFamilyProperties> queue_family_properties(queue_family_count);
vkGetPhysicalDeviceQueueFamilyProperties(
vk_physical, &queue_family_count, queue_family_properties.data());
timestamp_valid_bits =
queue_family_properties[vk_queue_family_index].timestampValidBits;
if (timestamp_valid_bits == 0) {
ET_LOG(
Info,
"VGF timestamp queries disabled: queue family %u does not support timestamps",
vk_queue_family_index);
return true;
}
VkPhysicalDeviceProperties physical_device_properties;
vkGetPhysicalDeviceProperties(vk_physical, &physical_device_properties);
timestamp_period_ns =
static_cast<double>(physical_device_properties.limits.timestampPeriod);
if (timestamp_period_ns <= 0.0) {
ET_LOG(
Info,
"VGF timestampPeriod is %.6f; using fallback 52.0 ns/tick",
timestamp_period_ns);
timestamp_period_ns = 52.0;
}
VkQueryPoolCreateInfo query_pool_info{
.sType = VK_STRUCTURE_TYPE_QUERY_POOL_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.queryType = VK_QUERY_TYPE_TIMESTAMP,
.queryCount = 2,
.pipelineStatistics = 0,
};
VkResult result = vkCreateQueryPool(
vk_device, &query_pool_info, nullptr, &vk_timestamp_query_pool);
if (result != VK_SUCCESS) {
ET_LOG(
Info,
"VGF timestamp queries disabled: vkCreateQueryPool failed with %d",
result);
vk_timestamp_query_pool = VK_NULL_HANDLE;
return true;
}
timestamp_queries_enabled = true;
ET_LOG(
Info,
"VGF timestamp queries enabled: queue_family=%u valid_bits=%u period_ns=%.6f",
vk_queue_family_index,
timestamp_valid_bits,
timestamp_period_ns);
return true;
}
void VgfRepr::read_timestamp_queries(
executorch::runtime::EventTracer* event_tracer) {
if (!timestamp_queries_enabled || vk_timestamp_query_pool == VK_NULL_HANDLE) {
return;
}
uint64_t timestamps[2] = {0, 0};
VkResult result;
{
VGF_PROFILE_SCOPE(event_tracer, "VGF_TIMESTAMP_QUERY_READBACK");
result = vkGetQueryPoolResults(
vk_device,
vk_timestamp_query_pool,
0,
2,
sizeof(timestamps),
timestamps,
sizeof(uint64_t),
VK_QUERY_RESULT_64_BIT | VK_QUERY_RESULT_WAIT_BIT);
}
if (result != VK_SUCCESS) {
ET_LOG(Error, "Failed to read VGF timestamp query results: %d", result);
return;
}
uint64_t start = timestamps[0];
uint64_t end = timestamps[1];
uint64_t mask = std::numeric_limits<uint64_t>::max();
if (timestamp_valid_bits < 64) {
mask = (1ULL << timestamp_valid_bits) - 1ULL;
start &= mask;
end &= mask;
}
uint64_t delta_ticks;
if (end >= start) {
delta_ticks = end - start;
} else {
delta_ticks = (mask - start) + end + 1ULL;
}
const double duration_ns =
static_cast<double>(delta_ticks) * timestamp_period_ns;
const double duration_ms = duration_ns / 1000000.0;
ET_LOG(
Info,
"VGF_DATA_GRAPH_DEVICE_TIME ticks=%llu duration_ns=%.3f duration_ms=%.6f",
static_cast<unsigned long long>(delta_ticks),
duration_ns,
duration_ms);
}
static bool find_memory_index(
VkPhysicalDevice vk_physical,
VkMemoryRequirements2 memory_requirements,
VkMemoryPropertyFlags aims,
uint32_t* memory_type_out) {
return find_memory_index_from_bits(
vk_physical,
memory_requirements.memoryRequirements.memoryTypeBits,
aims,
memory_type_out);
}
bool VgfRepr::map_persistent_io_memory() {
unmap_persistent_io_memory();
for (auto& io : IOs) {
if (io.memory == VK_NULL_HANDLE) {
ET_LOG(Error, "Cannot persistently map null Vulkan IO memory");
unmap_persistent_io_memory();
return false;
}
void* persistent_memory = nullptr;
// IO resources may alias the same VkDeviceMemory. Vulkan memory must not be
// mapped more than once at the same time, so map each unique memory once
// and share the returned pointer across aliased IO entries.
// Make sure that memory is HOST_VISIBLE and HOST_COHERENT.
bool found_existing_mapping = false;
auto mapped_memory_it = std::find_if(
persistent_mapped_memories.begin(),
persistent_mapped_memories.end(),
[&](const auto& mapped_memory) {
return mapped_memory.memory == io.memory;
});
if (mapped_memory_it != persistent_mapped_memories.end()) {
persistent_memory = mapped_memory_it->data;
found_existing_mapping = true;
}
if (!found_existing_mapping) {
VkResult result = vkMapMemory(
vk_device, io.memory, 0, VK_WHOLE_SIZE, 0, &persistent_memory);
if (result != VK_SUCCESS) {
ET_LOG(
Error,
"Failed to persistently map Vulkan IO memory, error %d",
result);
unmap_persistent_io_memory();
return false;
}
persistent_mapped_memories.push_back(PersistentMappedMemory{
.memory = io.memory,
.data = persistent_memory,
});
}
io.persistent_memory = persistent_memory;
}
return true;
}
void VgfRepr::unmap_persistent_io_memory() {
for (const auto& mapped_memory : persistent_mapped_memories) {
if (mapped_memory.memory != VK_NULL_HANDLE &&
mapped_memory.data != nullptr) {
vkUnmapMemory(vk_device, mapped_memory.memory);
}
}
persistent_mapped_memories.clear();
for (auto& io : IOs) {
io.persistent_memory = nullptr;
}
}
VkResult allocate_memory(
VkPhysicalDevice physical,
VkDevice device,
VkMemoryRequirements2 memory_requirements,
VkMemoryPropertyFlags aims,
VkDeviceMemory* memory,
uint32_t* memory_type_index_out = nullptr) {
uint32_t memory_index = 0;
if (!find_memory_index(physical, memory_requirements, aims, &memory_index)) {
ET_LOG(
Error,
"Failed to find compatible Vulkan memory type for aims 0x%x",
static_cast<unsigned int>(aims));
return VK_ERROR_FEATURE_NOT_PRESENT;
}
const VkMemoryAllocateInfo allocate_info = {
.sType = VK_STRUCTURE_TYPE_MEMORY_ALLOCATE_INFO,
.pNext = nullptr,
.allocationSize = memory_requirements.memoryRequirements.size,
.memoryTypeIndex = memory_index,
};
VkResult result = vkAllocateMemory(device, &allocate_info, nullptr, memory);
if (result == VK_SUCCESS && memory_type_index_out != nullptr) {
*memory_type_index_out = memory_index;
}
return result;
}
VkResult create_tensor_unbound(
VkDevice device,
VkFormat format,
uint32_t shape_size,
const int64_t* shape,
uint32_t stride_size,
const int64_t* strides,
VkTensorDescriptionARM* description,
VkTensorARM* tensor,
VkMemoryRequirements2* memory_requirements) {
*description = VkTensorDescriptionARM{
.sType = VK_STRUCTURE_TYPE_TENSOR_DESCRIPTION_ARM,
.pNext = nullptr,
.tiling = VK_TENSOR_TILING_LINEAR_ARM,
.format = format,
.dimensionCount = shape_size,
.pDimensions = shape,
.pStrides = (0 == stride_size ? nullptr : strides),
.usage = VK_TENSOR_USAGE_SHADER_BIT_ARM |
VK_TENSOR_USAGE_TRANSFER_SRC_BIT_ARM |
VK_TENSOR_USAGE_TRANSFER_DST_BIT_ARM |
VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM,
};
const VkTensorCreateInfoARM create_info = {
.sType = VK_STRUCTURE_TYPE_TENSOR_CREATE_INFO_ARM,
.pNext = nullptr,
.flags = 0,
.pDescription = description,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
};
VkResult result = vkCreateTensorARM(device, &create_info, nullptr, tensor);
if (result != VK_SUCCESS) {
ET_LOG(Error, "Failed to CreateTensor, error %d", result);
return result;
}
const VkTensorMemoryRequirementsInfoARM memory_requirements_info = {
.sType = VK_STRUCTURE_TYPE_TENSOR_MEMORY_REQUIREMENTS_INFO_ARM,
.pNext = nullptr,
.tensor = *tensor,
};
*memory_requirements = VkMemoryRequirements2{
.sType = VK_STRUCTURE_TYPE_MEMORY_REQUIREMENTS_2,
.pNext = nullptr,
};
vkGetTensorMemoryRequirementsARM(
device, &memory_requirements_info, memory_requirements);
return VK_SUCCESS;
}
VkTensorDescriptionARM make_data_graph_descriptor(
VkFormat format,
uint32_t shape_size,
const int64_t* shape,
uint32_t stride_size,
const int64_t* strides) {
return VkTensorDescriptionARM{
.sType = VK_STRUCTURE_TYPE_TENSOR_DESCRIPTION_ARM,
.pNext = nullptr,
.tiling = VK_TENSOR_TILING_LINEAR_ARM,
.format = format,
.dimensionCount = shape_size,
.pDimensions = shape,
.pStrides = (0 == stride_size ? nullptr : strides),
.usage = VK_TENSOR_USAGE_SHADER_BIT_ARM |
VK_TENSOR_USAGE_TRANSFER_SRC_BIT_ARM |
VK_TENSOR_USAGE_TRANSFER_DST_BIT_ARM |
VK_TENSOR_USAGE_DATA_GRAPH_BIT_ARM,
};
}
VkResult bind_tensor_memory_and_create_view(
VkDevice device,
VkFormat format,
VkTensorARM tensor,
VkDeviceMemory memory,
VkTensorViewARM* tensor_view) {
const VkBindTensorMemoryInfoARM bind_info = {
.sType = VK_STRUCTURE_TYPE_BIND_TENSOR_MEMORY_INFO_ARM,
.pNext = nullptr,
.tensor = tensor,
.memory = memory,
.memoryOffset = 0,
};
VkResult result = vkBindTensorMemoryARM(device, 1, &bind_info);
if (result != VK_SUCCESS) {
ET_LOG(Error, "Failed to bind tensor memory, error %d", result);
return result;
}
VkTensorViewCreateInfoARM tensor_view_info = {
.sType = VK_STRUCTURE_TYPE_TENSOR_VIEW_CREATE_INFO_ARM,
.pNext = nullptr,
.flags = 0,
.tensor = tensor,
.format = format,
};
return vkCreateTensorViewARM(device, &tensor_view_info, nullptr, tensor_view);
}
VkResult create_buffer_unbound(
VkDevice device,
VkDeviceSize size,
VkBufferUsageFlags usage,
VkBuffer* buffer,
VkMemoryRequirements2* memory_requirements) {
VkBufferCreateInfo buffer_info = {
.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO,
.pNext = nullptr,
.flags = 0,
.size = size,
.usage = usage,
.sharingMode = VK_SHARING_MODE_EXCLUSIVE,
.queueFamilyIndexCount = 0,
.pQueueFamilyIndices = nullptr,
};
VkResult result = vkCreateBuffer(device, &buffer_info, nullptr, buffer);
if (result != VK_SUCCESS) {
ET_LOG(Error, "Failed to create buffer, error %d", result);