-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_backend.cpp
More file actions
1615 lines (1414 loc) · 63 KB
/
Copy pathapi_backend.cpp
File metadata and controls
1615 lines (1414 loc) · 63 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 (c) 2026 Advanced Micro Devices, Inc. All rights reserved. */
#include "api_backend.hpp"
// Standard library includes
#include <cstdarg>
#include <deque>
#include <iostream>
#include <string>
#include <string_view>
#include <vector>
#include <memory>
#include <expected>
#include <algorithm>
#include <iterator>
#include <format>
#include <ranges>
#include <span>
#ifdef _WIN32
#define NOMINMAX
#include <windows.h>
#endif
// Core includes (which includes amdmlss_api_cdefs.h)
#include "core/core.hpp"
#include "core/impl/types/verbose_mode.hxx"
// Include shader headers
#include "shaders/shaders.hpp"
#include "shaders/operators/mha.hpp"
#include "shaders/operators/conv.hpp"
#include "shaders/operators/gemm.hpp"
#include "shaders/operators/gemm_gemm.hpp"
#include "shaders/operators/gqa.hpp"
#include "shaders/operators/mvn.hpp"
#include "shaders/operators/qgemm.hpp"
#include "shaders/operators/rmsnorm.hpp"
#include "shaders/operators/sigmoid_mul.hpp"
namespace mlss
{
namespace
{
//=====================================================================================================================
template <class T>
struct NoDeallocation
{
constexpr void operator()(T* ptr)
{
ptr = nullptr;
}
};
//=====================================================================================================================
// Convert std::error_code (with MLSSErrorCode) to the appropriate MLSSenum
MLSSenum errorCodeToMLSSEnum(const std::error_code& ec)
{
if (!ec)
{
return MLSS_SUCCESS;
}
// Check if it's from the MLSS error category
if (ec.category() == mlss_error_category())
{
switch (static_cast<MLSSErrorCode>(ec.value()))
{
case MLSSErrorCode::Success:
return MLSS_SUCCESS;
case MLSSErrorCode::ShaderInvalidParameters:
return MLSS_ERROR_SHADER_INVALID_PARAMETERS;
case MLSSErrorCode::ShaderUnsupportedOperator:
return MLSS_ERROR_SHADER_UNSUPPORTED_OPERATOR;
case MLSSErrorCode::ShaderUnsupportedArchitecture:
return MLSS_ERROR_SHADER_UNSUPPORTED_ARCHITECTURE;
case MLSSErrorCode::ShaderUnsupportedConfiguration:
return MLSS_ERROR_SHADER_UNSUPPORTED_CONFIGURATION;
case MLSSErrorCode::ShaderFeatureNotYetImplemented:
return MLSS_ERROR_SHADER_FEATURE_NOT_YET_IMPLEMENTED;
case MLSSErrorCode::ArchitectureNotSupported:
return MLSS_ERROR_ENUM_ARCHITECTURE_NOT_SUPPORTED;
case MLSSErrorCode::ArchitectureNotFound:
return MLSS_ERROR_ENUM_ARCHITECTURE_NOT_FOUND;
case MLSSErrorCode::CodenameNotFound:
return MLSS_ERROR_ENUM_CODENAME_NOT_FOUND;
default:
return MLSS_ERROR_UNKNOWN_ERROR;
}
}
// Unknown error category - return generic failure
return MLSS_ERROR_FAILURE;
}
//=====================================================================================================================
template <class FunctorType, class InputOutputType, class... Args>
constexpr MLSSenum createObj(InputOutputType& ref, Args&&... args)
{
FunctorType obj;
// return obj(ptr, std::forward<Args>(args)...).error_or(MLSS_SUCCESS);
auto tmp = obj(ref, std::forward<Args>(args)...);
return tmp.error_or(MLSS_SUCCESS);
}
//=====================================================================================================================
template <class T>
MLSSvoid destroyObj(MLSSvoid* obj)
{
if (obj == nullptr)
{
return;
}
std::default_delete<T> deleter;
deleter(static_cast<T*>(obj));
}
// Invoke fn() and return its result. On Windows, any structured exception
// (access violation, illegal instruction, …) raised inside an MLSS
// getCapsImpl or getBinaries call is caught here and converted to the
// fallback value so the caller never sees a process crash.
#ifdef _WIN32
template <class Fn, class Ret = std::invoke_result_t<Fn>>
Ret seh_call(Fn&& fn, Ret fallback) noexcept
{
__try
{
return fn();
}
__except(GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ||
GetExceptionCode() == EXCEPTION_ILLEGAL_INSTRUCTION ||
GetExceptionCode() == EXCEPTION_STACK_OVERFLOW
? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH)
{
return fallback;
}
}
#else
template <class Fn, class Ret = std::invoke_result_t<Fn>>
Ret seh_call(Fn&& fn, Ret /*fallback*/) noexcept
{
return fn();
}
#endif
//=====================================================================================================================
template <class T>
constexpr auto getShared(MLSSvoid* const ptr)
{
return std::shared_ptr<T>(static_cast<T*>(ptr), NoDeallocation<T>());
}
//=====================================================================================================================
template <class T>
constexpr auto getShared(const MLSSvoid* const ptr)
{
return std::shared_ptr<T>(static_cast<T*>(const_cast<MLSSvoid* const>(ptr)), NoDeallocation<T>());
}
//=====================================================================================================================
template <class T>
constexpr MLSSbool setParams(Context* const context, std::string_view opName, T paramName, const MLSSvoid* const value)
{
for (auto& op : context->m_ops)
{
if (op.m_op == opName.data())
{
for (auto& param : op.m_params)
{
if (param.is(paramName))
{
param = value;
return true;
}
}
}
}
return false;
}
enum class NotImplementedType
{
Warning,
Error
};
template <NotImplementedType err>
void not_implemented()
{
VerboseManager::getInstance().log(std::clog, VerboseLevel::DEBUG) << "Function or Method: " << __func__ << " Not implemented!" << std::endl;
if constexpr (err == NotImplementedType::Error)
{
setLastError(MLSS_ERROR_NOT_IMPLEMENTED);
throw std::runtime_error("Not implemented!");
}
else
{
setLastError(MLSS_WARNING_NOT_IMPLEMENTED);
}
}
//=====================================================================================================================
template <class T>
T* getTypeFromHandle(MLSShandle handle)
{
Any* any_obj = MemoryManager::template getPointer<Any>(handle);
if (any_obj && anyIs<T>(*any_obj))
{
return anyCast<T>(any_obj);
}
return nullptr;
}
//=====================================================================================================================
Context* getContextFromHandle(MLSScontext ctx_handle)
{
return getTypeFromHandle<Context>(ctx_handle);
}
//=====================================================================================================================
void* getVectorDataByType(const MLSSvector& vec)
{
if (vec.m_handle == 0)
{
return nullptr;
}
Any* any_obj = MemoryManager::template getPointer<Any>(vec.m_handle);
if (!any_obj || !any_obj->hasValue())
{
return nullptr;
}
switch (vec.m_type)
{
// Basic integer types
case MLSS_BOOL:
case MLSS_UINT8:
if (anyIs<std::vector<uint8_t>>(*any_obj))
{
auto& storage = anyCast<std::vector<uint8_t>&>(*any_obj);
return storage.data();
}
break;
case MLSS_INT8:
if (anyIs<std::vector<int8_t>>(*any_obj))
{
auto& storage = anyCast<std::vector<int8_t>&>(*any_obj);
return storage.data();
}
break;
case MLSS_UINT16:
if (anyIs<std::vector<uint16_t>>(*any_obj))
{
auto& storage = anyCast<std::vector<uint16_t>&>(*any_obj);
return storage.data();
}
break;
case MLSS_INT16:
if (anyIs<std::vector<int16_t>>(*any_obj))
{
auto& storage = anyCast<std::vector<int16_t>&>(*any_obj);
return storage.data();
}
break;
case MLSS_UINT32:
if (anyIs<std::vector<uint32_t>>(*any_obj))
{
auto& storage = anyCast<std::vector<uint32_t>&>(*any_obj);
return storage.data();
}
break;
case MLSS_INT32:
if (anyIs<std::vector<int32_t>>(*any_obj))
{
auto& storage = anyCast<std::vector<int32_t>&>(*any_obj);
return storage.data();
}
break;
case MLSS_UINT64:
if (anyIs<std::vector<uint64_t>>(*any_obj))
{
auto& storage = anyCast<std::vector<uint64_t>&>(*any_obj);
return storage.data();
}
break;
case MLSS_INT64:
if (anyIs<std::vector<int64_t>>(*any_obj))
{
auto& storage = anyCast<std::vector<int64_t>&>(*any_obj);
return storage.data();
}
break;
// Floating point types
case MLSS_FLOAT32:
if (anyIs<std::vector<float>>(*any_obj))
{
auto& storage = anyCast<std::vector<float>&>(*any_obj);
return storage.data();
}
break;
case MLSS_FLOAT64:
if (anyIs<std::vector<double>>(*any_obj))
{
auto& storage = anyCast<std::vector<double>&>(*any_obj);
return storage.data();
}
break;
// Enum types
case MLSS_ENUM:
if (anyIs<std::vector<MLSSenum>>(*any_obj))
{
auto& storage = anyCast<std::vector<MLSSenum>&>(*any_obj);
return storage.data();
}
break;
case MLSS_ENUM64:
if (anyIs<std::vector<enum64>>(*any_obj))
{
auto& storage = anyCast<std::vector<enum64>&>(*any_obj);
return storage.data();
}
break;
// Structured types
case MLSS_ARG:
if (anyIs<std::vector<MLSSarg>>(*any_obj))
{
auto& storage = anyCast<std::vector<MLSSarg>&>(*any_obj);
return storage.data();
}
break;
case MLSS_DIM3:
if (anyIs<std::vector<MLSSdim3>>(*any_obj))
{
auto& storage = anyCast<std::vector<MLSSdim3>&>(*any_obj);
return storage.data();
}
break;
case MLSS_VECTOR:
if (anyIs<std::vector<MLSSvector>>(*any_obj))
{
auto& storage = anyCast<std::vector<MLSSvector>&>(*any_obj);
return storage.data();
}
break;
case MLSS_BINARY:
if (anyIs<std::vector<MLSSbinary>>(*any_obj))
{
auto& storage = anyCast<std::vector<MLSSbinary>&>(*any_obj);
return storage.data();
}
break;
case MLSS_CONTEXT:
if (anyIs<std::vector<Context>>(*any_obj))
{
auto& storage = anyCast<std::vector<Context>&>(*any_obj);
return storage.data();
}
break;
case MLSS_STRING:
if (anyIs<std::vector<MLSSstring>>(*any_obj))
{
auto& storage = anyCast<std::vector<MLSSstring>&>(*any_obj);
return storage.data();
}
break;
// Note: The following types might not have direct C++ equivalents or might need special handling:
// MLSS_INT4, MLSS_UINT4 - These are typically packed types, not directly supported as standalone types
// MLSS_FLOAT4, MLSS_FLOAT8, MLSS_FLOAT16 - These might need special vector types or be represented differently
// MLSS_BFLOAT4, MLSS_BFLOAT8, MLSS_BFLOAT16 - Brain floating point formats
// Handle unsupported or unknown types
case MLSS_NONE_TYPE:
case MLSS_INT4:
case MLSS_UINT4:
case MLSS_FLOAT4:
case MLSS_FLOAT8:
case MLSS_FLOAT8_FNUZ:
case MLSS_FLOAT8_OCP:
case MLSS_FLOAT16:
case MLSS_BFLOAT4:
case MLSS_BFLOAT8:
case MLSS_BFLOAT8_FNUZ:
case MLSS_BFLOAT8_OCP:
case MLSS_BFLOAT16:
case MLSS_UNKNOWN_TYPE:
case MLSS_CUSTOM_TYPE:
case MLSS_UNSET_TYPE:
default:
// These types are either not implemented or don't have direct C++ equivalents
return nullptr;
}
return nullptr;
}
const char* getTypeString(MLSSenum type)
{
switch (type)
{
case MLSS_NONE_TYPE:
return "NONE";
case MLSS_BOOL:
return "BOOL";
case MLSS_INT8:
return "INT8";
case MLSS_UINT8:
return "UINT8";
case MLSS_INT16:
return "INT16";
case MLSS_UINT16:
return "UINT16";
case MLSS_INT32:
return "INT32";
case MLSS_UINT32:
return "UINT32";
case MLSS_INT64:
return "INT64";
case MLSS_UINT64:
return "UINT64";
case MLSS_FLOAT32:
return "FLOAT32";
case MLSS_FLOAT64:
return "FLOAT64";
case MLSS_ENUM:
return "ENUM";
case MLSS_ENUM64:
return "ENUM64";
case MLSS_CONTEXT:
return "CONTEXT";
case MLSS_ARG:
return "ARG";
case MLSS_VECTOR:
return "VECTOR";
case MLSS_DIM3:
return "DIM3";
case MLSS_BINARY:
return "BINARY";
case MLSS_STRING:
return "STRING";
case MLSS_UNKNOWN_TYPE:
return "UNKNOWN";
case MLSS_CUSTOM_TYPE:
return "CUSTOM";
case MLSS_UNSET_TYPE:
return "UNSET";
case MLSS_INT4:
return "INT4";
case MLSS_UINT4:
return "UINT4";
case MLSS_FLOAT4:
return "FLOAT4";
case MLSS_FLOAT8:
return "FLOAT8";
case MLSS_FLOAT8_FNUZ:
return "FLOAT8_FNUZ";
case MLSS_FLOAT8_OCP:
return "FLOAT8_OCP";
case MLSS_FLOAT16:
return "FLOAT16";
case MLSS_BFLOAT4:
return "BFLOAT4";
case MLSS_BFLOAT8:
return "BFLOAT8";
case MLSS_BFLOAT8_FNUZ:
return "BFLOAT8_FNUZ";
case MLSS_BFLOAT8_OCP:
return "BFLOAT8_OCP";
case MLSS_BFLOAT16:
return "BFLOAT16";
default:
return "INVALID";
}
}
} // namespace
//=====================================================================================================================
MLSSenum lastError = MLSS_SUCCESS;
//=====================================================================================================================
MLSSenum setLastError(const MLSSenum& error)
{
lastError = error;
return error;
}
//=====================================================================================================================
MLSSenum resetLastError()
{
MLSSenum error = lastError;
lastError = MLSS_SUCCESS;
return error;
}
//=====================================================================================================================
MLSSenum returnLastError()
{
return lastError;
}
//=====================================================================================================================
struct createContext_t
{
using value_type = Context;
using pointer = value_type*;
std::expected<MLSSbool, MLSSenum> operator()(MLSScontext& ctx,
std::string_view asic,
std::string_view opName,
va_list* lst) const;
};
//=====================================================================================================================
std::expected<MLSSbool, MLSSenum> createContext_t::operator()(MLSScontext& ctx, std::string_view asic, std::string_view opName, va_list* lst) const
{
std::vector<Context::Op> ops;
ops.emplace_back(Context::Op::create(std::string(opName)));
if (lst)
{
do
{
std::string tmp = va_arg(*lst, MLSSstring);
if (tmp != MLSS_END_LIST)
{
ops.emplace_back(Context::Op::create(tmp));
}
else
{
break;
}
} while (true);
}
Context context_obj(asic, std::move(ops));
if (context_obj.m_lastError)
{
// Return the specific error code from context creation
MLSSenum specificError = errorCodeToMLSSEnum(context_obj.m_lastError);
return std::unexpected<MLSSenum>(specificError);
}
if (ctx != 0) // ctx contains a valid handle
{
// Get the Any from MemoryManager
Any* existing_any = MemoryManager::template getPointer<Any>(ctx);
if (existing_any && MemoryManager::isInitialized(&existing_any))
{
// Check if Any contains Context
if (anyIs<Context>(*existing_any))
{
// Update existing Context
auto& existing_context = anyCast<Context&>(*existing_any);
existing_context.m_asic = context_obj.m_asic;
existing_context.m_ops = std::move(context_obj.m_ops);
existing_context.m_wasGetCapsCalled = context_obj.m_wasGetCapsCalled;
}
else
{
return std::unexpected<MLSSenum>(MLSS_ERROR_INVALID_PARAMETER);
}
}
else
{
return std::unexpected<MLSSenum>(MLSS_ERROR_INVALID_PARAMETER);
}
}
else
{
// Store Context directly in Any
Any context_any = std::move(context_obj);
// Create new object and handle
ctx = MemoryManager::addObject(std::move(context_any));
// Mark the Any as initialized
Any* new_any = MemoryManager::template getPointer<Any>(ctx);
if (new_any)
{
MemoryManager::markAsInitialized(&new_any);
}
}
return true;
}
//=====================================================================================================================
struct BinaryInfoCollection_t
{
// Use std::deque for storage that is read back through raw pointers:
// unlike std::vector, std::deque does not invalidate references or
// pointers to existing elements when push_back / emplace_back grows
// the container. This is required because addString() returns the
// c_str() of the back element and that pointer must remain valid
// for every subsequent insertion.
std::vector<MLSSbinary> binary_infos;
std::deque<std::string> string_storage;
std::deque<std::vector<MLSSuint32>> constants_storage;
// Keeps shader Binaries alive for as long as the C-API hands out
// pointers into Blob::m_pBinary. Without this, dynamically generated
// binaries (e.g. linked non-relocatable variants) would be freed
// before the user could read them.
std::deque<Binaries> binaries_storage;
// Helper to add a string and return a MLSSstring (i.e. a char*)
MLSSstring addString(const std::string& str);
// Helper to add constants and return handle
MLSShandle addConstants(const std::vector<MLSSuint32>& constants);
};
//=====================================================================================================================
MLSSstring BinaryInfoCollection_t::addString(const std::string& str)
{
string_storage.emplace_back(str);
return const_cast<char*>(string_storage.back().c_str());
}
//=====================================================================================================================
MLSShandle BinaryInfoCollection_t::addConstants(const std::vector<MLSSuint32>& constants)
{
if (constants.empty())
{
return 0;
}
constants_storage.emplace_back(constants);
return reinterpret_cast<MLSShandle>(constants_storage.back().data());
}
//=====================================================================================================================
struct createBinaries_t
{
using value_type = Binaries;
using pointer = value_type*;
// std::unique_ptr<Binaries> operator()(const Context& context, MLSSsize* const n) const;
std::expected<MLSSbool, MLSSenum> operator()(MLSSbinary*& bin, const MLSScontext& context, MLSSsize* const n) const;
};
//=====================================================================================================================
std::expected<MLSSbool, MLSSenum> createBinaries_t::operator()(MLSSbinary*& bin, const MLSScontext& context, MLSSsize* const n) const
{
if (n == nullptr)
{
return std::unexpected<MLSSenum>(MLSS_ERROR_INVALID_PARAMETER);
}
// Use MemoryManager to get Context from handle
Context* ctx = getContextFromHandle(context);
if (!ctx)
{
return std::unexpected<MLSSenum>(MLSS_ERROR_INVALID_PARAMETER);
}
if (!ctx->m_wasGetCapsCalled)
{
MLSSstatus* statuses = nullptr;
MLSSsize n = 0;
auto status = getCaps(context, &statuses, &n);
if (status != MLSS_SUCCESS)
{
return status;
}
}
// Create comprehensive collection. binary_infos is the only storage
// that must be contiguous (for the C-API surface); string_storage
// and constants_storage are std::deque so growth never invalidates
// already-handed-out pointers, regardless of how many blobs an op
// produces.
BinaryInfoCollection_t collection;
collection.binary_infos.reserve(ctx->m_ops.size() * 4);
for (const auto& op : ctx->m_ops)
{
Binaries binaries;
GfxIpTriple gfxArch = IP_GFX_UNKNOWN;
if (auto gfxIp = architectureStringToGfxIpTriple(ctx->m_asic); gfxIp.has_value())
{
gfxArch = gfxIp.value();
}
// Use operator classes for all operations
if (op.m_op == "MLSS_MHA")
{
op::OperatorMHA mha_operator;
mha_operator.setAttributes(op.m_params);
mha_operator.setGfxIpTriple(gfxArch);
auto result = mha_operator.getBinaries();
if (!result.has_value())
{
return std::unexpected<MLSSenum>(MLSS_ERROR_OPERATOR_NOT_SUPPORTED);
}
binaries = std::move(result.value());
}
else if (op.m_op == "MLSS_CONV")
{
op::OperatorConv conv_operator;
conv_operator.setAttributes(op.m_params);
conv_operator.setGfxIpTriple(gfxArch);
auto result = conv_operator.getBinaries();
if (!result.has_value())
{
return std::unexpected<MLSSenum>(MLSS_ERROR_OPERATOR_NOT_SUPPORTED);
}
binaries = std::move(result.value());
}
else if (op.m_op == "MLSS_GEMM")
{
op::OperatorGEMM gemm_operator;
gemm_operator.setAttributes(op.m_params);
gemm_operator.setGfxIpTriple(gfxArch);
auto result = gemm_operator.getBinaries();
if (!result.has_value())
{
return std::unexpected<MLSSenum>(MLSS_ERROR_OPERATOR_NOT_SUPPORTED);
}
binaries = std::move(result.value());
}
else if (op.m_op == "MLSS_GQA")
{
op::OperatorGQA gqa_operator;
gqa_operator.setAttributes(op.m_params);
gqa_operator.setGfxIpTriple(gfxArch);
auto result = gqa_operator.getBinaries();
if (!result.has_value())
{
return std::unexpected<MLSSenum>(MLSS_ERROR_OPERATOR_NOT_SUPPORTED);
}
binaries = std::move(result.value());
}
else if (op.m_op == "MLSS_MVN")
{
op::OperatorMVN mvn_operator;
mvn_operator.setAttributes(op.m_params);
mvn_operator.setGfxIpTriple(gfxArch);
auto result = mvn_operator.getBinaries();
if (!result.has_value())
{
return std::unexpected<MLSSenum>(MLSS_ERROR_OPERATOR_NOT_SUPPORTED);
}
binaries = std::move(result.value());
}
else if (op.m_op == "MLSS_QGEMM")
{
op::OperatorQGEMM qgemm_operator;
qgemm_operator.setAttributes(op.m_params);
qgemm_operator.setGfxIpTriple(gfxArch);
auto result = qgemm_operator.getBinaries();
if (!result.has_value())
{
return std::unexpected<MLSSenum>(MLSS_ERROR_OPERATOR_NOT_SUPPORTED);
}
binaries = std::move(result.value());
}
else if (op.m_op == "MLSS_RMSNORM")
{
op::OperatorRmsNorm rmsnorm_operator;
rmsnorm_operator.setAttributes(op.m_params);
rmsnorm_operator.setGfxIpTriple(gfxArch);
auto result = rmsnorm_operator.getBinaries();
if (!result.has_value())
{
return std::unexpected<MLSSenum>(MLSS_ERROR_OPERATOR_NOT_SUPPORTED);
}
binaries = std::move(result.value());
}
else if (op.m_op == "MLSS_SIGMOID_MUL")
{
op::OperatorSigmoidMul sigmoid_mul_operator;
sigmoid_mul_operator.setAttributes(op.m_params);
sigmoid_mul_operator.setGfxIpTriple(gfxArch);
auto result = sigmoid_mul_operator.getBinaries();
if (!result.has_value())
{
return std::unexpected<MLSSenum>(MLSS_ERROR_OPERATOR_NOT_SUPPORTED);
}
binaries = std::move(result.value());
}
else if (op.m_op == "MLSS_GEMMGEMM")
{
op::OperatorGemmGemm gemm_gemm_operator;
gemm_gemm_operator.setAttributes(op.m_params);
gemm_gemm_operator.setGfxIpTriple(gfxArch);
auto result = gemm_gemm_operator.getBinaries();
if (!result.has_value())
{
return std::unexpected<MLSSenum>(MLSS_ERROR_OPERATOR_NOT_SUPPORTED);
}
binaries = std::move(result.value());
}
else
{
// Unknown operator
return std::unexpected<MLSSenum>(MLSS_ERROR_OPERATOR_NOT_FOUND);
}
// Helper lambda to create MLSSbinary from a Blob
auto createBinaryInfo = [&collection, &op, &ctx](const Binaries::Blob& shader_blob) -> MLSSbinary
{
MLSSbinary binary_info = {};
// Store strings with proper lifetime management
binary_info.m_pOperatorName = collection.addString(op.m_op);
binary_info.m_ASIC = collection.addString(ctx->m_asic);
binary_info.m_pKernelName = collection.addString(shader_blob.m_name);
// Set grid and block dimensions from shader blob
binary_info.m_grid = shader_blob.m_grid;
binary_info.m_blocks = shader_blob.m_blocks;
binary_info.m_sharedMemInBytes = 0;
// Create constants vector
if (!shader_blob.m_constants.empty())
{
binary_info.m_constants = createTypedVector<MLSSuint32>(
shader_blob.m_constants.data(),
shader_blob.m_constants.size());
}
else
{
binary_info.m_constants = {};
binary_info.m_constants.m_size = 0;
binary_info.m_constants.m_type = MLSS_UINT32;
binary_info.m_constants.m_handle = 0;
}
// Create arguments vector from shader blob
if (!shader_blob.m_argList.empty())
{
binary_info.m_argList = createTypedVector<MLSSarg>(
shader_blob.m_argList.data(),
shader_blob.m_argList.size());
}
else
{
binary_info.m_argList = {};
binary_info.m_argList.m_size = 0;
binary_info.m_argList.m_type = MLSS_ARG;
binary_info.m_argList.m_handle = 0;
}
// Store binary data pointer and size
binary_info.m_binaries = const_cast<MLSSvoid*>(shader_blob.m_pBinary);
binary_info.m_binarySize = shader_blob.m_size;
bool isRelocatable = false;
if (shader_blob.m_size >= 18u)
{
const auto* raw = static_cast<const std::uint8_t*>(shader_blob.m_pBinary);
if (raw[0] == 0x7Fu && raw[1] == 0x45u && raw[2] == 0x4Cu && raw[3] == 0x46u)
{
std::uint16_t eType = static_cast<std::uint16_t>(raw[16])
| (static_cast<std::uint16_t>(raw[17]) << 8u);
isRelocatable = (eType == 1u);
}
}
binary_info.m_isRelocatable = isRelocatable;
return binary_info;
};
// Keep the Binaries (and the Blobs they own) alive past this
// loop iteration; the createBinaryInfo lambda above hands out
// raw pointers into each Blob's underlying buffer.
collection.binaries_storage.emplace_back(std::move(binaries));
const auto& storedBinaries = collection.binaries_storage.back();
for (const auto& blob : storedBinaries)
{
collection.binary_infos.emplace_back(createBinaryInfo(blob));
}
}
*n = collection.binary_infos.size();
// Store the collection in MemoryManager using Any
Any collection_any = std::move(collection);
MLSShandle handle = MemoryManager::addObject(std::move(collection_any));
// Mark as initialized
Any* new_any = MemoryManager::template getPointer<Any>(handle);
if (!new_any)
{
return std::unexpected<MLSSenum>(MLSS_ERROR_BAD_MEMORY_ALLOCATION);
}
MemoryManager::markAsInitialized(&new_any);
// Get the stored collection to return pointer to its data
if (anyIs<BinaryInfoCollection_t>(*new_any))
{
auto& stored_collection = anyCast<BinaryInfoCollection_t&>(*new_any);
bin = stored_collection.binary_infos.data();
}
else
{
return std::unexpected<MLSSenum>(MLSS_ERROR_BAD_MEMORY_ALLOCATION);
}
return true;
}
//=====================================================================================================================
MLSSstatus createContext(MLSScontext& context, std::string_view asic, std::string_view opName, va_list* lst)
{
return createObj<createContext_t>(context, asic, opName, lst);
}
//=====================================================================================================================
MLSSenum createBinaries(MLSSbinary*& binaries, const MLSScontext context, MLSSsize* const n)
{
return createObj<createBinaries_t>(binaries, context, n);
}
//=====================================================================================================================
// Filtered variant: collects all blobs via createBinaries, then compacts the array
// in-place to keep only entries matching `kind`.
MLSSenum createBinariesEx(MLSSbinary*& binaries, const MLSScontext context, MLSSsize* const n, MLSSbinaryKind kind)
{
// Reject unknown / not-yet-supported kinds up-front instead of silently
// treating them as "relocatable". Only the ELF-type filters are
// implemented; SINGLE_POINTER / DOUBLE_POINTER are not handled here yet.
switch (kind)
{
case MLSS_BINARY_KIND_ANY:
case MLSS_BINARY_KIND_NON_RELOCATABLE:
case MLSS_BINARY_KIND_RELOCATABLE:
break;
default:
return MLSS_ERROR_INVALID_PARAMETER;
}
MLSSenum status = createBinaries(binaries, context, n);
if (status != MLSS_SUCCESS)
return status;
if (!n || *n == 0 || !binaries)
return MLSS_SUCCESS;
if (kind == MLSS_BINARY_KIND_ANY)
return MLSS_SUCCESS;
if (kind != MLSS_BINARY_KIND_NON_RELOCATABLE && kind != MLSS_BINARY_KIND_RELOCATABLE)
return MLSS_ERROR_INVALID_PARAMETER;
const MLSSsize total = *n;
// Compact matching binaries into the front of the array so the
// returned [binaries, binaries + *n) range contains only matches
// even when matching entries are not contiguous in the original data.
MLSSsize writeIndex = 0;
for (MLSSsize i = 0; i < total; ++i)
{
if (!binaries[i].m_binaries || binaries[i].m_binarySize == 0)
continue;