-
Notifications
You must be signed in to change notification settings - Fork 20
/
ggml-qnn.cpp
3653 lines (2888 loc) · 135 KB
/
ggml-qnn.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
/*
* Copyright (c) 2024- KanTV Authors
*
* this is implementation of "PoC: Add Qualcomm mobile SoC native backend for GGML", https://github.com/zhouwg/kantv/issues/121
*
*
* IPR statement:
* The QNN helper macros and functions are referenced(reverse engineering by many experiments) from:
* (1) https://github.com/pytorch/executorch/tree/main/backends/qualcomm (provided by Qualcomm Technologies, Inc.)
* (2) QNN samples (Qualcomm Technologies, Inc.)
* (3) /opt/qcom/aistack/qnn/2.20.0.240223/examples/Models/InceptionV3/model/Inception_v3.cpp which is
* generated automatically by Qualcomm's dedicated tool and it contains more then 20,000 lines C++ code
* Copyright (c) 2019-2023 Qualcomm Technologies, Inc.
* All Rights Reserved.
* Confidential and Proprietary - Qualcomm Technologies, Inc.
*
*
* status:
* 1. core implementation(data path works fine as expected with whisper.cpp&llama.cpp using QNN CPU/GPU backend)
* on Qualcomm's SoC based low-end phone
* 2. core implementation(data path works fine as expected with whisper.cpp&llama.cpp using QNN NPU(aka HTP/DSP)
* backend on Qualcomm's soC based high-end phone
* 3. GGML_OP_MUL_MAT & GGML_OP_MUL & GGML_OP_ADD using QNN API has been completed and the dedicated
* Android command line UT program works fine as expected on Qualcomm's SoC based Android phone
* 4. PR to upstream GGML community on 04-24-2024: https://github.com/ggerganov/llama.cpp/pull/6869
*
* todo:
* 1. lack of implementation of other GGML OPs using QNN API(only support GGML_OP_MUL_MAT,
* GGML_OP_MUL, GGML_OP_ADD currently). this problem has been done by s standalone PR
* https://github.com/zhouwg/kantv/pull/216 in this project or a standalone PR
* https://github.com/ggerganov/llama.cpp/pull/7641 in upstream.
* it's a general approach for mixed inference between Qualcomm's CPU&GPU / CPU&NPU very
* easily and re-use/refine the existing GGML backend subsystem and no any side-effect to
* any existing backends/codes.
* 2. only support FP32 / FP16, other(quantized) GGML data type not used currently, data type of
* input tensor and output tensor must be same(this is a real big limitation in this backend).
* would be done in upstream GGML community if the PR of ggml-qnn-backend in upstream could be accepted.
* 3. QNN's RPC feature(which is required for QNN NPU backend) not used,would be done in upstream
* GGML community if the PR of ggml-qnn-backend in upstream could be accepted.
* 4. performance fine-tune(long-term task)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stddef.h>
#include <inttypes.h>
#include <math.h>
#include <time.h>
#include <unistd.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <string>
#include <vector>
#include <thread>
#include <mutex>
#include <map>
#include <set>
#include <tuple>
#include <queue>
#include <fstream>
#include <iostream>
#include <sstream>
#include <chrono>
#include <memory>
#include <regex>
#include <random>
#include <functional>
#include <unordered_map>
#include <condition_variable>
#include <cassert>
#include <unordered_set>
#include <utility>
#include <stdatomic.h>
#include "QnnTypes.h"
#include "QnnCommon.h"
#include "QnnContext.h"
#include "QnnBackend.h"
#include "QnnGraph.h"
#include "QnnProperty.h"
#include "QnnTensor.h"
#include "QnnInterface.h"
#include "Saver/QnnSaver.h"
#include "System/QnnSystemInterface.h"
#include "HTP/QnnHtpDevice.h"
#include "ggml-qnn.h"
#include "ggml-backend-impl.h"
// =================================================================================================
//
// forward/external/helper declaration
//
// =================================================================================================
class qnn_instance;
#if (defined __ANDROID__) || (defined ANDROID)
extern "C" int __android_log_print(int prio, const char * tag, const char * fmt, ...)
__attribute__((__format__(printf, 3, 4)));
#endif
static void ggml_qnn_log_internal(ggml_log_level level, const char * file, const char * func, int line, const char * format, ...);
// =================================================================================================
//
// self-defined macro / data structure
//
// =================================================================================================
#define RPCMEM_DEFAULT_FLAGS 1
#define RPCMEM_HEAP_ID_SYSTEM 25
#define GGML_DUMP_TENSOR(tensor) ggml_tensor_dump(tensor, #tensor)
#define GGML_QNN_LOGBUF_LEN 4096
#define GGML_QNN_DEBUG 1 //for troubleshooting QNN backend
#define NOT_IN_PR 0 //for update PR(https://github.com/ggerganov/llama.cpp/pull/6869) in upstream easily and quickly
#define QNN_LOG_ERROR(...) ggml_qnn_log_internal(GGML_LOG_LEVEL_DEBUG, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#define QNN_LOG_WARN(...) ggml_qnn_log_internal(GGML_LOG_LEVEL_DEBUG , __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#define QNN_LOG_INFO(...) ggml_qnn_log_internal(GGML_LOG_LEVEL_DEBUG , __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#if GGML_QNN_DEBUG
#define QNN_LOG_DEBUG(...) ggml_qnn_log_internal(GGML_LOG_LEVEL_DEBUG, __FILE__, __FUNCTION__, __LINE__, __VA_ARGS__)
#else
#define QNN_LOG_DEBUG(...)
#endif
#define VALIDATE(value, status) \
do { \
status = value; \
if (status != QNN_SUCCESS) { \
QNN_LOG_WARN("%s expected QNN_SUCCESS\n", #value); \
return status; \
} \
} while (0)
#define VALIDATE_TENSOR_VERSION(tensor, err) VALIDATE(validate_tensor_version(tensor), err)
#define VALIDATE_OP_CONFIG_VERSION(op, err) VALIDATE(validate_op_config_version(op), err)
#define QNN_VER_PTR(x) (&((x).v1))
#define QNN_OP_CFG_VALID(op_config) ((op_config).version == QNN_OPCONFIG_VERSION_1)
#define QNN_OP_CFG_GET_NAME(op_config) get_qnn_oponfig_name(op_config)
#define QNN_OP_CFG_GET_PACKAGE_NAME(op_config) get_qnn_op_config_packagename(op_config)
#define QNN_OP_CFG_GET_TYPE_NAME(op_config) get_qnn_op_config_typename(op_config)
#define QNN_OP_CFG_GET_NUM_PARAMS(op_config) get_qnn_op_config_numparams(op_config)
#define QNN_OP_CFG_GET_PARAMS(op_config) get_qnn_op_config_params(op_config)
#define QNN_OP_CFG_GET_NUM_INPUTS(op_config) get_qnn_op_config_numinputs(op_config)
#define QNN_OP_CFG_GET_INPUTS(op_config) get_qnn_op_config_inputs(op_config)
#define QNN_OP_CFG_GET_NUM_OUTPUTS(op_config) get_qnn_op_config_numoutputs(op_config)
#define QNN_OP_CFG_GET_OUTPUTS(op_config) get_qnn_op_config_outputs(op_config)
#define QNN_OP_CFG_SET_NAME(op_config, value) set_qnn_op_config_name(op_config, value)
#define QNN_OP_CFG_SET_PACKAGE_NAME(op_config, value) set_qnn_op_config_packagename(op_config, value)
#define QNN_OP_CFG_SET_TYPE_NAME(op_config, value) set_qnn_op_config_typename(op_config, value)
#define QNN_OP_CFG_SET_PARAMS(op_config, num_of_params, params) \
set_qnn_op_config_params(op_config, num_of_params, params)
#define QNN_OP_CFG_SET_INPUTS(op_config, num_of_inputs, inputTensors) \
set_qnn_op_config_inputs(op_config, num_of_inputs, inputTensors)
#define QNN_OP_CFG_SET_OUTPUTS(op_config, num_of_outputs, output_tensors) \
set_qnn_op_config_outputs(op_config, num_of_outputs, output_tensors)
#define QNN_TENSOR_GET_ID(tensor) get_qnn_tensorid(tensor)
#define QNN_TENSOR_GET_NAME(tensor) get_qnn_tensorname(tensor)
#define QNN_TENSOR_GET_TYPE(tensor) get_qnn_tensortype(tensor)
#define QNN_TENSOR_GET_DATA_FORMAT(tensor) get_qnn_tensor_dataformat(tensor)
#define QNN_TENSOR_GET_DATA_TYPE(tensor) get_qnn_tensor_datatype(tensor)
#define QNN_TENSOR_GET_QUANT_PARAMS(tensor) get_qnn_tensor_quantparams(tensor)
#define QNN_TENSOR_GET_RANK(tensor) get_qnn_tensor_rank(tensor)
#define QNN_TENSOR_GET_DIMENSIONS(tensor) get_qnn_tensor_dimensions(tensor)
#define QNN_TENSOR_GET_MEM_TYPE(tensor) get_qnn_tensor_memtype(tensor)
#define QNN_TENSOR_GET_CLIENT_BUF(tensor) get_qnn_tensor_clientbuf(tensor)
#define QNN_TENSOR_GET_MEM_HANDLE(tensor) get_qnn_tensor_memhandle(tensor)
#define QNN_TENSOR_SET_ID(tensor, value) set_qnn_tensor_id(tensor, value)
#define QNN_TENSOR_SET_NAME(tensor, value) set_qnn_tensor_name(tensor, value)
#define QNN_TENSOR_SET_TYPE(tensor, value) set_qnn_tensor_type(tensor, value)
#define QNN_TENSOR_SET_DATA_FORMAT(tensor, value) set_qnn_tensor_dataformat(tensor, value)
#define QNN_TENSOR_SET_DATA_TYPE(tensor, value) set_qnn_tensor_datatype(tensor, value)
#define QNN_TENSOR_SET_QUANT_PARAMS(tensor, value) set_qnn_tensor_quantparams(tensor, value)
#define QNN_TENSOR_SET_RANK(tensor, value) set_qnn_tensor_rank(tensor, value)
#define QNN_TENSOR_SET_DIMENSIONS(tensor, value) set_qnn_tensor_dimensions(tensor, value)
#define QNN_TENSOR_SET_MEM_TYPE(tensor, value) set_qnn_tensor_memtype(tensor, value)
#define QNN_TENSOR_SET_CLIENT_BUF(tensor, value) set_qnn_tensor_clientbuf(tensor, value)
#define QNN_TENSOR_SET_MEM_HANDLE(tensor, value) set_qnn_tensor_memhandle(tensor, value)
using pfn_rpc_mem_init = void (*)(void);
using pfn_rpc_mem_deinit = void (*)(void);
using pfn_rpc_mem_alloc = void *(*)(int, uint32_t, int);
using pfn_rpc_mem_free = void (*)(void *);
using pfn_rpc_mem_to_fd = int (*)(void *);
using _pfn_QnnSaver_initialize = decltype(QnnSaver_initialize);
using _pfn_QnnInterface_getProviders = decltype(QnnInterface_getProviders);
using _pfn_QnnSystemInterface_getProviders = decltype(QnnSystemInterface_getProviders);
typedef void (* ggml_qnn_func_t)(const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst);
typedef void (* ggml_qnn_func_common_t)(const ggml_op ggml_op, const ggml_tensor * src0, const ggml_tensor * src1, ggml_tensor * dst);
enum class ggml_qnn_profile_level {
profile_off = 0,
profile_basic = 1,
profile_detail = 2
};
struct ggml_backend_qnn_context {
int device;
int threads;
char name[GGML_MAX_NAME];
char lib[GGML_MAX_NAME];
qnn_instance * instance;
struct ggml_backend * backend;
QNN_INTERFACE_VER_TYPE raw_interface;
QNN_SYSTEM_INTERFACE_VER_TYPE raw_system_interface;
} ;
// =================================================================================================
//
// static global variables
//
// =================================================================================================
static ggml_backend_t g_qnn_backend = nullptr;
static int g_current_device = QNN_BACKEND_GGML;
//QNN cDSP and HTA backend would not be used currently, just focus on QNN CPU/GPU/NPU(aka HTP/DSP) backend currently
static struct ggml_backend_qnn_context g_qnn_mgr[GGML_QNN_MAX_DEVICES] = {
[QNN_BACKEND_CPU] = {.device = 0, .threads = 1, .name = "qnn-cpu", .lib = "libQnnCpu.so", .instance = nullptr, .backend = nullptr, .raw_interface = {}, .raw_system_interface = {}},
[QNN_BACKEND_GPU] = {.device = 1, .threads = 1, .name = "qnn-gpu", .lib = "libQnnGpu.so", .instance = nullptr, .backend = nullptr, .raw_interface = {}, .raw_system_interface = {}},
[QNN_BACKEND_NPU] = {.device = 2, .threads = 1, .name = "qnn-npu", .lib = "libQnnHtp.so", .instance = nullptr, .backend = nullptr, .raw_interface = {}, .raw_system_interface = {}},
};
// =================================================================================================
//
// QNN helper functions and other internal helper functions
//
// =================================================================================================
static inline int validate_tensor_version(Qnn_Tensor_t tensor) {
if (tensor.version != QNN_TENSOR_VERSION_1) {
QNN_LOG_WARN("validate_tensor_version() tensor %s, got unsupported version %d\n",
tensor.v1.name,
tensor.version);
return 1;
}
return 0;
}
[[maybe_unused]] static inline int validate_op_config_version(Qnn_OpConfig_t op_config) {
if (op_config.version != QNN_OPCONFIG_VERSION_1) {
QNN_LOG_WARN("validate_op_config_version() op %s, got unsupported version %d\n",
op_config.v1.name,
op_config.version);
return 1;
}
return 0;
}
static inline const char * get_qnn_oponfig_name(const Qnn_OpConfig_t & op_config) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
return op_config.v1.name;
}
return nullptr;
}
[[maybe_unused]] static inline const char * get_qnn_oponfig_name(const Qnn_OpConfig_t * op_config) {
return get_qnn_oponfig_name(*op_config);
}
static inline const char * get_qnn_op_config_packagename(const Qnn_OpConfig_t & op_config) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
return op_config.v1.packageName;
}
return nullptr;
}
[[maybe_unused]] static inline const char * get_qnn_op_config_packagename(const Qnn_OpConfig_t * op_config) {
return get_qnn_op_config_packagename(*op_config);
}
static inline const char * get_qnn_op_config_typename(const Qnn_OpConfig_t & op_config) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
return op_config.v1.typeName;
}
return nullptr;
}
[[maybe_unused]] static inline const char * get_qnn_op_config_typename(const Qnn_OpConfig_t * op_config) {
return get_qnn_op_config_typename(*op_config);
}
static inline uint32_t get_qnn_op_config_numparams(const Qnn_OpConfig_t & op_config) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
return op_config.v1.numOfParams;
}
return 0u;
}
[[maybe_unused]] static inline uint32_t get_qnn_op_config_numparams(const Qnn_OpConfig_t * op_config) {
return get_qnn_op_config_numparams(*op_config);
}
static inline const Qnn_Param_t * get_qnn_op_config_params(const Qnn_OpConfig_t & op_config) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
return op_config.v1.params;
}
return nullptr;
}
[[maybe_unused]] static inline const Qnn_Param_t * get_qnn_op_config_params(const Qnn_OpConfig_t * op_config) {
return get_qnn_op_config_params(*op_config);
}
static inline uint32_t get_qnn_op_config_numinputs(const Qnn_OpConfig_t & op_config) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
return op_config.v1.numOfInputs;
}
return 0u;
}
[[maybe_unused]] static inline uint32_t get_qnn_op_config_numinputs(const Qnn_OpConfig_t * op_config) {
return get_qnn_op_config_numinputs(*op_config);
}
static inline const Qnn_Tensor_t * get_qnn_op_config_inputs(const Qnn_OpConfig_t & op_config) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
return op_config.v1.inputTensors;
}
return nullptr;
}
[[maybe_unused]] static inline const Qnn_Tensor_t * get_qnn_op_config_inputs(const Qnn_OpConfig_t * op_config) {
return get_qnn_op_config_inputs(*op_config);
}
static inline uint32_t get_qnn_op_config_numoutputs(const Qnn_OpConfig_t & op_config) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
return op_config.v1.numOfOutputs;
}
return 0u;
}
[[maybe_unused]] static inline uint32_t get_qnn_op_config_numoutputs(const Qnn_OpConfig_t * op_config) {
return get_qnn_op_config_numoutputs(*op_config);
}
static inline const Qnn_Tensor_t * get_qnn_op_config_outputs(const Qnn_OpConfig_t & op_config) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
return op_config.v1.outputTensors;
}
return nullptr;
}
[[maybe_unused]] static inline const Qnn_Tensor_t * get_qnn_op_config_outputs(const Qnn_OpConfig_t * op_config) {
return get_qnn_op_config_outputs(*op_config);
}
static inline void set_qnn_op_config_name(Qnn_OpConfig_t & op_config, const char * name) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
op_config.v1.name = name;
}
}
[[maybe_unused]] static inline void set_qnn_op_config_name(Qnn_OpConfig_t * op_config, const char * name) {
set_qnn_op_config_name(*op_config, name);
}
static inline void set_qnn_op_config_packagename(Qnn_OpConfig_t & op_config, const char * package_name) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
op_config.v1.packageName = package_name;
}
}
[[maybe_unused]] static inline void set_qnn_op_config_packagename(Qnn_OpConfig_t * op_config, const char * package_name) {
set_qnn_op_config_packagename(*op_config, package_name);
}
static inline void set_qnn_op_config_typename(Qnn_OpConfig_t & op_config, const char * type_name) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
op_config.v1.typeName = type_name;
}
}
[[maybe_unused]] static inline void set_qnn_op_config_typename(Qnn_OpConfig_t * op_config, const char * type_name) {
set_qnn_op_config_typename(*op_config, type_name);
}
static inline void set_qnn_op_config_params(Qnn_OpConfig_t & op_config,
uint32_t num_of_params,
Qnn_Param_t * params) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
op_config.v1.numOfParams = num_of_params;
op_config.v1.params = params;
}
}
[[maybe_unused]] static inline void set_qnn_op_config_params(Qnn_OpConfig_t * op_config,
uint32_t num_of_params,
Qnn_Param_t * params) {
set_qnn_op_config_params(*op_config, num_of_params, params);
}
static inline void set_qnn_op_config_inputs(Qnn_OpConfig_t & op_config,
uint32_t num_of_inputs,
Qnn_Tensor_t * input_tensors) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
op_config.v1.numOfInputs = num_of_inputs;
op_config.v1.inputTensors = input_tensors;
}
}
[[maybe_unused]] static inline void set_qnn_op_config_inputs(Qnn_OpConfig_t * op_config,
uint32_t num_of_inputs,
Qnn_Tensor_t * input_tensors) {
set_qnn_op_config_inputs(*op_config, num_of_inputs, input_tensors);
}
static inline void set_qnn_op_config_outputs(Qnn_OpConfig_t & op_config,
uint32_t num_of_outputs,
Qnn_Tensor_t * output_tensors) {
if (op_config.version == QNN_OPCONFIG_VERSION_1) {
op_config.v1.numOfOutputs = num_of_outputs;
op_config.v1.outputTensors = output_tensors;
}
}
[[maybe_unused]] static inline void set_qnn_op_config_outputs(Qnn_OpConfig_t * op_config,
uint32_t num_of_outputs,
Qnn_Tensor_t * output_tensors) {
set_qnn_op_config_outputs(*op_config, num_of_outputs, output_tensors);
}
static inline uint32_t get_qnn_tensorid(const Qnn_Tensor_t & tensor) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
return tensor.v1.id;
}
return 0u;
}
[[maybe_unused]] static inline uint32_t get_qnn_tensorid(const Qnn_Tensor_t * tensor) {
return get_qnn_tensorid(*tensor);
}
static inline const char * get_qnn_tensorname(const Qnn_Tensor_t & tensor) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
return tensor.v1.name;
}
return nullptr;
}
static inline const char * get_qnn_tensorname(const Qnn_Tensor_t * tensor) {
return get_qnn_tensorname(*tensor);
}
static inline Qnn_TensorType_t get_qnn_tensortype(const Qnn_Tensor_t & tensor) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
return tensor.v1.type;
}
return QNN_TENSOR_TYPE_UNDEFINED;
}
[[maybe_unused]] static inline Qnn_TensorType_t get_qnn_tensortype(const Qnn_Tensor_t * tensor) {
return get_qnn_tensortype(*tensor);
}
static inline Qnn_TensorDataFormat_t get_qnn_tensor_dataformat(const Qnn_Tensor_t & tensor) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
return tensor.v1.dataFormat;
}
return QNN_TENSOR_DATA_FORMAT_FLAT_BUFFER;
}
[[maybe_unused]] static inline Qnn_TensorDataFormat_t get_qnn_tensor_dataformat(const Qnn_Tensor_t * tensor) {
return get_qnn_tensor_dataformat(*tensor);
}
static inline Qnn_DataType_t get_qnn_tensor_datatype(const Qnn_Tensor_t & tensor) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
return tensor.v1.dataType;
}
return QNN_DATATYPE_UNDEFINED;
}
[[maybe_unused]] static inline Qnn_DataType_t get_qnn_tensor_datatype(const Qnn_Tensor_t * tensor) {
return get_qnn_tensor_datatype(*tensor);
}
static inline Qnn_QuantizeParams_t get_qnn_tensor_quantparams(const Qnn_Tensor_t & tensor) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
return tensor.v1.quantizeParams;
}
return QNN_QUANTIZE_PARAMS_INIT;
}
[[maybe_unused]] static inline Qnn_QuantizeParams_t get_qnn_tensor_quantparams(const Qnn_Tensor_t * tensor) {
return get_qnn_tensor_quantparams(*tensor);
}
static inline uint32_t get_qnn_tensor_rank(const Qnn_Tensor_t & tensor) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
return tensor.v1.rank;
}
return 0u;
}
[[maybe_unused]] static inline uint32_t get_qnn_tensor_rank(const Qnn_Tensor_t * tensor) {
return get_qnn_tensor_rank(*tensor);
}
static inline uint32_t * get_qnn_tensor_dimensions(const Qnn_Tensor_t & tensor) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
return tensor.v1.dimensions;
}
return nullptr;
}
[[maybe_unused]] static inline uint32_t * get_qnn_tensor_dimensions(const Qnn_Tensor_t * tensor) {
return get_qnn_tensor_dimensions(*tensor);
}
static inline Qnn_TensorMemType_t get_qnn_tensor_memtype(const Qnn_Tensor_t & tensor) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
return tensor.v1.memType;
}
return QNN_TENSORMEMTYPE_UNDEFINED;
}
[[maybe_unused]] static inline Qnn_TensorMemType_t get_qnn_tensor_memtype(const Qnn_Tensor_t * tensor) {
return get_qnn_tensor_memtype(*tensor);
}
static inline Qnn_ClientBuffer_t get_qnn_tensor_clientbuf(const Qnn_Tensor_t & tensor) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
return tensor.v1.clientBuf;
}
return QNN_CLIENT_BUFFER_INIT;
}
[[maybe_unused]] static inline Qnn_ClientBuffer_t get_qnn_tensor_clientbuf(const Qnn_Tensor_t * tensor) {
return get_qnn_tensor_clientbuf(*tensor);
}
static inline Qnn_MemHandle_t get_qnn_tensor_memhandle(const Qnn_Tensor_t & tensor) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
return tensor.v1.memHandle;
}
return nullptr;
}
[[maybe_unused]] static inline Qnn_MemHandle_t get_qnn_tensor_memhandle(const Qnn_Tensor_t * tensor) {
return get_qnn_tensor_memhandle(*tensor);
}
static inline void set_qnn_tensor_id(Qnn_Tensor_t & tensor, uint32_t id) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
tensor.v1.id = id;
}
}
[[maybe_unused]] static inline void set_qnn_tensor_id(Qnn_Tensor_t * tensor, uint32_t id) {
set_qnn_tensor_id(*tensor, id);
}
static inline void set_qnn_tensor_name(Qnn_Tensor_t & tensor, const char * name) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
tensor.v1.name = name;
}
}
[[maybe_unused]] static inline void set_qnn_tensor_name(Qnn_Tensor_t * tensor, const char * name) {
set_qnn_tensor_name(*tensor, name);
}
static inline void set_qnn_tensor_type(Qnn_Tensor_t & tensor, Qnn_TensorType_t type) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
tensor.v1.type = type;
}
}
[[maybe_unused]] static inline void set_qnn_tensor_type(Qnn_Tensor_t * tensor, Qnn_TensorType_t type) {
set_qnn_tensor_type(*tensor, type);
}
static inline void set_qnn_tensor_dataformat(Qnn_Tensor_t & tensor, Qnn_TensorDataFormat_t format) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
tensor.v1.dataFormat = format;
}
}
[[maybe_unused]] static inline void set_qnn_tensor_dataformat(Qnn_Tensor_t * tensor, Qnn_TensorDataFormat_t format) {
set_qnn_tensor_dataformat(*tensor, format);
}
static inline void set_qnn_tensor_datatype(Qnn_Tensor_t & tensor, Qnn_DataType_t dataType) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
tensor.v1.dataType = dataType;
}
}
[[maybe_unused]] static inline void set_qnn_tensor_datatype(Qnn_Tensor_t * tensor, Qnn_DataType_t dataType) {
set_qnn_tensor_datatype(*tensor, dataType);
}
static inline void set_qnn_tensor_quantparams(Qnn_Tensor_t & tensor, Qnn_QuantizeParams_t params) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
tensor.v1.quantizeParams = params;
}
}
[[maybe_unused]] static inline void set_qnn_tensor_quantparams(Qnn_Tensor_t * tensor, Qnn_QuantizeParams_t params) {
set_qnn_tensor_quantparams(*tensor, params);
}
static inline void set_qnn_tensor_rank(Qnn_Tensor_t & tensor, uint32_t rank) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
tensor.v1.rank = rank;
}
}
[[maybe_unused]] static inline void set_qnn_tensor_rank(Qnn_Tensor_t * tensor, uint32_t rank) {
set_qnn_tensor_rank(*tensor, rank);
}
static inline void set_qnn_tensor_dimensions(Qnn_Tensor_t & tensor, uint32_t * dims) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
tensor.v1.dimensions = dims;
}
}
[[maybe_unused]] static inline void set_qnn_tensor_dimensions(Qnn_Tensor_t * tensor, uint32_t * dims) {
set_qnn_tensor_dimensions(*tensor, dims);
}
static inline void set_qnn_tensor_memtype(Qnn_Tensor_t & tensor, Qnn_TensorMemType_t memType) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
tensor.v1.memType = memType;
}
}
[[maybe_unused]] static inline void set_qnn_tensor_memtype(Qnn_Tensor_t * tensor, Qnn_TensorMemType_t memType) {
set_qnn_tensor_memtype(*tensor, memType);
}
static inline void set_qnn_tensor_clientbuf(Qnn_Tensor_t & tensor, Qnn_ClientBuffer_t clientBuf) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
tensor.v1.clientBuf = clientBuf;
}
}
[[maybe_unused]] static inline void set_qnn_tensor_clientbuf(Qnn_Tensor_t * tensor, Qnn_ClientBuffer_t clientBuf) {
set_qnn_tensor_clientbuf(*tensor, clientBuf);
}
static inline void set_qnn_tensor_memhandle(Qnn_Tensor_t & tensor, Qnn_MemHandle_t handle) {
if (tensor.version == QNN_TENSOR_VERSION_1) {
tensor.v1.memHandle = handle;
}
}
[[maybe_unused]] static inline void set_qnn_tensor_memhandle(Qnn_Tensor_t * tensor, Qnn_MemHandle_t handle) {
set_qnn_tensor_memhandle(*tensor, handle);
}
static size_t memscpy(void * dst, size_t dstSize, const void * src, size_t copySize) {
if (!dst || !src || !dstSize || !copySize)
return 0;
size_t minSize = dstSize < copySize ? dstSize : copySize;
memcpy(dst, src, minSize);
return minSize;
}
static char * ggml_qnn_strndup(const char * source, size_t maxlen) {
return ::strndup(source, maxlen);
}
static int deep_copy_qnn_tensors(Qnn_Tensor_t & src, Qnn_Tensor_t & dst) {
int err = 0;
VALIDATE_TENSOR_VERSION(src, err);
dst.version = src.version;
QNN_TENSOR_SET_NAME(
dst, ggml_qnn_strndup(QNN_TENSOR_GET_NAME(src), std::string(QNN_TENSOR_GET_NAME(src)).size()));
if (QNN_TENSOR_GET_NAME(dst) == nullptr) {
return 1;
}
QNN_TENSOR_SET_ID(dst, QNN_TENSOR_GET_ID(src));
QNN_TENSOR_SET_TYPE(dst, QNN_TENSOR_GET_TYPE(src));
QNN_TENSOR_SET_DATA_FORMAT(dst, QNN_TENSOR_GET_DATA_FORMAT(src));
QNN_TENSOR_SET_DATA_TYPE(dst, QNN_TENSOR_GET_DATA_TYPE(src));
QNN_TENSOR_SET_MEM_TYPE(dst, QNN_TENSOR_GET_MEM_TYPE(src));
// Only metadata (i.e. non-static data) is copied from source to destination. The union still
// must be initialized so that the clientBuf/memHandle do not contain garbage data
if (QNN_TENSOR_GET_MEM_TYPE(src) == QNN_TENSORMEMTYPE_RAW) {
Qnn_ClientBuffer_t client_buf = {nullptr, 0};
QNN_TENSOR_SET_CLIENT_BUF(dst, client_buf);
} else if (QNN_TENSOR_GET_MEM_TYPE(src) == QNN_TENSORMEMTYPE_MEMHANDLE) {
QNN_TENSOR_SET_MEM_HANDLE(dst, nullptr);
} else {
return 1;
}
Qnn_QuantizeParams_t src_qparam = QNN_TENSOR_GET_QUANT_PARAMS(src);
Qnn_QuantizationEncoding_t encoding = src_qparam.quantizationEncoding;
if (encoding == QNN_QUANTIZATION_ENCODING_AXIS_SCALE_OFFSET) {
// need to allocate and copy memory for scaleOffset as it is a pointer array
Qnn_QuantizeParams_t src_qparam_cpy = src_qparam;
Qnn_AxisScaleOffset_t &axis_scale_offset = src_qparam_cpy.axisScaleOffsetEncoding;
Qnn_ScaleOffset_t **scaleOffset = &axis_scale_offset.scaleOffset;
size_t scaleOffsetSize = axis_scale_offset.numScaleOffsets * sizeof(Qnn_ScaleOffset_t);
*scaleOffset = (Qnn_ScaleOffset_t *)malloc(scaleOffsetSize);
memscpy(*scaleOffset,
scaleOffsetSize,
src_qparam.axisScaleOffsetEncoding.scaleOffset,
scaleOffsetSize);
QNN_TENSOR_SET_QUANT_PARAMS(dst, src_qparam_cpy);
} else if (encoding == QNN_QUANTIZATION_ENCODING_BW_AXIS_SCALE_OFFSET) {
// need to allocate and copy memory for scaleOffset as it is a pointer array
Qnn_QuantizeParams_t src_qparam_cpy = src_qparam;
Qnn_BwAxisScaleOffset_t &bwaxis_scale_offset = src_qparam_cpy.bwAxisScaleOffsetEncoding;
size_t scaleSize = bwaxis_scale_offset.numElements * sizeof(float);
float **scales = &bwaxis_scale_offset.scales;
int32_t **offsets = &bwaxis_scale_offset.offsets;
*scales = (float *)malloc(scaleSize);
memscpy(*scales, scaleSize, src_qparam.bwAxisScaleOffsetEncoding.scales, scaleSize);
// only copy offsets if present, nullptr implies all offsets are 0
if (bwaxis_scale_offset.offsets != nullptr) {
size_t offsetSize = bwaxis_scale_offset.numElements * sizeof(int32_t);
*offsets = (int32_t *)malloc(offsetSize);
memscpy(*offsets, offsetSize, src_qparam.bwAxisScaleOffsetEncoding.offsets, offsetSize);
}
QNN_TENSOR_SET_QUANT_PARAMS(dst, src_qparam_cpy);
} else {
QNN_TENSOR_SET_QUANT_PARAMS(dst, src_qparam);
}
// allocate and copy memory for all the pointer members
uint32_t rank = QNN_TENSOR_GET_RANK(src);
QNN_TENSOR_SET_RANK(dst, rank);
size_t dim_size = rank * sizeof(uint32_t);
uint32_t * dimensions = (uint32_t *)malloc(dim_size);
if (dimensions == nullptr) {
QNN_LOG_WARN("deep_copy_qnn_tensors() allocation error while copying tensor %s\n", QNN_TENSOR_GET_NAME(src));
return 1;
}
memscpy(dimensions, dim_size, QNN_TENSOR_GET_DIMENSIONS(src), dim_size);
QNN_TENSOR_SET_DIMENSIONS(dst, dimensions);
return err;
}
static int free_qnn_tensor(Qnn_Tensor_t & tensor) {
int err = 0;
VALIDATE_TENSOR_VERSION(tensor, err);
free((void *) QNN_TENSOR_GET_NAME(tensor));
free(QNN_TENSOR_GET_DIMENSIONS(tensor));
return err;
}
[[maybe_unused]] static int free_qnn_tensors(Qnn_Tensor_t *& tensors, uint32_t num_tensors) {
int err = 0;
// free all pointer allocations in struct
for (size_t i = 0; i < num_tensors; i++) {
free_qnn_tensor(tensors[i]);
}
free(tensors);
return err;
}
static uint32_t ggml_get_tensor_rank(const ggml_tensor * tensor) {
uint32_t rank = 0;
for (int i = 0; i < GGML_MAX_DIMS; i++) {
if ((0 != tensor->ne[i]) && (1 != tensor->ne[i])) {
rank++;
}
}
return rank;
}
//TODO: mapping more ggml data type to QNN data type
//ref:explanation of k-quants, https://github.com/ggerganov/llama.cpp/pull/1684
static Qnn_DataType_t qnn_datatype_from_ggml_datatype(enum ggml_type ggmltype) {
switch (ggmltype) {
case GGML_TYPE_F16:
return QNN_DATATYPE_FLOAT_16;
case GGML_TYPE_F32:
return QNN_DATATYPE_FLOAT_32;
default:
break;
}
return QNN_DATATYPE_UNDEFINED;
}
//TODO: only support GGML_OP_ADD/GGML_OP_MUL/GGML_OP_MUL_MAT
static const char * qnn_opname_from_ggmlop(enum ggml_op ggmlop) {
switch (ggmlop) {
case GGML_OP_ADD:
return QNN_OP_ELEMENT_WISE_ADD;
case GGML_OP_MUL:
return QNN_OP_ELEMENT_WISE_MULTIPLY;
case GGML_OP_MUL_MAT:
return QNN_OP_MAT_MUL;
default:
break;
}
return nullptr;
}
static uint32_t ggml_get_tensor_data_size(const ggml_tensor * tensor) {
/*
size_t data_size = ggml_row_size(tensor->type, tensor->ne[0]);
size_t n_dims = ggml_get_tensor_rank(tensor);
for (int i = 1; i < n_dims; i++) {
data_size *= tensor->ne[i];
}
return data_size;
*/
return ggml_nbytes(tensor);
}
template<typename Fn>
Fn load_qnn_functionpointers(void * handle, const char * function_name) {
return reinterpret_cast<Fn>(dlsym(handle, function_name));
}
static const char * get_qnn_backend_name(int n_backend_type) {
switch (n_backend_type) {
case 0:
return "QNN-CPU";
case 1:
return "QNN-GPU";
case 2:
return "QNN-NPU";
case 3:
return "ggml"; //the default GGML backend, used to compare performance between QNN backend and the default GGML backend
#if 0 //QNN cDSP and HTA backend would not be used currently, focus on QNN CPU/GPU/NPU(aka HTP/DSP) backend currently
case 3:
return "QNN-cDSP";
case 4:
return "QNN-HTA";
#endif
default:
return "unknown";
}
}
static intptr_t align_to(size_t alignment, intptr_t offset) {
return offset % alignment == 0 ? offset
: offset +
(static_cast<intptr_t>(alignment) -
offset % static_cast<intptr_t>(alignment));
}
static void ggml_qnn_log_internal(ggml_log_level level, const char * file, const char * func, int line, const char * format, ...) {
static std::mutex ggml_qnn_log_internal_mutex;
static char s_ggml_qnn_log_internal_buf[GGML_QNN_LOGBUF_LEN];
{
std::lock_guard<std::mutex> lock(ggml_qnn_log_internal_mutex);
va_list args;
va_start(args, format);
int len_prefix = snprintf(s_ggml_qnn_log_internal_buf, GGML_QNN_LOGBUF_LEN, "[%s, %d]: ", func, line);
int len = vsnprintf(s_ggml_qnn_log_internal_buf + len_prefix, GGML_QNN_LOGBUF_LEN - len_prefix, format, args);
if (len < (GGML_QNN_LOGBUF_LEN - len_prefix)) {
#if (defined __ANDROID__) || (defined ANDROID)
//for Android APK
#if 1// NOT_IN_PR
__android_log_print(level, "KANTV", "%s\n", s_ggml_qnn_log_internal_buf);
#else
__android_log_print(level, "ggml-qnn", "%s\n", s_ggml_qnn_log_internal_buf);