-
Notifications
You must be signed in to change notification settings - Fork 26
/
minigpt4.cpp
2987 lines (2520 loc) · 101 KB
/
minigpt4.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
#include "minigpt4.h"
#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <filesystem>
#include <sstream>
#include <csignal>
#include <fstream>
#include <codecvt>
#include <numeric>
#include <optional>
#include <thread>
#include <span>
#include <variant>
#include <any>
#include <ranges>
#include <cstring>
#include <map>
#include <chrono>
#include "llama.h"
#include "ggml.h"
#include "fmt/core.h"
#include "fmt/ranges.h"
#include "ankerl/unordered_dense.h"
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
#include <spdlog/spdlog.h>
#include <spdlog/stopwatch.h>
#include <spdlog/fmt/bin_to_hex.h>
#include <nlohmann/json.hpp>
using json = nlohmann::json;
#include <expected.hpp>
#include <magic_enum.hpp>
#ifdef MINIGPT4_BUILD_WITH_OPENCV
#include <opencv2/opencv.hpp>
#include <PillowResize.hpp>
#endif
/////////////////////
/// PLATFORM INCLUDE
/////////////////////
#ifdef __has_include
#if __has_include(<unistd.h>)
#include <unistd.h>
#if defined(_POSIX_MAPPED_FILES)
#include <sys/mman.h>
#endif
#if defined(_POSIX_MEMLOCK_RANGE)
#include <sys/resource.h>
#endif
#endif
#endif
#if defined(_WIN32)
#define WIN32_LEAN_AND_MEAN
#ifndef NOMINMAX
#define NOMINMAX
#endif
#include <windows.h>
#include <io.h>
#include <stdio.h>
#endif
/////////////////////
/// FORWARDS
/////////////////////
namespace fs = std::filesystem;
using namespace std::chrono_literals;
template <typename K, typename V>
using HashMap = ankerl::unordered_dense::map<K, V>;
constexpr auto PAGE_SIZE = 4096u;
/////////////////////
/// DEFINITIONS
/////////////////////
constexpr std::string_view EXPECTED_HEADER = "ggml";
constexpr auto MB = 1024u * 1024u;
constexpr auto GB = 1024u * MB;
constexpr auto bytes_to_mb = [](auto bytes)
{ return static_cast<double>(bytes) / MB; };
enum MiniGPT4Error : int
{
None,
LoadModelFileHeader,
LoadModelFileVersion,
LoadModelMiniGPT4DataType,
LoadLanguageModel,
OpenImage,
ImageSize,
MmapSupport,
FailedToAddString,
LLamaProjectionEmbeddingInvalidSize,
FailedToAddEmbedding,
EosToken,
Eos,
ImageNot224_244_3,
ImageNotF32,
ImageChannelsExpectedRGB,
ImageFormatExpectedU8,
PathDoesNotExist,
DumpModelFileOpen,
OpenCVNotLinked,
};
/////////////////////
/// CONSTANT GLOBALS
/////////////////////
constexpr std::size_t PATCH_SIZE = 16;
constexpr std::size_t NUM_ATTENTION_HEADS = 12;
constexpr std::size_t ATTENTION_HEAD_SIZE = 64;
constexpr std::size_t ALL_HEAD_SIZE = 768;
constexpr std::size_t IMAGE_RESIZE = 224;
constexpr std::size_t LLAMA_PROJECTION_EMBEDDING_SIZE1 = 32;
constexpr std::size_t LLAMA_PROJECTION_HIDDEN_SIZE_7B = 4096;
constexpr std::size_t LLAMA_PROJECTION_HIDDEN_SIZE_13B = 5120;
constexpr std::size_t LLAMA_PROJECTION_EMBEDDING_SIZE_7B = LLAMA_PROJECTION_HIDDEN_SIZE_7B * LLAMA_PROJECTION_EMBEDDING_SIZE1;
constexpr std::size_t LLAMA_PROJECTION_EMBEDDING_SIZE_13B = LLAMA_PROJECTION_HIDDEN_SIZE_13B * LLAMA_PROJECTION_EMBEDDING_SIZE1;
constexpr std::string_view SYSTEM_PROMPT = R"(Give the following image: <Img>ImageContent</Img>. You will be able to see the image once I provide it to you. Please answer my questions.###)";
constexpr std::string_view EOS_TOKEN_SUFFIX = "##";
constexpr std::string_view EOS_SUFFIX = "###";
constexpr float TORCH_FLOAT_FIFO_MIN = -3.40282e+38;
constexpr std::size_t RGB_CHANNELS = 3;
constexpr static std::size_t MAX_SCRATCH_BUFFERS = 1;
/////////////////////
/// MUTABLE GLOBALS
/////////////////////
static MiniGPT4Verbosity global_verbosity;
/////////////////////
/// Memory sizes
/////////////////////
enum class ModelType
{
Unknown,
Vicuna7B,
Vicuna13B,
};
// TODO: dynamically determine sizes
const static HashMap<ModelType, std::size_t> model_type_to_compute_size = {
{ModelType::Vicuna7B, 100 * MB},
{ModelType::Vicuna13B, 100 * MB},
};
const static HashMap<ModelType, std::size_t> model_type_to_scratch_size = {
{ModelType::Vicuna7B, 2814 * MB},
{ModelType::Vicuna13B, 2815 * MB},
};
/////////////////////
/// UTILS
/////////////////////
#define CCAT(a, b) a##b
#define CAT(a, b) CCAT(a, b)
#define STRINGIFY2(x) #x
#define STRINGIFY(x) STRINGIFY2(x)
#define UNIQUIFY2(x) CAT(x, __LINE__)
#define UNIQUIFY(x) UNIQUIFY2(x)
#ifdef USE_PREFIX
#define PREFIX "{}:{}:{} "
#define PREFIX_ENTRIES __FILE__, __FUNCTION__, __LINE__
#else
#define PREFIX
#define PREFIX_ENTRIES __FILE__
#endif
#define DEBUG(...) \
do \
{ \
if (global_verbosity >= MiniGPT4Verbosity::MINIGPT4_VERBOSITY_DEBUG) \
{ \
auto UNIQUIFY(log_header) = fmt::format(PREFIX "DEBUG: ", PREFIX_ENTRIES); \
auto UNIQUIFY(other_info) = fmt::format(__VA_ARGS__); \
std::cout << UNIQUIFY(log_header) << UNIQUIFY(other_info) << "\n"; \
} \
} while (0)
#define INFO(...) \
do \
{ \
if (global_verbosity >= MiniGPT4Verbosity::MINIGPT4_VERBOSITY_INFO) \
{ \
auto UNIQUIFY(log_header) = fmt::format(PREFIX "INFO: ", PREFIX_ENTRIES); \
auto UNIQUIFY(other_info) = fmt::format(__VA_ARGS__); \
std::cout << UNIQUIFY(log_header) << UNIQUIFY(other_info) << "\n"; \
} \
} while (0)
#define ERR(...) \
do \
{ \
if (global_verbosity >= MiniGPT4Verbosity::MINIGPT4_VERBOSITY_ERROR) \
{ \
auto UNIQUIFY(log_header) = fmt::format(PREFIX "ERROR: ", PREFIX_ENTRIES); \
auto UNIQUIFY(other_info) = fmt::format(__VA_ARGS__); \
std::cerr << UNIQUIFY(log_header) << UNIQUIFY(other_info) << "\n"; \
} \
} while (0)
#define PANIC(...) \
ERR(__VA_ARGS__); \
exit(-1);
#ifndef NDEBUG
#define ASSERT(result, ...) \
do \
{ \
if (!(result)) \
{ \
auto UNIQUIFY(log_header) = fmt::format(PREFIX "ASSERT: [{}] ", PREFIX_ENTRIES, STRINGIFY(result)); \
auto UNIQUIFY(other_info) = fmt::format(__VA_ARGS__); \
std::cerr << UNIQUIFY(log_header) << UNIQUIFY(other_info) << "\n"; \
exit(-1); \
} \
} while (0)
#else
#define ASSERT(result, ...)
#endif
struct BufferView
{
explicit BufferView(uint8_t *addr = nullptr, std::size_t size = 0) : addr(addr), size(size) {}
bool valid() const
{
return addr != nullptr && size != 0;
}
template <typename T>
T *As()
{
return reinterpret_cast<T *>(addr);
}
uint8_t *addr{};
std::size_t size{};
};
struct Buffer : public BufferView
{
explicit Buffer() = default;
explicit Buffer(std::size_t size_)
{
size = size_;
if (size)
{
buf.resize(size);
addr = buf.data();
}
}
std::vector<uint8_t> buf{};
};
struct Timer
{
explicit Timer() {}
double elapsed_us()
{
auto diff = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::high_resolution_clock::now() - start).count();
return diff;
}
const std::chrono::time_point<std::chrono::high_resolution_clock> start = std::chrono::high_resolution_clock::now();
};
struct LoggingTimer : public Timer
{
explicit LoggingTimer(std::string_view s_ = "") : s(std::string(s_)) {}
~LoggingTimer()
{
auto diff = elapsed_us();
if (global_verbosity >= MiniGPT4Verbosity::MINIGPT4_VERBOSITY_INFO)
{
INFO("{} took {} ms to complete", s, diff);
}
}
std::string s;
};
/////////////////////
/// FILE UTILS
/////////////////////
class MMappedFile
{
public:
explicit MMappedFile() = default;
#ifdef _POSIX_MAPPED_FILES
static constexpr bool SUPPORTED = true;
void load(fs::path p, bool prefetch = true)
{
fp = std::fopen(p.string().c_str(), "rb");
ASSERT(fp != nullptr, "file does not exist {}", p.string());
std::fseek(fp, 0, SEEK_END);
view.size = std::ftell(fp);
std::fseek(fp, 0, SEEK_SET);
int fd = fileno(fp);
int flags = MAP_SHARED;
#ifdef __linux__
flags |= MAP_POPULATE;
#endif
view.addr = reinterpret_cast<uint8_t *>(mmap(NULL, view.size, PROT_READ, flags, fd, 0));
if (view.addr == MAP_FAILED)
{
ERR("mmap failed: {}", strerror(errno));
}
if (prefetch)
{
// Advise the kernel to preload the mapped memory
if (madvise(view.addr, view.size, MADV_WILLNEED))
{
ERR("warning: madvise(.., MADV_WILLNEED) failed: {}\n",
strerror(errno));
}
}
}
~MMappedFile()
{
fclose(fp);
munmap(view.addr, view.size);
}
#elif defined(_WIN32)
static constexpr bool SUPPORTED = true;
void load(fs::path p, bool prefetch = true)
{
fp = std::fopen(p.string().c_str(), "rb");
ASSERT(fp != nullptr, "file does not exist {}", p.string());
std::fseek(fp, 0, SEEK_END);
view.size = _ftelli64(fp);
std::fseek(fp, 0, SEEK_SET);
HANDLE hFile = (HANDLE)_get_osfhandle(_fileno(fp));
HANDLE hMapping = CreateFileMappingA(hFile, NULL, PAGE_READONLY, 0, 0, NULL);
DWORD error = GetLastError();
if (hMapping == NULL)
{
PANIC("CreateFileMappingA failed: {}", error);
}
view.addr = reinterpret_cast<uint8_t *>(MapViewOfFile(hMapping, FILE_MAP_READ, 0, 0, 0));
error = GetLastError();
if (view.addr == NULL)
{
PANIC("MapViewOfFile failed: {}", error);
}
#if _WIN32_WINNT >= _WIN32_WINNT_WIN8
if (prefetch)
{
// Advise the kernel to preload the mapped memory
WIN32_MEMORY_RANGE_ENTRY range;
range.VirtualAddress = view.addr;
range.NumberOfBytes = (SIZE_T)view.size;
if (!PrefetchVirtualMemory(GetCurrentProcess(), 1, &range, 0))
{
INFO("PrefetchVirtualMemory failed: {}", GetLastError());
}
}
#else
#pragma message("warning: You are building for pre-Windows 8; prefetch not supported")
#endif // _WIN32_WINNT >= _WIN32_WINNT_WIN8
CloseHandle(hMapping);
}
~MMappedFile()
{
fclose(fp);
if (!UnmapViewOfFile(view.addr))
{
PANIC("UnmapViewOfFile failed: {}", GetLastError());
}
}
#else
static constexpr bool SUPPORTED = false;
void load(fs::path p, bool prefetch = true)
{
PANIC("mmap not supported");
}
#endif
protected:
BufferView view;
FILE *fp{};
};
class MMapReader : public MMappedFile
{
public:
explicit MMapReader() = default;
template <typename T = uint8_t *>
T base_addr()
{
return reinterpret_cast<T>(view.addr);
}
template <typename T = uint8_t *>
T current_addr()
{
return reinterpret_cast<T>(view.addr + pos);
}
std::size_t tell()
{
return pos;
}
void seek(std::size_t new_pos)
{
pos = new_pos;
ASSERT(pos <= view.size, "Out of bounds for seeking {} > {}", pos, view.size);
}
void seek_to_alignment(std::size_t alignment)
{
if ((alignment - 1) & pos)
{
pos = (pos + alignment) & ~(alignment - 1);
}
}
bool is_eof() const
{
ASSERT(pos <= view.size, "Out of bounds for eof {} > {}", pos, view.size);
return pos == view.size;
}
void add_pos(std::size_t amount)
{
pos += amount;
ASSERT(pos <= view.size, "Out of bounds for reading {} > {}", pos, view.size);
}
template <typename T>
T &read_as()
{
T *t = current_addr<T *>();
add_pos(sizeof(T));
return *t;
}
int32_t read_s4()
{
return read_as<int32_t>();
}
std::string_view read_bytes(std::size_t len)
{
auto start = current_addr<const char *>();
std::string_view s(start, len);
add_pos(len);
return s;
}
std::string_view read_string()
{
auto string_length = read_s4();
auto s = read_bytes(string_length);
return s;
}
template <typename T>
void read_bytes_into(T buf, std::size_t len)
{
static_assert(std::is_pointer_v<T>, "T must be a pointer");
auto start = current_addr();
std::copy(start, start + len, buf);
add_pos(len);
}
private:
std::size_t pos{};
};
/////////////////////
/// Debug
/////////////////////
void WriteDump(ggml_tensor *t)
{
std::ofstream f("out.txt", std::ios::trunc | std::ios::ate);
std::vector<std::size_t> sizes{(size_t *)&t->ne[0], (size_t *)&t->ne[4]};
auto total = sizes[0] * sizes[1] * sizes[2] * sizes[3];
for (auto i = 0; i < total; i++)
{
auto *d = (float *)t->data;
auto dd = d[i];
f << fmt::format("{},", dd);
}
fmt::print("TOTAL {}\n", total);
f.close();
exit(-2);
}
#define DUMP_TENSOR(cur) \
{ \
auto xxx = cur; \
xxx = ggml_cont(ctx0, xxx); \
ggml_set_name(xxx, "dump"); \
use_scratch(-1); \
struct ggml_cgraph gf = {}; \
gf.n_threads = 16; \
ggml_build_forward_expand(&gf, xxx); \
ggml_graph_compute(ctx0, &gf); \
auto *t = ggml_get_tensor(ctx0, "dump"); \
WriteDump(t); \
}
/////////////////////
/// Tensors
/////////////////////
tl::expected<ggml_type, MiniGPT4Error> data_type_to_ggml_type(MiniGPT4DataType data_type)
{
ggml_type type;
switch (data_type)
{
case MiniGPT4DataType::F16:
{
type = GGML_TYPE_F16;
break;
}
case MiniGPT4DataType::F32:
{
type = GGML_TYPE_F32;
break;
}
case MiniGPT4DataType::I32:
{
type = GGML_TYPE_I32;
break;
}
case MiniGPT4DataType::L64:
{
ERR("Unsupported MiniGPT4DataType {}", magic_enum::enum_name(data_type));
return tl::unexpected(MiniGPT4Error::LoadModelMiniGPT4DataType);
break;
}
case MiniGPT4DataType::Q4_0:
{
type = GGML_TYPE_Q4_0;
break;
}
case MiniGPT4DataType::Q4_1:
{
type = GGML_TYPE_Q4_1;
break;
}
case MiniGPT4DataType::Q5_0:
{
type = GGML_TYPE_Q5_0;
break;
}
case MiniGPT4DataType::Q5_1:
{
type = GGML_TYPE_Q5_1;
break;
}
case MiniGPT4DataType::Q8_0:
{
type = GGML_TYPE_Q8_0;
break;
}
case MiniGPT4DataType::Q8_1:
{
type = GGML_TYPE_Q8_1;
break;
}
case MiniGPT4DataType::Q2_K:
{
type = GGML_TYPE_Q2_K;
break;
}
case MiniGPT4DataType::Q3_K:
{
type = GGML_TYPE_Q3_K;
break;
}
case MiniGPT4DataType::Q4_K:
{
type = GGML_TYPE_Q4_K;
break;
}
case MiniGPT4DataType::Q5_K:
{
type = GGML_TYPE_Q5_K;
break;
}
case MiniGPT4DataType::Q6_K:
{
type = GGML_TYPE_Q6_K;
break;
}
case MiniGPT4DataType::Q8_K:
{
type = GGML_TYPE_Q8_K;
break;
}
default:
{
ERR("Unsupported MiniGPT4DataType {}", magic_enum::enum_name(data_type));
return tl::unexpected(MiniGPT4Error::LoadModelMiniGPT4DataType);
break;
}
}
return type;
}
tl::expected<MiniGPT4DataType, MiniGPT4Error> ggml_type_to_data_type(ggml_type t)
{
MiniGPT4DataType data_type;
switch (t)
{
case GGML_TYPE_F16:
{
data_type = MiniGPT4DataType::F16;
break;
}
case GGML_TYPE_F32:
{
data_type = MiniGPT4DataType::F32;
break;
}
case GGML_TYPE_I32:
{
data_type = MiniGPT4DataType::I32;
break;
}
case GGML_TYPE_Q4_0:
{
data_type = MiniGPT4DataType::Q4_0;
break;
}
case GGML_TYPE_Q4_1:
{
data_type = MiniGPT4DataType::Q4_1;
break;
}
case GGML_TYPE_Q5_0:
{
data_type = MiniGPT4DataType::Q5_0;
break;
}
case GGML_TYPE_Q5_1:
{
data_type = MiniGPT4DataType::Q5_1;
break;
}
case GGML_TYPE_Q8_0:
{
data_type = MiniGPT4DataType::Q8_0;
break;
}
case GGML_TYPE_Q8_1:
{
data_type = MiniGPT4DataType::Q8_1;
break;
}
case GGML_TYPE_Q2_K:
{
data_type = MiniGPT4DataType::Q2_K;
break;
}
case GGML_TYPE_Q3_K:
{
data_type = MiniGPT4DataType::Q3_K;
break;
}
case GGML_TYPE_Q4_K:
{
data_type = MiniGPT4DataType::Q4_K;
break;
}
case GGML_TYPE_Q5_K:
{
data_type = MiniGPT4DataType::Q5_K;
break;
}
case GGML_TYPE_Q6_K:
{
data_type = MiniGPT4DataType::Q6_K;
break;
}
case GGML_TYPE_Q8_K:
{
data_type = MiniGPT4DataType::Q8_K;
break;
}
default:
{
ERR("Unsupported MiniGPT4DataType {}", magic_enum::enum_name(t));
return tl::unexpected(MiniGPT4Error::LoadModelMiniGPT4DataType);
break;
}
}
return data_type;
}
struct LazyLoadTensor
{
MMapReader *reader;
std::string name;
std::vector<uint32_t> shape;
ggml_type type = ggml_type::GGML_TYPE_COUNT;
std::size_t pos = 0;
struct ggml_tensor *tensor = nullptr;
BufferView tensor_buf;
std::size_t type_size() const
{
switch (type)
{
case ggml_type::GGML_TYPE_F16:
return sizeof(float) / 2;
case ggml_type::GGML_TYPE_F32:
return sizeof(float);
case ggml_type::GGML_TYPE_I32:
return sizeof(int32_t);
default:
return ggml_type_size(type);
}
return 0;
}
std::size_t total_shape() const
{
std::size_t size = 1;
for (auto i = 0; i < shape.size(); i++)
{
size *= shape[i];
}
return size;
}
std::size_t total_size() const
{
if (shape.empty())
{
return type_size();
}
std::size_t size = 1;
for (auto i = 0; i < shape.size(); i++)
{
size *= shape[i];
}
size *= type_size();
return size;
}
auto get_size_in_bytes() const
{
// Calculate the size
struct ggml_tensor temp
{
};
temp.type = type;
auto k = 0;
for (; k < shape.size(); k++)
{
temp.ne[k] = shape[k];
}
for (; k < 4; k++)
{
temp.ne[k] = 1;
}
return ggml_nbytes(&temp);
}
auto get_file_address() const
{
return reader->base_addr() + pos;
}
struct ggml_tensor *operator()(ggml_context *ctx)
{
// Cached
if (tensor)
{
return tensor;
}
// Create tensors
const auto shape_size = shape.size();
if (shape_size == 1)
{
tensor = ggml_new_tensor_1d(ctx, type, shape[0]);
}
else if (shape_size == 2)
{
tensor = ggml_new_tensor_2d(ctx, type, shape[0], shape[1]);
}
else if (shape_size == 3)
{
tensor = ggml_new_tensor_3d(ctx, type, shape[0], shape[1], shape[2]);
}
else if (shape_size == 4)
{
tensor = ggml_new_tensor_4d(ctx, type, shape[0], shape[1], shape[2], shape[3]);
}
else
{
PANIC("Layer: {}, didn't expect shape of size {}", name, shape_size);
}
// Just reference it
tensor_buf.addr = get_file_address();
tensor_buf.size = get_size_in_bytes();
tensor->data = tensor_buf.addr;
return tensor;
}
};
class TorchModel
{
public:
void set_name(std::string_view s)
{
name = s;
}
const std::string &get_name() const
{
return name;
}
void add_tensor(std::string_view name, LazyLoadTensor tensor)
{
tensors.try_emplace(std::string(name), tensor);
}
template <typename... Args>
LazyLoadTensor &get(Args &&...args)
{
const auto tensor_name = fmt::format(std::forward<Args>(args)...);
return operator[](tensor_name);
}
std::optional<LazyLoadTensor *> get_tensor(const std::string &tensor_name)
{
if (auto found = tensors.find(tensor_name); found != std::end(tensors))
{
auto &[_, tensor] = *found;
return &tensor;
}
return std::nullopt;
}
LazyLoadTensor &operator[](const std::string &tensor_name)
{
if (auto tensor = get_tensor(tensor_name))
{
return **tensor;
}
PANIC("Couldn't find tensor {}", name);
return tensors.begin()->second;
}
const LazyLoadTensor &operator[](const std::string &tensor_name) const
{
return const_cast<TorchModel *>(this)->operator[](tensor_name);
}
auto &get_tensors() { return tensors; }
const auto &get_tensors() const { return tensors; }
private:
std::string name;
HashMap<std::string, LazyLoadTensor> tensors;
};
struct ContextBuffer
{
void init_context(std::size_t buf_compute_size,
std::size_t buf_scratch_size,
std::size_t num_scratch_buffers = MAX_SCRATCH_BUFFERS)
{
buf_scratch.resize(num_scratch_buffers);
buf_max_size.resize(num_scratch_buffers);
reset_scratch_usage();
buf_compute = Buffer(buf_compute_size);
if (buf_scratch_size)
{
for (auto i = 0; i < num_scratch_buffers; i++)
{
buf_scratch[i] = Buffer(buf_scratch_size);
}
}
}
void use_scratch(int i)
{
size_t last_size = 0;
if (i == -1)
{
last_size = ggml_set_scratch(ctx, {0, 0, nullptr});
}
else
{
auto &buf = buf_scratch[i];
last_size = ggml_set_scratch(ctx, {0, buf.size, buf.addr});
}
if (buf_last >= 0)
{
buf_max_size[buf_last] = std::max(buf_max_size[buf_last], last_size);
}
buf_last = i;
}
auto get_memory_usage(int i)
{
if (i == -1)
{
return ggml_used_mem(ctx);
}
return buf_max_size[static_cast<std::size_t>(i)];
}
void reset_scratch_usage()
{
buf_last = 0;
for (auto &s : buf_max_size)
{
s = 0;
}
}
Buffer buf_compute;
std::vector<Buffer> buf_scratch;
int buf_last = 0;
std::vector<size_t> buf_max_size;
ggml_context *ctx{};
};
template <typename Derived>
struct HasContext
{
ggml_context *data_ctx = nullptr;
template <typename... Args>
auto operator()(ggml_context *ctx, ggml_tensor *x, Args &&...args)
{
return static_cast<Derived *>(this)->forward(ctx, x, std::forward<Args>(args)...);
}
};
struct HasContextBase;
template <template <typename> class THIS, typename IMPL, template <typename> class SUPERCLASS>
using HasContextFix = SUPERCLASS<std::conditional_t<
std::is_same_v<IMPL, HasContextBase>,
THIS<HasContextBase>, IMPL>>;