-
Notifications
You must be signed in to change notification settings - Fork 22
/
Copy pathggml-jni-impl-external.cpp
7464 lines (6292 loc) · 276 KB
/
ggml-jni-impl-external.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
/*
* the following is NOT 100% original source code,
*
* just for:
*
* study internal mechanism of GGML(Georgi Gerganov Machine Learning, https://github.com/ggerganov/ggml)
*
* study various open source pure C/C++ AI projects based on GGML(such as llama.cpp, stablediffusion.cpp)
*
* implementation of PoC S2 & PoC S3 (merged into this file on 04/15/2024), https://github.com/zhouwg/kantv/issues/121
*
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <string.h>
#include <stddef.h>
#include <unistd.h>
#include <inttypes.h>
#include <math.h>
#include <time.h>
#include <unistd.h>
#include <dlfcn.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <limits.h>
#include <signal.h>
#include <fcntl.h>
#include <sys/types.h>
extern "C" {
#include "libavutil/avstring.h"
#include "libavutil/eval.h"
#include "libavutil/mathematics.h"
#include "libavutil/pixdesc.h"
#include "libavutil/imgutils.h"
#include "libavutil/dict.h"
#include "libavutil/parseutils.h"
#include "libavutil/avassert.h"
#include "libavutil/time.h"
#include "libavformat/avformat.h"
#include "libavcodec/avcodec.h"
#include "libswscale/swscale.h"
#include "libavcodec/avfft.h"
#include "libswresample/swresample.h"
#include "libavutil/log.h"
#include "libavutil/avutil.h"
#include "libavutil/opt.h"
#include "libavutil/samplefmt.h"
#include "libswresample/swresample.h"
#include "libavutil/myfifo.h"
#include "libavutil/cde_log.h"
#include "libavutil/cde_assert.h"
#if CONFIG_AVFILTER
#include "libavfilter/avfilter.h"
#include "libavfilter/buffersink.h"
#include "libavfilter/buffersrc.h"
#endif
}
#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 "ggml.h"
#include "ggml-alloc.h"
#include "ggml-backend.h"
#include "kantv-asr.h"
#include "ggml-jni.h"
#include "whisper.h"
#include "llama.h"
#include "llamacpp/ggml/include/ggml-hexagon.h"
// =================================================================================================
//
// JNI helper function for llama.cpp
// all the following codes comes from examples/main.cpp in project llama.cpp
//
// trying to integrate llama.cpp from 03/26/2024 - 03/28/2024
// =================================================================================================
#include "sampling.h"
#define log_tostr(var) log_var_to_string_impl(var).c_str()
static bool ggml_graph_compute_helper(
struct ggml_backend *backend,
struct ggml_cgraph *graph,
std::vector<uint8_t> &buf,
int n_threads,
ggml_abort_callback abort_callback,
void *abort_callback_data) {
struct ggml_cplan plan = ggml_graph_plan(graph, n_threads, NULL);
plan.abort_callback = abort_callback;
plan.abort_callback_data = abort_callback_data;
if (plan.work_size > 0) {
buf.resize(plan.work_size);
plan.work_data = buf.data();
}
if (ggml_backend_is_cpu(backend)) {
ggml_backend_cpu_set_n_threads(backend, n_threads);
}
//a new approch of mixed inference
if (nullptr != backend)
return ggml_backend_graph_compute(backend, graph) == GGML_STATUS_SUCCESS;
else
return ggml_graph_compute(graph, &plan);
}
static float tensor_sum_elements(const ggml_tensor *tensor) {
double sum = 0;
float value = 0;
std::ostringstream tmposs;
if (tensor->type == GGML_TYPE_F32) {
for (int h = 0; h < tensor->ne[3]; h++) {
for (int i = 0; i < tensor->ne[2]; i++) {
for (int j = 0; j < tensor->ne[1]; j++) {
for (int k = 0; k < tensor->ne[0]; k++) {
value = ((float *) tensor->data)[h * tensor->ne[2] + i * tensor->ne[1] +
j * tensor->ne[0] + k];
sum += value;
//LOGGD("[%d][%d][%d][%d]%.2f \t", h, i, j, k, value);
tmposs << std::setw(8) << std::fixed << std::setprecision(2) << value
<< "\t";
}
if (strlen(tmposs.str().c_str()) > 4000) {
} else {
LOGGD("%s", tmposs.str().c_str());
GGML_JNI_NOTIFY("%s", tmposs.str().c_str());
}
tmposs.clear();
tmposs.str("");
//LOGGD("\n");
}
}
}
}
if (tensor->type == GGML_TYPE_Q8_0) {
for (int h = 0; h < tensor->ne[3]; h++) {
for (int i = 0; i < tensor->ne[2]; i++) {
for (int j = 0; j < tensor->ne[1]; j++) {
for (int k = 0; k < tensor->ne[0]; k++) {
value = ((int8_t *) tensor->data)[h * tensor->ne[2] + i * tensor->ne[1] +
j * tensor->ne[0] + k];
sum += value;
//LOGGD("[%d][%d][%d][%d]%.2f \t", h, i, j, k, value);
tmposs << std::setw(8) << std::fixed << std::setprecision(2) << value
<< "\t";
}
if (strlen(tmposs.str().c_str()) > 4000) {
} else {
LOGGD("%s", tmposs.str().c_str());
GGML_JNI_NOTIFY("%s", tmposs.str().c_str());
}
tmposs.clear();
tmposs.str("");
//LOGGD("\n");
}
}
}
}
//LOGGD("\n");
return sum;
}
static void tensor_dump(const ggml_tensor *tensor, const char *name) {
LOGGD("dump ggml tensor %s(%s)", name, tensor->name);
GGML_JNI_NOTIFY("dump ggml tensor %s(%s)", name, tensor->name);
LOGGD("%15s: type = %i (%5s) ne = %5" PRIi64 " x %5" PRIi64 " x %5" PRIi64 ", nb = (%5zi, %5zi, %5zi)",
name,
tensor->type, ggml_type_name(tensor->type),
tensor->ne[0], tensor->ne[1], tensor->ne[2], tensor->nb[0], tensor->nb[1], tensor->nb[2]);
float sum = tensor_sum_elements(tensor);
LOGGD("\n");
//LOGGD("Sum of tensor %s is %6.2f\n", name, sum);
}
#define TENSOR_DUMP(tensor) tensor_dump(tensor, #tensor)
static uint32_t 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++;
}
}
//LOGGD("tensor->rank %d\n", tensor->rank);
LOGGD("get_tensor_rank %d\n", rank);
return rank;
}
static uint32_t get_tensor_data_size(const ggml_tensor *tensor) {
size_t data_size = ggml_row_size(tensor->type, tensor->ne[0]);
size_t n_dims = get_tensor_rank(tensor);
for (int i = 1; i < n_dims; i++) {
data_size *= tensor->ne[i];
}
LOGGD("get_tensor_data_size %d", data_size);
LOGGD("ggml_nbytes(tensor) %d", ggml_nbytes(tensor));
return ggml_nbytes(tensor);
}
const char *ggml_jni_bench_mulmat(int n_threads, int n_backend) {
static std::string s;
s = "";
char strbuf[256];
#ifdef TARGET_ANDROID
static std::string tipString;
tipString = "";
tipString += "calling ggml_time_init";
kantv_asr_notify_benchmark_c("calling ggml_time_init\n");
#endif
ggml_time_init();
const int n_max = 128;
const std::vector<size_t> sizes = {
64, 128, 256, 512, 1024, 2048, 4096,
};
const size_t N_max = sizes.back();
// a: N*N*sizeof(float)
// b: N*N*sizeof(float)
// c: N*N*sizeof(float)
// when F16 is used, there is an extra work buffer of size N*N*sizeof(float)
std::vector<uint8_t> buf(3llu * N_max * N_max * sizeof(float) + 3 * ggml_tensor_overhead() +
ggml_graph_overhead());
std::vector<uint8_t> work;
#ifdef TARGET_ANDROID
tipString += "\nprepare matrix";
kantv_asr_notify_benchmark_c("prepare matrix\n");
#endif
// put a bunch of random data in the buffer
for (size_t i = 0; i < buf.size(); i++) buf[i] = i;
for (int j = 0; j < (int) sizes.size(); j++) {
int n_q4_0 = 0;
int n_q4_1 = 0;
int n_q5_0 = 0;
int n_q5_1 = 0;
int n_q8_0 = 0;
int n_fp16 = 0;
int n_fp32 = 0;
// GFLOPS/s
double s_q4_0 = 0.0;
double s_q4_1 = 0.0;
double s_q5_0 = 0.0;
double s_q5_1 = 0.0;
double s_q8_0 = 0.0;
double s_fp16 = 0.0;
double s_fp32 = 0.0;
const size_t N = sizes[j];
if (1 == ggml_jni_get_abortbenchmark_flag()) {
break;
}
#if 1
for (int k = 0; k < 7; ++k) {
const ggml_type wtype =
k == 0 ? GGML_TYPE_Q4_0 :
k == 1 ? GGML_TYPE_Q4_1 :
k == 2 ? GGML_TYPE_Q5_0 :
k == 3 ? GGML_TYPE_Q5_1 :
k == 4 ? GGML_TYPE_Q8_0 :
k == 5 ? GGML_TYPE_F16 : GGML_TYPE_F32;
#else
for (int k = 5; k < 7; ++k) {
const ggml_type wtype =
k == 5 ? GGML_TYPE_F16 : GGML_TYPE_F32; //TODO: only f16&f32 supported with QNN backend
#endif
if (1 == ggml_jni_get_abortbenchmark_flag()) {
break;
}
double &s =
k == 0 ? s_q4_0 : k == 1 ? s_q4_1 : k == 2 ? s_q5_0 : k == 3 ? s_q5_1 : k == 4
? s_q8_0
: k == 5
? s_fp16
: /*k == 6*/ s_fp32;
int &n = k == 0 ? n_q4_0 : k == 1 ? n_q4_1 : k == 2 ? n_q5_0 : k == 3 ? n_q5_1 : k == 4
? n_q8_0
: k ==
5
? n_fp16
: /*k == 6*/ n_fp32;
ggml_backend_t backend = nullptr;
ggml_backend_buffer_t buffer = nullptr;
#ifdef GGML_USE_HEXAGON
if (n_backend !=
HEXAGON_BACKEND_GGML) {
backend = ggml_backend_hexagon_init(n_backend,
"/data/data/com.kantvai.kantvplayer/qnnlib/"); // the second param can be got by JNI from Java layer
if (nullptr == backend) {
LOGGD("create qnn backend %d failed", n_backend);
GGML_JNI_NOTIFY("create qnn backend %d failed", n_backend);
return "unknown";
}
n_threads = 1; // make QNN backend happy because this scenario is in JNI, data path here is totally different with whisper.cpp/llama.cpp
}
#endif
struct ggml_init_params gparams = {
/*.mem_size =*/ buf.size(),
/*.mem_buffer =*/ buf.data(),
/*.no_alloc =*/ false,
};
#ifdef GGML_USE_HEXAGON
if (n_backend != HEXAGON_BACKEND_GGML) {
//gparams.use_hwaccel = true;
gparams.no_alloc = true;
}
#endif
struct ggml_context *ctx0 = ggml_init(gparams);
struct ggml_tensor *a = ggml_new_tensor_2d(ctx0, wtype, N, N);
struct ggml_tensor *b = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, N, N);
ggml_set_input(a);
ggml_set_input(b);
struct ggml_tensor *c = ggml_mul_mat(ctx0, a, b);
ggml_set_output(c);
#ifdef GGML_USE_HEXAGON
if (n_backend != HEXAGON_BACKEND_GGML) {
buffer = ggml_backend_alloc_ctx_tensors(ctx0, backend);
if (!buffer) {
LOGGD("%s: failed to allocate backend buffer\n", __func__);
GGML_JNI_NOTIFY("%s: failed to allocate backend buffer\n", __func__);
ggml_backend_free(backend);
return "unknown";
}
}
#endif
struct ggml_cgraph *gf = ggml_new_graph(ctx0);
ggml_build_forward_expand(gf, c);
double tsum = 0.0;
// heat-up
ggml_graph_compute_helper(backend, gf, work, n_threads, nullptr, nullptr);
for (int i = 0; i < n_max; ++i) {
const int64_t t0 = ggml_time_us();
if (1 == ggml_jni_get_abortbenchmark_flag()) {
break;
}
#ifdef TARGET_ANDROID
kantv_asr_notify_benchmark_c("reset");
tipString = "calling ggml_graphic_compute_helper:\n";
tipString +=
"j= " + std::to_string(j) + "(matrix dimension = " + std::to_string(N) +
",n_max=" + std::to_string(n_max) + ")"
+ ",k=" + std::to_string(k) + "(ggml quant type=" +
std::string(ggml_jni_get_ggmltype_str(static_cast<ggml_type>(wtype))) + ")"
+ ",i=" + std::to_string(i) + "\n";
kantv_asr_notify_benchmark(tipString);
#endif
ggml_graph_compute_helper(backend, gf, work, n_threads, nullptr, nullptr);
const int64_t t1 = ggml_time_us();
tsum += (t1 - t0) * 1e-6;
n++;
if (tsum > 1.0 && n >= 3) {
break;
}
}
ggml_free(ctx0);
ggml_backend_buffer_free(buffer);
ggml_backend_free(backend);
s = ((2.0 * N * N * N * n) / tsum) * 1e-9;
}
#ifdef TARGET_ANDROID
kantv_asr_notify_benchmark_c("reset");
#endif
// Q4_0 | Q4_1
snprintf(strbuf, sizeof(strbuf),
"%4zu x %4zu: Q4_0 %7.1f GFLOPS (%3d runs) | Q4_1 %7.1f GFLOPS (%3d runs)\n",
N, N, s_q4_0, n_q4_0, s_q4_1, n_q4_1);
s += strbuf;
// Q5_0 | Q5_1 | Q8_0
snprintf(strbuf, sizeof(strbuf),
"%4zu x %4zu: Q5_0 %7.1f GFLOPS (%3d runs) | Q5_1 %7.1f GFLOPS (%3d runs) | Q8_0 %7.1f GFLOPS (%3d runs)\n",
N, N, s_q5_0, n_q5_0, s_q5_1, n_q5_1, s_q8_0, n_q8_0);
s += strbuf;
// F16 | F32
snprintf(strbuf, sizeof(strbuf),
"%4zu x %4zu: F16 %7.1f GFLOPS (%3d runs) | F32 %7.1f GFLOPS (%3d runs)\n",
N, N, s_fp16, n_fp16, s_fp32, n_fp32);
s += strbuf;
#ifdef TARGET_ANDROID
kantv_asr_notify_benchmark(s);
#endif
}
return s.c_str();
}
const char *ggml_jni_bench_memcpy(int n_threads) {
static std::string s;
s = "";
char strbuf[256];
#ifdef TARGET_ANDROID
kantv_asr_notify_benchmark_c("calling ggml_time_init\n");
#endif
ggml_time_init();
size_t n = 20;
size_t arr = n_threads > 0 ? 1024llu : n_threads; // trick to avoid compiler optimizations
// 1GB array
const size_t size = arr * 1e6;
double sum = 0.0;
// heat-up
{
char *src = (char *) malloc(size);
char *dst = (char *) malloc(size);
for (size_t i = 0; i < size; i++) src[i] = i;
memcpy(dst, src, size); // heat-up
double tsum = 0.0;
for (size_t i = 0; i < n; i++) {
const int64_t t0 = ggml_time_us();
memcpy(dst, src, size);
const int64_t t1 = ggml_time_us();
tsum += (t1 - t0) * 1e-6;
src[rand() % size] = rand() % 256;
}
snprintf(strbuf, sizeof(strbuf), "memcpy: %7.2f GB/s (heat-up)\n",
(double) (n * size) / (tsum * 1e9));
#ifdef TARGET_ANDROID
kantv_asr_notify_benchmark_c(strbuf);
#endif
s += strbuf;
// needed to prevent the compiler from optimizing the memcpy away
{
for (size_t i = 0; i < size; i++) sum += dst[i];
}
free(src);
free(dst);
}
// single-thread
{
char *src = (char *) malloc(size);
char *dst = (char *) malloc(size);
for (size_t i = 0; i < size; i++) src[i] = i;
memcpy(dst, src, size); // heat-up
double tsum = 0.0;
for (size_t i = 0; i < n; i++) {
const int64_t t0 = ggml_time_us();
memcpy(dst, src, size);
const int64_t t1 = ggml_time_us();
tsum += (t1 - t0) * 1e-6;
src[rand() % size] = rand() % 256;
}
snprintf(strbuf, sizeof(strbuf), "memcpy: %7.2f GB/s ( 1 thread)\n",
(double) (n * size) / (tsum * 1e9));
#ifdef TARGET_ANDROID
kantv_asr_notify_benchmark_c(strbuf);
#endif
s += strbuf;
// needed to prevent the compiler from optimizing the memcpy away
{
for (size_t i = 0; i < size; i++) sum += dst[i];
}
free(src);
free(dst);
}
// multi-thread
for (int32_t k = 1; k <= n_threads; k++) {
char *src = (char *) malloc(size);
char *dst = (char *) malloc(size);
for (size_t i = 0; i < size; i++) src[i] = i;
memcpy(dst, src, size); // heat-up
double tsum = 0.0;
auto helper = [&](int th) {
const int64_t i0 = (th + 0) * size / k;
const int64_t i1 = (th + 1) * size / k;
for (size_t i = 0; i < n; i++) {
memcpy(dst + i0, src + i0, i1 - i0);
src[i0 + rand() % (i1 - i0)] = rand() % 256;
};
};
const int64_t t0 = ggml_time_us();
std::vector<std::thread> threads(k - 1);
for (int32_t th = 0; th < k - 1; ++th) {
threads[th] = std::thread(helper, th);
}
helper(k - 1);
for (int32_t th = 0; th < k - 1; ++th) {
threads[th].join();
}
const int64_t t1 = ggml_time_us();
tsum += (t1 - t0) * 1e-6;
snprintf(strbuf, sizeof(strbuf), "memcpy: %7.2f GB/s (%2d thread)\n",
(double) (n * size) / (tsum * 1e9), k);
#ifdef TARGET_ANDROID
kantv_asr_notify_benchmark_c(strbuf);
#endif
s += strbuf;
// needed to prevent the compiler from optimizing the memcpy away
{
for (size_t i = 0; i < size; i++) sum += dst[i];
}
free(src);
free(dst);
}
snprintf(strbuf, sizeof(strbuf), "sum: %f\n", sum);
#ifdef TARGET_ANDROID
kantv_asr_notify_benchmark_c(strbuf);
#endif
s += strbuf;
return s.c_str();
}
// 03-26-2024,
// this function was referenced by this PR:https://github.com/ggerganov/llama.cpp/pull/5935/
// ref:https://github.com/ggerganov/llama.cpp/pull/5935/
bool ggml_jni_is_valid_utf8(const char *string) {
if (!string) {
return true;
}
const unsigned char *bytes = (const unsigned char *) string;
int num;
while (*bytes != 0x00) {
if ((*bytes & 0x80) == 0x00) {
// U+0000 to U+007F
num = 1;
} else if ((*bytes & 0xE0) == 0xC0) {
// U+0080 to U+07FF
num = 2;
} else if ((*bytes & 0xF0) == 0xE0) {
// U+0800 to U+FFFF
num = 3;
} else if ((*bytes & 0xF8) == 0xF0) {
// U+10000 to U+10FFFF
num = 4;
} else {
return false;
}
bytes += 1;
for (int i = 1; i < num; ++i) {
if ((*bytes & 0xC0) != 0x80) {
return false;
}
bytes += 1;
}
}
return true;
}
//similar with original llama_print_timings and dedicated for project kantv, for merge/update latest source code of llama.cpp more easily and quickly
void ggml_jni_llama_print_timings(struct llama_context *ctx) {
}
/**
*
* @param sz_model_path
* @param prompt
* @param bench_type not used currently
* @param n_threads 1 - 8
* @param n_backend 0: HEXAGON_BACKEND_QNNCPU 1: HEXAGON_BACKEND_QNNGPU 2: HEXAGON_BACKEND_QNNNPU, 3: HEXAGON_BACKEND_CDSP 4: ggml
* @return
*/
//don't remove and keep it for compare with llama inference using latest source code from upstream llama.cpp
int llama_inference(const char *model_path, const char *prompt, int bench_type, int num_threads,
int n_backend) {
return 0;
}
void ggml_bench_matrix(int num_threads, int backend_type) {
int32_t n_threads = 1;
int32_t n_iterations = 10;
bool invalid_param = false;
std::string arg;
int64_t n_begin_time = 0LL;
int64_t n_end_time = 0LL;
int64_t n_durtion = 0LL;
LOGGD("enter ggml_bench_matrix\n");
GGML_JNI_NOTIFY("Starting GGML matrix benchmark\n");
// create the ggml context
struct ggml_context *ctx;
//const int sizex = 4096;
//const int sizey = 11008;
#if 0
const int sizey = 2048;
const int sizex = 2048;
const int sizez = 128;
#else
const int sizey = 2;
const int sizex = 2;
const int sizez = 1;
#endif
GGML_JNI_NOTIFY("memsize required = %i\n", sizex * sizex);
const ggml_type qtype = GGML_TYPE_F32;
n_begin_time = ggml_time_us();
n_threads = num_threads;
size_t ctx_size = 0;
ctx_size += ggml_row_size(GGML_TYPE_F32, sizex * sizey);
ctx_size += ggml_row_size(GGML_TYPE_F32, sizex * sizey);
ctx_size += ggml_row_size(GGML_TYPE_F32, sizex * sizez);
ctx_size += ggml_row_size(qtype, sizex * sizey);
ctx_size += ggml_row_size(qtype, sizex * sizey);
ctx_size += ggml_row_size(GGML_TYPE_F32, sizex * sizey); // BLAS
ctx_size += ggml_row_size(GGML_TYPE_F32, sizex * sizey); // BLAS
ctx_size += 1024 * 1024 * 16;
GGML_JNI_NOTIFY("allocating Memory of size %zi bytes, %zi MB\n", ctx_size,
(ctx_size / 1024 / 1024));
struct ggml_init_params params = {
/*.mem_size =*/ ctx_size,
/*.mem_buffer =*/ NULL,
/* no_alloc =*/ 0
};
ggml_backend_t backend = nullptr;
ggml_backend_buffer_t buffer = nullptr;
#ifdef GGML_USE_HEXAGON
if (backend_type != HEXAGON_BACKEND_GGML) {
//params.use_hwaccel = true;
params.no_alloc = true;
backend = ggml_backend_hexagon_init(backend_type,
"/data/data/com.kantvai.kantvplayer/qnnlib/"); // the second param can be got by JNI from Java layer
if (nullptr == backend) {
LOGGD("create qnn backend %d failed", backend_type);
GGML_JNI_NOTIFY("create qnn backend %d failed", backend_type);
return;
}
} else {
backend = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
}
#else
backend = ggml_backend_init_by_type(GGML_BACKEND_DEVICE_TYPE_CPU, nullptr);
#endif
ctx = ggml_init(params);
if (!ctx) {
LOGGW("%s: ggml_init() failed\n");
return;
}
GGML_JNI_NOTIFY("Creating new tensors\n");
struct ggml_tensor *m11 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, sizex, sizey);
ggml_set_f32(m11, 1.0f);
GGML_JNI_NOTIFY("Creating new tensor\n");
struct ggml_tensor *m12 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, sizex, sizey);
ggml_set_f32(m12, 2.0f);
GGML_JNI_NOTIFY("Creating new tensor\n");
struct ggml_tensor *m2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, sizex, sizez);
ggml_set_f32(m2, 2.0f);
struct ggml_tensor *m11xm12 = ggml_mul_mat(ctx, m11, m12);
ggml_set_f32(m11xm12, 0.0f);
GGML_JNI_NOTIFY("Creating compute graph\n");
struct ggml_cgraph *gf = ggml_new_graph(ctx);
ggml_build_forward_expand(gf, m11xm12);
GGML_JNI_NOTIFY("n_threads=%i\n", n_threads);
std::vector<uint8_t> work_buffer;
ggml_graph_compute_helper(backend, gf, work_buffer, n_threads, nullptr, nullptr);
if (get_tensor_data_size(m11) < 100) {
TENSOR_DUMP(m11);
TENSOR_DUMP(m12);
TENSOR_DUMP(m11xm12);
} else {
LOGGI("%15s: type = %i (%5s) ne = %5" PRIi64 " x %5" PRIi64 " x %5" PRIi64 ", nb = (%5zi, %5zi, %5zi)\n",
m11->name,
m11->type, ggml_type_name(m11->type), m11->ne[0], m11->ne[1], m11->ne[2], m11->nb[0],
m11->nb[1], m11->nb[2]);
LOGGI("%15s: type = %i (%5s) ne = %5" PRIi64 " x %5" PRIi64 " x %5" PRIi64 ", nb = (%5zi, %5zi, %5zi)\n",
m12->name,
m12->type, ggml_type_name(m12->type), m12->ne[0], m12->ne[1], m12->ne[2], m12->nb[0],
m12->nb[1], m12->nb[2]);
LOGGI("%15s: type = %i (%5s) ne = %5" PRIi64 " x %5" PRIi64 " x %5" PRIi64 ", nb = (%5zi, %5zi, %5zi)\n",
m11xm12->name,
m11xm12->type, ggml_type_name(m11xm12->type), m11xm12->ne[0], m11xm12->ne[1],
m11xm12->ne[2], m11xm12->nb[0], m11xm12->nb[1], m11xm12->nb[2]);
GGML_JNI_NOTIFY(
"%15s: type = %i (%5s) ne = %5" PRIi64 " x %5" PRIi64 " x %5" PRIi64 ", nb = (%5zi, %5zi, %5zi)\n",
m11->name,
m11->type, ggml_type_name(m11->type), m11->ne[0], m11->ne[1], m11->ne[2],
m11->nb[0], m11->nb[1], m11->nb[2]);
GGML_JNI_NOTIFY(
"%15s: type = %i (%5s) ne = %5" PRIi64 " x %5" PRIi64 " x %5" PRIi64 ", nb = (%5zi, %5zi, %5zi)\n",
m12->name,
m12->type, ggml_type_name(m12->type), m12->ne[0], m12->ne[1], m12->ne[2],
m12->nb[0], m12->nb[1], m12->nb[2]);
GGML_JNI_NOTIFY(
"%15s: type = %i (%5s) ne = %5" PRIi64 " x %5" PRIi64 " x %5" PRIi64 ", nb = (%5zi, %5zi, %5zi)\n",
m11xm12->name,
m11xm12->type, ggml_type_name(m11xm12->type), m11xm12->ne[0], m11xm12->ne[1],
m11xm12->ne[2], m11xm12->nb[0], m11xm12->nb[1], m11xm12->nb[2]);
}
//TENSOR_DUMP(gf->nodes[0]);
n_end_time = ggml_time_us();
n_durtion = (n_end_time - n_begin_time) / 1000;
LOGGD("duration of matrix with backend %d(%s) is: %lld milliseconds\n", backend_type,
ggml_backend_hexagon_get_devname(backend_type), n_durtion);
GGML_JNI_NOTIFY("duration of matrix with backend %d(%s) is: %lld milliseconds\n", backend_type,
ggml_backend_hexagon_get_devname(backend_type), n_durtion);
ggml_free(ctx);
ggml_backend_buffer_free(buffer);
ggml_backend_free(backend);
GGML_JNI_NOTIFY("\n");
GGML_JNI_NOTIFY(
"=====================================================================================\n");
LOGGD("leave ggml_bench_matrix\n");
}
#ifdef GGML_USE_HEXAGON
/*
* MIT license
* Copyright (C) 2024 KanTV Authors
* SPDX-License-Identifier: MIT
*
* The most important two references are:
*
* (1) https://github.com/pytorch/executorch/tree/main/backends/qualcomm
*
* (2) /opt/qcom/aistack/qnn/2.20.0.240223/examples/Models/InceptionV3/model/Inception_v3.cpp
*
* Inception_v3.cpp is generated automatically by Qualcomm's dedicated tool and it contains more then 20,000 lines C++ code
*
*
* this implementation is preparation stage (PoC-S2, PoC-S3) of PoC-S42
*
* PoC#121:Add Qualcomm mobile SoC native backend for GGML(https://github.com/zhouwg/kantv/issues/121) in Project KanTV
*
*/
#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 "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-hexagon.h"
#include "ggml-jni.h"
// =================================================================================================
//
// self-defined structure / class / macro / const / pfn
//
// =================================================================================================
#define RPCMEM_DEFAULT_FLAGS 1
#define RPCMEM_HEAP_ID_SYSTEM 25
#define QNN_VER_PTR(x) (&((x).v1))
#define TENSOR_DUMP(tensor) tensor_dump(tensor, #tensor)
#define QNN_OP_CFG_VALID(opConfig) ((opConfig).version == QNN_OPCONFIG_VERSION_1)
#define VALIDATE(value, status) \
do { \
status = value; \
if (status != QNN_SUCCESS) { \
LOGGW("%s expected QNN_SUCCESS\n", #value); \
return status; \
} \
} while (0)
#define VALIDATE_TENSOR_VERSION(tensor, err) VALIDATE(validateTensorVersion(tensor), err)
#define VALIDATE_OP_CONFIG_VERSION(op, err) VALIDATE(validateOpConfigVersion(op), err)
#define BINVARSTART(NAME) \
({ \
extern const uint8_t _binary_obj_binary_##NAME##_raw_start[]; \
(void *)_binary_obj_binary_##NAME##_raw_start; \
})
#define BINVAREND(NAME) \
({ \
extern const uint8_t _binary_obj_binary_##NAME##_raw_end[]; \
(void *)_binary_obj_binary_##NAME##_raw_end; \
})
#define BINLEN(NAME) \
({ \
extern const uint8_t _binary_obj_binary_##NAME##_raw_start[]; \
extern const uint8_t _binary_obj_binary_##NAME##_raw_end[]; \
(uint32_t)((_binary_obj_binary_##NAME##_raw_end) - (_binary_obj_binary_##NAME##_raw_start)); \
})
#define FREE_MEMORY(ptr1, ptr2, ptr3) \
do { \
free(ptr1); \
free(ptr2); \
free(ptr3); \
} while (0)
enum class ggml_qnn_profile_level {
profile_off = 0,
profile_basic = 1,
profile_detail = 2
};
enum class OutputDataType {
FLOAT_ONLY, NATIVE_ONLY, FLOAT_AND_NATIVE, INVALID
};
enum class InputDataType {
FLOAT, NATIVE, INVALID
};
typedef struct GraphInfo {
Qnn_GraphHandle_t graph;
char *graphName;
Qnn_Tensor_t *inputTensors;