-
Notifications
You must be signed in to change notification settings - Fork 4
/
Onnx2Text.cpp
3882 lines (3465 loc) · 160 KB
/
Onnx2Text.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#define _SILENCE_CXX17_ITERATOR_BASE_CLASS_DEPRECATION_WARNING 1 // For Google Protobuf using std::iterator as a base class in C++17.
#define _SILENCE_CXX17_CODECVT_HEADER_DEPRECATION_WARNING 1
#define _SILENCE_CXX20_IS_POD_DEPRECATION_WARNING 1 // For Google Protobuf std::is_pod in generated_message_table_driven.h.
#define _SILENCE_STDEXT_HASH_DEPRECATION_WARNINGS // For Google Protobuf: error C1189: #error: <hash_map> is deprecated
#define _SILENCE_CXX23_DENORM_DEPRECATION_WARNING // For Google Protobuf: Warning C4996: 'std::float_denorm_style': warning STL4042: std::float_denorm_style, std::numeric_limits::has_denorm, and std::numeric_limits::has_denorm_loss are deprecated in C++23. Y
#define NOMINMAX
#include <iostream>
#include <fstream>
#include <sstream>
#include <string_view>
#include <filesystem>
#include <algorithm>
#include <numeric>
#include <codecvt>
#include <charconv>
#include <random>
#include <hash_map> // For Google Protobuf: std::hash_compare is not defined.
#pragma warning(push)
#pragma warning(disable: 4146) // unary minus operator applied to unsigned type, result still unsigned
#pragma warning(disable: 4125) // decimal digit terminates octal escape sequence
#pragma warning(disable: 5054 ) // deprecated between enumerations of different types
#ifdef __clang__
#define GOOGLE_PROTOBUF_MISSING_HASH // For Google Protobuf hash.h with clang (protobuf-3.5.1\src\google\protobuf\stubs\hash.h).
#endif
#include "onnx.pb.h"
#include "google/protobuf/text_format.h"
#include "google/protobuf/any.pb.h"
#include "google/protobuf/io/zero_copy_stream.h"
#include "google/protobuf/io/zero_copy_stream_impl.h"
#pragma warning(pop)
// Disable useless warnings.
#pragma warning(disable: 4100) // unreferenced formal parameter - yeah, it's intentional
#include "half/half.hpp"
#ifdef _WIN32
#include <wrl/client.h>
#include <wincodec.h>
#endif
// Float16 support.
using float16 = half_float::half;
// Truncated IEEE 32-bit floating type to 16-bits (so called "brain float").
struct float16m7e8s1_t
{
float16m7e8s1_t() = default;
float16m7e8s1_t(const float16m7e8s1_t&) = default;
float16m7e8s1_t(float16m7e8s1_t&&) = default;
float16m7e8s1_t(float floatValue) noexcept
{
value = reinterpret_cast<uint32_t&>(floatValue) >> 16;
}
float16m7e8s1_t& operator =(const float16m7e8s1_t&) = default;
inline float16m7e8s1_t& operator =(float floatValue) noexcept
{
new(this) float16m7e8s1_t(floatValue);
return *this;
}
operator float() const noexcept
{
float floatValue = 0.0;
reinterpret_cast<uint32_t&>(floatValue) = value << 16;
return floatValue;
}
uint16_t value;
};
// String helpers
inline char ToChar(std::byte c) { return static_cast<char>(c); }
inline char* ToChar(std::byte* p) { return reinterpret_cast<char*>(p); }
inline char const* ToChar(std::byte const* p) { return reinterpret_cast<char const*>(p); }
inline char ToChar(char8_t c) { return static_cast<char>(c); }
inline char* ToChar(char8_t* p) { return reinterpret_cast<char*>(p); }
inline char const* ToChar(char8_t const* const p) { return reinterpret_cast<char const* const>(p); }
inline char** ToChar(char8_t** p) { return reinterpret_cast<char**>(p); }
inline char* const* ToChar(char8_t* const* const p) { return reinterpret_cast<char* const* const>(p); }
inline char const* const* ToChar(char8_t const* const* const p) { return reinterpret_cast<char const* const* const>(p); }
inline unsigned char* ToUChar(char* p) { return reinterpret_cast<unsigned char*>(p); }
inline unsigned char* ToUChar(char8_t* p) { return reinterpret_cast<unsigned char*>(p); }
inline unsigned char* ToUChar(std::byte* p) { return reinterpret_cast<unsigned char*>(p); }
inline char8_t* ToUtf8Char(char* p) { return reinterpret_cast<char8_t*>(p); }
inline std::u8string_view ToUtf8Char(std::string_view s) { return std::u8string_view(reinterpret_cast<char8_t const*>(s.data()), s.size()); }
inline std::string_view ToChar(std::u8string_view s) { return std::string_view(reinterpret_cast<char const*>(s.data()), s.size()); }
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>, wchar_t> g_converterToUtf8;
inline std::u8string ToUtf8String(std::wstring_view source)
{
static_assert(sizeof(wchar_t) == sizeof(char16_t), "Doesn't work on Linux, expecting UTF-16 for wchar_t.");
std::u8string dest;
std::string temporary = g_converterToUtf8.to_bytes(source.data(), source.data() + source.size());
dest = std::move(*reinterpret_cast<std::u8string const*>(&temporary));
return dest;
}
inline std::u8string ToUtf8String(std::u16string_view source)
{
static_assert(sizeof(wchar_t) == sizeof(char16_t), "Doesn't work on Linux, expecting UTF-16 for wchar_t.");
std::u8string dest;
std::string temporary = g_converterToUtf8.to_bytes(
reinterpret_cast<wchar_t const*>(source.data()),
reinterpret_cast<wchar_t const*>(source.data() + source.size())
);
dest = std::move(*reinterpret_cast<std::u8string const*>(&temporary));
return dest;
}
inline std::u16string ToUtf16String(std::u8string_view source)
{
std::u16string dest;
std::wstring temporary = g_converterToUtf8.from_bytes(ToChar(source.data()), ToChar(source.data() + source.size()));
dest = std::move(*reinterpret_cast<std::u16string const*>(&temporary));
return dest;
}
#ifdef _WIN32
extern "C"
{
HRESULT WINAPI WICCreateImagingFactory_Proxy(
__in UINT SDKVersion,
__deref_out IWICImagingFactory** IWICImagingFactory
);
}
using Microsoft::WRL::ComPtr;
void ThrowBadHResultRuntimeErrorWithMessage(HRESULT hr)
{
std::string result;
std::stringstream stream;
stream << "Failing HRESULT: 0x" << std::hex << hr;
stream.str(/*out*/ result);
throw std::runtime_error(result.c_str());
}
#ifndef THROW_IF_FAILED
#define THROW_IF_FAILED(hr) {HRESULT localHr = (hr); if (FAILED(localHr)) ThrowBadHResultRuntimeErrorWithMessage(localHr);}
#endif
#endif // _WIN32
////////////////////////////////////////////////////////////////////////////////
template <typename T>
class span
{
public:
span() = default;
constexpr span(span<T>& s) = default;
template<typename ContiguousContainerType>
constexpr span(ContiguousContainerType&& container)
: begin_(std::data(container)),
end_(begin_ + std::size(container))
{
}
constexpr span(std::initializer_list<T> i)
: begin_(std::data(i)),
end_(begin_ + std::size(i))
{
}
span(T* begin, T* end)
: begin_(begin),
end_(end)
{
}
span(T* begin, size_t elementCount)
: begin_(begin),
end_(begin + elementCount)
{
}
T* data() noexcept { return begin_; }
T* begin() noexcept { return begin_; }
T* end() noexcept { return end_; }
T const* data() const noexcept { return begin_; }
T const* begin() const noexcept { return begin_; }
T const* end() const noexcept { return end_; }
bool empty() const noexcept { return end_ == begin_; }
size_t size() const noexcept { return end_ - begin_; }
size_t size_bytes() const noexcept { return sizeof(T) * size(); }
T& operator[](size_t index) const noexcept { return begin_[index]; }
span<T> subspan(size_t index, size_t count) const noexcept { return span<T>(begin_ + index, begin_ + index + count); }
span<T> subrange(size_t begin, size_t end) const noexcept { return span<T>(begin_ + begin, begin_ + end); }
span<T> first(size_t count) const noexcept { return span<T>(begin_, begin_ + count); }
span<T> last(size_t count) const noexcept { return span<T>(end_ - count, end_); }
T& front() noexcept { return *begin_; }
T& back() noexcept { return *(end_ - 1); }
T const& front() const noexcept { return *begin_; }
T const& back() const noexcept { return *(end_ - 1); }
T consume_front() noexcept { return *begin_++; }
T consume_back() noexcept { return *--end_; }
void pop_front() noexcept { ++begin_; }
void pop_back() noexcept { --end_; }
void pop_front(size_t n) noexcept { begin_ += n; }
void pop_back(size_t n) noexcept { end_ -= n; }
protected:
T* begin_ = nullptr;
T* end_ = nullptr;
};
template<
typename ContiguousContainerType,
typename ElementType = std::remove_reference_t<decltype(*std::declval<ContiguousContainerType>().data())>
>
auto make_span(ContiguousContainerType& container) -> span<ElementType>
{
auto* begin = std::data(container);
return span<ElementType>(begin, begin + std::size(container));
}
template<typename ContiguousContainerType>
span<const std::byte> as_bytes(ContiguousContainerType const& container)
requires (std::is_const_v<std::remove_pointer_t<decltype(container.data())>>)
{
auto oldSpan = make_span(container);
return span<const std::byte>(reinterpret_cast<const std::byte*>(oldSpan.data()), oldSpan.size_bytes());
}
template<typename ContiguousContainerType>
span<std::byte> as_bytes(ContiguousContainerType& container)
requires (!std::is_const_v<std::remove_pointer_t<decltype(container.data())>>)
{
auto oldSpan = make_span(container);
return span<std::byte>(reinterpret_cast<std::byte*>(oldSpan.data()), oldSpan.size_bytes());
}
template<typename T>
span<const std::byte> struct_as_bytes(T const& data)
requires (std::is_const_v<decltype(data)>)
{
return span<const std::byte>(reinterpret_cast<const std::byte*>(std::addressof(data)), sizeof(data));
}
template<typename T>
span<std::byte> struct_as_bytes(T const& data)
requires (!std::is_const_v<decltype(data)>)
{
return span<std::byte>(reinterpret_cast<const std::byte*>(std::addressof(data)), sizeof(data));
}
template<typename T>
struct HalfOpenRange
{
static_assert(std::is_trivial<T>::value);
T begin;
T end;
constexpr HalfOpenRange() noexcept : begin(static_cast<T>(0)), end(static_cast<T>(0)) {}
constexpr HalfOpenRange(T initialValue) noexcept : begin(initialValue), end(initialValue) {}
constexpr HalfOpenRange(T initialBegin, T initialEnd) noexcept : begin(initialBegin), end(initialEnd) {}
static HalfOpenRange None() { return { static_cast<T>(0), static_cast<T>(0) }; }
static HalfOpenRange All() { return {std::numeric_limits<T>::min(), std::numeric_limits<T>::max()}; }
bool IsEmpty() const noexcept { return begin == end; }
bool empty() const noexcept { return IsEmpty(); }
bool Contains(T value) const noexcept { return value >= begin && value < end; }
bool Contains(HalfOpenRange const& other) const noexcept { return other.begin >= begin && other.end <= end;}
void ExpandAllIfEmpty() noexcept
{
if (begin == end)
{
*this = All();
}
}
};
using HalfOpenRangeUint32 = HalfOpenRange<uint32_t>;
// Reinterprets a span of data from one type to another.
// The input parameter can be any contiguous container with data() and size() methods,
// including gsl::span, std::array, and std::vector.
template <typename NewType, typename OldTypeContainer>
span<NewType> reinterpret_span(OldTypeContainer& oldSpan)
{
using OldType = decltype(*oldSpan.data());
size_t newElementCount = static_cast<size_t>(oldSpan.size()) * sizeof(OldType) / sizeof(NewType);
assert(newElementCount * sizeof(NewType) == oldSpan.size() * sizeof(OldType));
NewType* p = reinterpret_cast<NewType*>(oldSpan.data());
return span<NewType>(p, p + newElementCount);
}
template <typename ContainerType>
auto clamped_span(ContainerType& oldSpan, size_t offset, size_t count) -> span<decltype(*oldSpan.data())>
{
using NewType = decltype(*oldSpan.data());
size_t endOffset = offset + count;
size_t maxOffset = oldSpan.size();
size_t beginOffset = std::min(offset, maxOffset);
endOffset = (endOffset > maxOffset || endOffset < offset) ? maxOffset : endOffset;
auto* p = oldSpan.data();
return span<NewType>(p + beginOffset, p + endOffset);
}
// Reads a byte array from std::vector/std::string/std::array as a struct.
template <typename NewStructType, typename OldTypeContainer>
const NewStructType& read_as(OldTypeContainer&& oldSpan)
requires requires {std::data(oldSpan); std::size(oldSpan);}
{
span<const std::byte> byteSpan = as_bytes(oldSpan);
size_t byteSize = byteSpan.size_bytes();
if (sizeof(NewStructType) > byteSize)
{
throw std::runtime_error("Span is too small to be cast to new data type.");
}
return *reinterpret_cast<const NewStructType*>(byteSpan.data());
}
// Why? How? How are basic functions like this missing from the standard library?
template <typename ContainerType1, typename ContainerType2>
bool equals(ContainerType1&& c1, ContainerType2&& c2)
{
return std::equal(c1.begin(), c1.end(), c2.begin(), c2.end());
}
// e.g. starts_with(some_string_view, "prefix");
template <typename ContainerType1, typename ContainerType2>
bool starts_with(ContainerType1&& fullSequence, ContainerType2&& prefix)
{
return fullSequence.size() >= prefix.size()
&& std::equal(fullSequence.begin(), fullSequence.begin() + prefix.size(), prefix.begin(), prefix.end());
}
// e.g. ends_with(some_string_view, "suffix");
template <typename ContainerType1, typename ContainerType2>
bool ends_with(ContainerType1&& fullSequence, ContainerType2&& suffix)
{
return fullSequence.size() >= suffix.size()
&& std::equal(fullSequence.end() - + suffix.size(), fullSequence.end(), suffix.begin(), suffix.end());
}
template <typename ContainerType>
auto find(ContainerType&& container, decltype(*container.data())&& value) -> decltype(container.begin())
{
return std::find(container.begin(), container.end(), value);
}
template<
typename ContiguousContainerType,
typename ElementType = std::remove_reference_t<decltype(*std::declval<ContiguousContainerType>().data())>
>
auto append_data(ContiguousContainerType& v, span<ElementType const> s)
{
// Whyyyy is basic functionality like std::vector::append() missing from the standard? -_-
// Thankfully C++23 adds append_range!
v.insert(v.end(), s.begin(), s.end());
}
template <typename ContainerType>
auto tokenize(
ContainerType&& container,
std::remove_reference_t<decltype(*container.data())> divider
) -> std::vector<span< std::remove_reference_t<decltype(*container.data())> >>
{
using ElementType = std::remove_reference_t<decltype(*container.data())>;
std::vector<span<ElementType>> v;
for (auto i = container.begin(), end = container.end(); i != end; )
{
auto next = std::find(i, container.end(), divider);
v.push_back(span<ElementType>(&*i, &*next));
if (next != end)
{
++next;
}
i = next;
}
return v;
}
template<typename OutputType, typename InputType> OutputType clamp_cast(InputType input)
{
// Determine the larger type to decide which numeric limits to clamp to.
using InputLimits = std::numeric_limits<InputType>;
using OutputLimits = std::numeric_limits<OutputType>;
constexpr int inputMaxDigits = std::max(InputLimits::max_exponent, InputLimits::digits);
constexpr int outputMaxDigits = std::max(OutputLimits::max_exponent, OutputLimits::digits);
constexpr bool isEitherTypeUnsigned = std::is_unsigned_v<InputType> || std::is_unsigned_v<OutputType>;
constexpr bool isOutputTypeLarger = outputMaxDigits > inputMaxDigits;
InputType lowestValue = isEitherTypeUnsigned ? static_cast<InputType>(0) :
isOutputTypeLarger ? InputLimits::lowest() :
static_cast<InputType>(OutputLimits::lowest());
InputType highestValue = isOutputTypeLarger ? InputLimits::max() :
static_cast<InputType>(OutputLimits::max());
return static_cast<OutputType>(std::clamp<InputType>(input, lowestValue, highestValue));
}
// Read the file, calling back to set the size and return a span to the data to write into.
void ReadBinaryFileWithCallback(
wchar_t const* inputFilename,
std::function<span<std::byte>(size_t newSize)> setDataSize
)
{
std::ifstream file(inputFilename, std::ios::binary);
if (!file.is_open())
{
throw std::ios::failure("Could not open input file.");
}
file.seekg(0, std::ios::end);
size_t size = static_cast<size_t>(file.tellg());
file.seekg(0, std::ios::beg);
span<std::byte> s = setDataSize(size);
file.read(ToChar(s.data()), size);
}
template<typename T = std::vector<std::byte>>
T ReadBinaryFile(wchar_t const* inputFilename)
{
T fileData;
ReadBinaryFileWithCallback(
inputFilename,
[&](size_t newSize)
{
fileData.resize(newSize);
return as_bytes(fileData);
}
);
return fileData;
}
void WriteBinaryFileBytes(wchar_t const* outputFilename, span<std::byte const> fileData)
{
// Create any intermediate output path needed.
std::filesystem::path path(outputFilename);
if (path.has_parent_path())
{
path.remove_filename();
// .filename() lies when referring to the root directory, saying there is a filename when
// there actually is not. So instead we check whether the current path equals the root.
std::filesystem::path root = path.root_path();
if (path != root)
{
std::filesystem::create_directory(path);
}
}
std::ofstream file(outputFilename, std::ios::binary);
if (!file.is_open())
{
throw std::ios::failure("Could not open output file.");
}
file.write(ToChar(fileData.data()), fileData.size());
}
template <typename ContainerType>
void WriteBinaryFile(wchar_t const* outputFilename, ContainerType const& fileData)
{
return WriteBinaryFileBytes(outputFilename, as_bytes(fileData));
}
enum class FileType
{
Unknown, // .onnx
OnnxModel, // .onnx
GoogleProtobuf, // .pb
Text, // .txt / .prototxt
CommaSeparatedValue, // .csv
Image, // .png / .jpg
RawData, // .dat / .bin - raw binary, dump of tensor values as-is
NumPyArray, // .npy (not .npz zip files with multiple arrays in them)
OnnxTensor, // .onnxtensor
TensorGenerator, // generator:
GraphVizDot, // .dot
};
size_t GetFileExtensionOffset(std::wstring_view filename)
{
size_t extensionOffset = filename.find_last_of(L".");
extensionOffset = (extensionOffset != std::wstring_view::npos) ? extensionOffset + 1 : filename.size();
return extensionOffset;
}
struct Mapping
{
std::wstring_view filenameExtension;
FileType fileType;
};
const static Mapping fileTypeMappings[] =
{
{ L"pb", FileType::GoogleProtobuf },
{ L"onnx", FileType::OnnxModel },
{ L"txt" , FileType::Text },
{ L"prototxt" , FileType::Text },
{ L"csv" , FileType::CommaSeparatedValue },
{ L"dat" , FileType::RawData },
{ L"bin" , FileType::RawData },
{ L"bmp" , FileType::Image },
{ L"png" , FileType::Image },
{ L"jpg" , FileType::Image },
{ L"jpeg", FileType::Image },
{ L"npy" , FileType::NumPyArray },
{ L"onnxtensor", FileType::OnnxTensor },
{ L"tensorproto", FileType::OnnxTensor },
{ L"dot", FileType::GraphVizDot },
};
FileType GetFileType(std::wstring_view filename)
{
size_t extensionOffset = GetFileExtensionOffset(filename);
std::wstring_view filenameExtension = filename.substr(extensionOffset);
if (starts_with(filename, std::wstring_view(L"generate("))) return FileType::TensorGenerator;
for (auto& mapping : fileTypeMappings)
{
if (filenameExtension == mapping.filenameExtension)
{
return mapping.fileType;
}
}
// Special case for device name on Windows.
if (filename == L"con" || filename == L"con:")
{
return FileType::Text;
}
return FileType::Unknown;
}
size_t GetDataTypeElementByteSize(onnx::TensorProto::DataType dataType)
{
switch (dataType)
{
case onnx::TensorProto::DataType::TensorProto_DataType_BOOL: return 1;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT8: return 1;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT16: return 2;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT32: return 4;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT64: return 8;
case onnx::TensorProto::DataType::TensorProto_DataType_INT8: return 1;
case onnx::TensorProto::DataType::TensorProto_DataType_INT16: return 2;
case onnx::TensorProto::DataType::TensorProto_DataType_INT32: return 4;
case onnx::TensorProto::DataType::TensorProto_DataType_INT64: return 8;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT16: return 2;
case onnx::TensorProto::DataType::TensorProto_DataType_BFLOAT16: return 2;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT: return 4;
case onnx::TensorProto::DataType::TensorProto_DataType_DOUBLE: return 8;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX64: return 8;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX128: return 16;
default: throw std::ios::failure("Unsupported data type in tensor.");
}
}
union ScalarValueUnion
{
double floatValue;
int64_t intValue;
uint64_t uintValue;
};
enum class CsvValueNumberClass
{
Int,
Uint,
Float,
Hex,
};
CsvValueNumberClass GetCsvValueNumberClass(
onnx::TensorProto::DataType dataType,
bool shouldPrintRawBytes
)
{
CsvValueNumberClass valueNumberClass = CsvValueNumberClass::Uint;
switch (dataType)
{
case onnx::TensorProto::DataType::TensorProto_DataType_BOOL: valueNumberClass = CsvValueNumberClass::Uint ; break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT8: valueNumberClass = CsvValueNumberClass::Uint ; break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT16: valueNumberClass = CsvValueNumberClass::Uint ; break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT32: valueNumberClass = CsvValueNumberClass::Uint ; break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT64: valueNumberClass = CsvValueNumberClass::Uint ; break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT8: valueNumberClass = CsvValueNumberClass::Int ; break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT16: valueNumberClass = CsvValueNumberClass::Int ; break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT32: valueNumberClass = CsvValueNumberClass::Int ; break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT64: valueNumberClass = CsvValueNumberClass::Int ; break;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT16: valueNumberClass = CsvValueNumberClass::Float; break;
case onnx::TensorProto::DataType::TensorProto_DataType_BFLOAT16: valueNumberClass = CsvValueNumberClass::Float; break;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT: valueNumberClass = CsvValueNumberClass::Float; break;
case onnx::TensorProto::DataType::TensorProto_DataType_DOUBLE: valueNumberClass = CsvValueNumberClass::Float; break;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX64: valueNumberClass = CsvValueNumberClass::Float; break;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX128: valueNumberClass = CsvValueNumberClass::Float; break;
default: throw std::ios::failure("Unsupported data type in tensor for CSV output.");
}
// For printing raw hex, always print as hex digits regardless of actual data type.
if (shouldPrintRawBytes)
{
valueNumberClass = CsvValueNumberClass::Hex;
}
return valueNumberClass;
}
void WriteTensorValue(
void* data, // Must point to memory that has at least the number of bytes specified by the dataType.
onnx::TensorProto::DataType dataType,
ScalarValueUnion value
)
{
switch (dataType)
{
case onnx::TensorProto::DataType::TensorProto_DataType_BOOL: *reinterpret_cast<bool*> (data) = static_cast<bool> (value.uintValue ); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT8: *reinterpret_cast<uint8_t*> (data) = static_cast<uint8_t> (value.uintValue ); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT16: *reinterpret_cast<uint16_t*>(data) = static_cast<uint16_t>(value.uintValue ); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT32: *reinterpret_cast<uint32_t*>(data) = static_cast<uint32_t>(value.uintValue ); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT64: *reinterpret_cast<uint64_t*>(data) = static_cast<uint64_t>(value.uintValue ); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT8: *reinterpret_cast<int8_t*> (data) = static_cast<int8_t> (value.intValue ); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT16: *reinterpret_cast<int16_t*> (data) = static_cast<int16_t> (value.intValue ); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT32: *reinterpret_cast<int32_t*> (data) = static_cast<int32_t> (value.intValue ); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT64: *reinterpret_cast<int64_t*> (data) = static_cast<int64_t> (value.intValue ); break;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT16: *reinterpret_cast<float16*> (data) = static_cast<float> (value.floatValue); break;
case onnx::TensorProto::DataType::TensorProto_DataType_BFLOAT16: *reinterpret_cast<float16m7e8s1_t*>(data) = static_cast<float>(value.floatValue); break;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT: *reinterpret_cast<float*> (data) = static_cast<float> (value.floatValue); break;
case onnx::TensorProto::DataType::TensorProto_DataType_DOUBLE: *reinterpret_cast<double*> (data) = static_cast<double> (value.floatValue); break;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX64: *reinterpret_cast<float*> (data) = static_cast<float> (value.floatValue); break;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX128: *reinterpret_cast<double*> (data) = static_cast<double> (value.floatValue); break;
default: throw std::ios::failure("Unsupported data type for tensor.");
}
}
void WriteTensorValueFloat64(
/*out*/ void* data, // Must point to memory that has at least the number of bytes specified by the dataType.
onnx::TensorProto::DataType dataType,
double value
)
{
switch (dataType)
{
case onnx::TensorProto::DataType::TensorProto_DataType_BOOL: *reinterpret_cast<bool*> (data) = static_cast<bool> (value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT8: *reinterpret_cast<uint8_t*> (data) = static_cast<uint8_t> (value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT16: *reinterpret_cast<uint16_t*>(data) = static_cast<uint16_t>(value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT32: *reinterpret_cast<uint32_t*>(data) = static_cast<uint32_t>(value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT64: *reinterpret_cast<uint64_t*>(data) = static_cast<uint64_t>(value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT8: *reinterpret_cast<int8_t*> (data) = static_cast<int8_t> (value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT16: *reinterpret_cast<int16_t*> (data) = static_cast<int16_t> (value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT32: *reinterpret_cast<int32_t*> (data) = static_cast<int32_t> (value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT64: *reinterpret_cast<int64_t*> (data) = static_cast<int64_t> (value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT16: *reinterpret_cast<float16*> (data) = static_cast<float> (value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_BFLOAT16: *reinterpret_cast<float16m7e8s1_t*>(data) = static_cast<float>(value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT: *reinterpret_cast<float*> (data) = static_cast<float> (value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_DOUBLE: *reinterpret_cast<double*> (data) = static_cast<double> (value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX64: *reinterpret_cast<float*> (data) = static_cast<float> (value); break;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX128: *reinterpret_cast<double*> (data) = static_cast<double> (value); break;
default: throw std::ios::failure("Unsupported data type for tensor.");
}
}
ScalarValueUnion ReadTensorValue(
void const* data, // Must point to memory that has at least the number of bytes specified by the dataType.
onnx::TensorProto::DataType dataType
)
{
ScalarValueUnion value;
switch (dataType)
{
case onnx::TensorProto::DataType::TensorProto_DataType_BOOL: value.uintValue = *reinterpret_cast<const bool*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT8: value.uintValue = *reinterpret_cast<const uint8_t*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT16: value.uintValue = *reinterpret_cast<const uint16_t*>(data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT32: value.uintValue = *reinterpret_cast<const uint32_t*>(data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT64: value.uintValue = *reinterpret_cast<const uint64_t*>(data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT8: value.intValue = *reinterpret_cast<const int8_t*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT16: value.intValue = *reinterpret_cast<const int16_t*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT32: value.intValue = *reinterpret_cast<const int32_t*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT64: value.intValue = *reinterpret_cast<const int64_t*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT16: value.floatValue = *reinterpret_cast<const float16*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_BFLOAT16: value.floatValue = *reinterpret_cast<const float16m7e8s1_t*>(data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT: value.floatValue = *reinterpret_cast<const float*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_DOUBLE: value.floatValue = *reinterpret_cast<const double*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX64: value.floatValue = *reinterpret_cast<const float*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX128: value.floatValue = *reinterpret_cast<const double*> (data); break;
default: throw std::ios::failure("Unsupported data type for tensor.");
}
return value;
}
double ReadTensorValueFloat64(
void const* data, // Must point to memory that has at least the number of bytes specified by the dataType.
onnx::TensorProto::DataType dataType
)
{
double value;
switch (dataType)
{
case onnx::TensorProto::DataType::TensorProto_DataType_BOOL: value = *reinterpret_cast<const bool*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT8: value = *reinterpret_cast<const uint8_t*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT16: value = *reinterpret_cast<const uint16_t*>(data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT32: value = *reinterpret_cast<const uint32_t*>(data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT64: value = double(*reinterpret_cast<const uint64_t*>(data)); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT8: value = *reinterpret_cast<const int8_t*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT16: value = *reinterpret_cast<const int16_t*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT32: value = *reinterpret_cast<const int32_t*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_INT64: value = double(*reinterpret_cast<const int64_t*> (data)); break;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT16: value = *reinterpret_cast<const float16*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_BFLOAT16: value = *reinterpret_cast<const float16m7e8s1_t*>(data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT: value = *reinterpret_cast<const float*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_DOUBLE: value = *reinterpret_cast<const double*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX64: value = *reinterpret_cast<const float*> (data); break;
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX128: value = *reinterpret_cast<const double*> (data); break;
default: throw std::ios::failure("Unsupported data type for tensor.");
}
return value;
}
void WriteTensorValues(
/*out*/ span<std::byte> arrayByteData,
onnx::TensorProto::DataType dataType,
ScalarValueUnion value
)
{
const size_t elementByteSize = GetDataTypeElementByteSize(dataType);
if (elementByteSize == 0)
{
return;
}
size_t alignedByteCount = arrayByteData.size_bytes() / elementByteSize * elementByteSize;
for (size_t i = 0; i < alignedByteCount; i += elementByteSize)
{
WriteTensorValue(/*out*/ &arrayByteData[i], dataType, value);
}
}
void WriteTensorValues(
/*out*/ span<std::byte> arrayByteData,
onnx::TensorProto::DataType dataType,
std::function<ScalarValueUnion()> valueGetter
)
{
const size_t elementByteSize = GetDataTypeElementByteSize(dataType);
if (elementByteSize == 0)
{
return;
}
size_t alignedByteCount = arrayByteData.size_bytes() / elementByteSize * elementByteSize;
for (size_t i = 0; i < alignedByteCount; i += elementByteSize)
{
ScalarValueUnion value = valueGetter();
WriteTensorValue(/*out*/ &arrayByteData[i], dataType, value);
}
}
void ReadCsv(
std::u8string_view text,
onnx::TensorProto::DataType dataType,
HalfOpenRangeUint32 rowRange,
HalfOpenRangeUint32 columnRange,
/*out*/std::vector<std::byte>& byteData
)
{
byteData.clear();
rowRange.ExpandAllIfEmpty();
columnRange.ExpandAllIfEmpty();
size_t elementByteSize = GetDataTypeElementByteSize(dataType);
size_t byteDataSize = 0;
uint32_t row = 1, column = 1;
std::u8string unquotedText;
CsvValueNumberClass valueNumberClass = GetCsvValueNumberClass(dataType, /*shouldPrintRawBytes*/ false);
constexpr char quote = '\"';
char8_t const* begin = text.data();
char8_t const* end = text.data() + text.size();
while (begin != end)
{
char8_t const* numberStart = begin;
// Skip leading spaces.
while (begin != end && *begin == ' ')
{
++begin;
}
// Read quoted field.
if (begin != end && *begin == quote)
{
unquotedText.clear();
while (++begin != end)
{
auto ch = *begin;
if (ch == quote)
{
++begin; // skip the quote.
if (begin != end && *begin != quote)
{
break; // Found ending quote.
}
}
unquotedText.push_back(ch);
}
numberStart = unquotedText.data();
}
// Write the value to the byte buffer.
if (rowRange.Contains(row) && columnRange.Contains(column))
{
ScalarValueUnion value = {};
// Read the numeric value.
bool shouldReadRawBytes = false;
if (numberStart[0] == '0' && numberStart[1] == 'x')
{
shouldReadRawBytes = true;
std::from_chars(ToChar(numberStart + 2), ToChar(end), /*out*/ value.uintValue);
}
else
{
switch (valueNumberClass)
{
case CsvValueNumberClass::Int: std::from_chars(ToChar(numberStart), ToChar(end), /*out*/ value.intValue); break;
case CsvValueNumberClass::Uint: std::from_chars(ToChar(numberStart), ToChar(end), /*out*/ value.uintValue); break;
case CsvValueNumberClass::Float: std::from_chars(ToChar(numberStart), ToChar(end), /*out*/ value.floatValue); break;
case CsvValueNumberClass::Hex: std::from_chars(ToChar(numberStart), ToChar(end), /*out*/ value.uintValue, 16); break;
}
}
byteData.resize(byteDataSize + elementByteSize);
void* data = &byteData[byteDataSize];
byteDataSize += elementByteSize;
if (shouldReadRawBytes)
{
switch (dataType)
{
case onnx::TensorProto::DataType::TensorProto_DataType_BOOL:
case onnx::TensorProto::DataType::TensorProto_DataType_UINT8:
case onnx::TensorProto::DataType::TensorProto_DataType_INT8:
*reinterpret_cast<uint8_t*> (data) = static_cast<uint8_t>(value.uintValue);
break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT16:
case onnx::TensorProto::DataType::TensorProto_DataType_INT16:
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT16:
case onnx::TensorProto::DataType::TensorProto_DataType_BFLOAT16:
*reinterpret_cast<uint16_t*>(data) = static_cast<uint16_t>(value.uintValue);
break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT32:
case onnx::TensorProto::DataType::TensorProto_DataType_INT32:
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT:
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX64:
*reinterpret_cast<uint32_t*>(data) = static_cast<uint32_t>(value.uintValue);
break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT64:
case onnx::TensorProto::DataType::TensorProto_DataType_INT64:
case onnx::TensorProto::DataType::TensorProto_DataType_DOUBLE:
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX128:
*reinterpret_cast<uint64_t*>(data) = static_cast<uint64_t>(value.uintValue);
break;
default: throw std::ios::failure("Unsupported data type in tensor for CSV input.");
}
}
else
{
WriteTensorValue(/*out*/ data, dataType, value);
}
}
++column;
// Skip any following comma or line return.
for (; begin != end; ++begin)
{
char ch = *begin;
if (ch == ',') // Comma ends value.
{
++begin;
break;
}
if (ch == '\x000A' || ch == '\x000D') // Line feed or carriage return ends value.
{
++begin;
++row;
column = 1;
if (ch == '\x000D' && begin != end && *begin == '\x000A')
{
++begin;
}
break;
}
}
}
}
// Simpler version just for reading command line arguments.
void ReadCsv(std::u8string_view text, /*out*/std::vector<int32_t>& values)
{
values.clear();
const char8_t* begin = text.data();
const char8_t* end = text.data() + text.size();
// Special case of empty dimensions.
if (text == u8"[]" || text == u8"()")
{
return;
}
while (begin != end)
{
char8_t* valueEnd;
uint32_t value = strtol(ToChar(begin), ToChar(&valueEnd), 10);
values.push_back(value);
if (valueEnd != end && *valueEnd == u8',')
{
++valueEnd;
}
begin = valueEnd;
}
}
// Writes tensor data to a string (not directly to a file).
void WriteCsv(
span<std::byte const> byteData,
onnx::TensorProto::DataType dataType,
bool shouldPrintRawBytes, // Print raw hex bit values instead of formatted numbers.
/*out*/std::u8string& text
)
{
text.clear();
size_t elementByteSize = GetDataTypeElementByteSize(dataType);
char8_t buffer[40];
// Round off any potential trailing padding.
byteData = span<std::byte const>(byteData.data(), (byteData.size() / elementByteSize) * elementByteSize);
CsvValueNumberClass valueNumberClass = GetCsvValueNumberClass(dataType, shouldPrintRawBytes);
std::byte const* begin = byteData.data();
std::byte const* end = byteData.data() + byteData.size();
ScalarValueUnion value;
while (begin != end)
{
// Read the next value from the type buffer.
value = {};
void const* data = begin;
begin += elementByteSize;
if (shouldPrintRawBytes)
{
switch (dataType)
{
case onnx::TensorProto::DataType::TensorProto_DataType_BOOL:
case onnx::TensorProto::DataType::TensorProto_DataType_UINT8:
case onnx::TensorProto::DataType::TensorProto_DataType_INT8:
value.uintValue = *reinterpret_cast<const uint8_t*> (data);
break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT16:
case onnx::TensorProto::DataType::TensorProto_DataType_INT16:
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT16:
case onnx::TensorProto::DataType::TensorProto_DataType_BFLOAT16:
value.uintValue = *reinterpret_cast<const uint16_t*>(data);
break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT32:
case onnx::TensorProto::DataType::TensorProto_DataType_INT32:
case onnx::TensorProto::DataType::TensorProto_DataType_FLOAT:
case onnx::TensorProto::DataType::TensorProto_DataType_COMPLEX64:
value.uintValue = *reinterpret_cast<const uint32_t*>(data);
break;
case onnx::TensorProto::DataType::TensorProto_DataType_UINT64: