-
Notifications
You must be signed in to change notification settings - Fork 4
/
file.go
1669 lines (1498 loc) · 44.9 KB
/
file.go
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
package gguf_parser
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"regexp"
"strings"
"golang.org/x/exp/constraints"
"github.com/gpustack/gguf-parser-go/util/anyx"
"github.com/gpustack/gguf-parser-go/util/bytex"
"github.com/gpustack/gguf-parser-go/util/funcx"
"github.com/gpustack/gguf-parser-go/util/osx"
)
// GGUFFile represents a GGUF file,
// see https://github.com/ggerganov/ggml/blob/master/docs/gguf.md#file-structure.
//
// Compared with the complete GGUF file,
// this structure lacks the tensor data part.
type GGUFFile struct {
/* Basic */
// Header is the header of the GGUF file.
Header GGUFHeader `json:"header"`
// TensorInfos are the tensor infos of the GGUF file,
// the size of TensorInfos is equal to `Header.TensorCount`.
TensorInfos GGUFTensorInfos `json:"tensorInfos"`
// Padding is the padding size of the GGUF file,
// which is used to split Header and TensorInfos from tensor data.
Padding int64 `json:"padding"`
// SplitPaddings holds the padding size slice of the GGUF file splits,
// each item represents splitting Header and TensorInfos from tensor data.
//
// The length of SplitPaddings is the number of split files.
SplitPaddings []int64 `json:"splitPaddings,omitempty"`
// TensorDataStartOffset is the offset in bytes of the tensor data in this file.
//
// The offset is the start of the file.
TensorDataStartOffset int64 `json:"tensorDataStartOffset"`
// SplitTensorDataStartOffsets holds the offset slice in bytes of the tensor data of the GGUF file splits,
// each item represents the offset of the tensor data in the split file.
//
// The length of SplitTensorDataStartOffsets is the number of split files.
SplitTensorDataStartOffsets []int64 `json:"splitTensorDataStartOffsets,omitempty"`
/* Appendix */
// Size is the size of the GGUF file,
// if the file is split, the size is the sum of all split files.
Size GGUFBytesScalar `json:"size"`
// SplitSizes holds the size slice of the GGUF file splits,
// each item represents the size of the split file.
//
// The length of SplitSizes is the number of split files.
SplitSizes []GGUFBytesScalar `json:"splitSizes,omitempty"`
// ModelSize is the size of the model when loading.
ModelSize GGUFBytesScalar `json:"modelSize"`
// SplitModelSizes holds the size slice of the model,
// each item represents a size when loading of the split file.
//
// The length of SplitModelSizes is the number of split files.
SplitModelSizes []GGUFBytesScalar `json:"splitModelSizes,omitempty"`
// ModelParameters is the number of the model parameters.
ModelParameters GGUFParametersScalar `json:"modelParameters"`
// ModelBitsPerWeight is the bits per weight of the model,
// which describes how many bits are used to store a weight,
// higher is better.
ModelBitsPerWeight GGUFBitsPerWeightScalar `json:"modelBitsPerWeight"`
}
// GGUFMagic is a magic number of GGUF file,
// see https://github.com/ggerganov/ggml/blob/master/docs/gguf.md#historical-state-of-affairs.
type GGUFMagic uint32
// GGUFMagic constants.
const (
GGUFMagicGGML GGUFMagic = 0x67676d6c
GGUFMagicGGMF GGUFMagic = 0x67676d66
GGUFMagicGGJT GGUFMagic = 0x67676a74
GGUFMagicGGUFLe GGUFMagic = 0x46554747 // GGUF
GGUFMagicGGUFBe GGUFMagic = 0x47475546 // GGUF
)
// GGUFVersion is a version of GGUF file format,
// see https://github.com/ggerganov/ggml/blob/master/docs/gguf.md#version-history.
type GGUFVersion uint32
// GGUFVersion constants.
const (
GGUFVersionV1 GGUFVersion = iota + 1
GGUFVersionV2
GGUFVersionV3
)
// GGUFHeader represents the header of a GGUF file.
type GGUFHeader struct {
// Magic is a magic number that announces that this is a GGUF file.
Magic GGUFMagic `json:"magic"`
// Version is a version of the GGUF file format.
Version GGUFVersion `json:"version"`
// TensorCount is the number of tensors in the file.
TensorCount uint64 `json:"tensorCount"`
// MetadataKVCount is the number of key-value pairs in the metadata.
MetadataKVCount uint64 `json:"metadataKVCount"`
// MetadataKV are the key-value pairs in the metadata,
MetadataKV GGUFMetadataKVs `json:"metadataKV"`
}
// GGUFMetadataValueType is a type of GGUF metadata value,
// see https://github.com/ggerganov/ggml/blob/master/docs/gguf.md#file-structure.
type GGUFMetadataValueType uint32
// GGUFMetadataValueType constants.
const (
GGUFMetadataValueTypeUint8 GGUFMetadataValueType = iota
GGUFMetadataValueTypeInt8
GGUFMetadataValueTypeUint16
GGUFMetadataValueTypeInt16
GGUFMetadataValueTypeUint32
GGUFMetadataValueTypeInt32
GGUFMetadataValueTypeFloat32
GGUFMetadataValueTypeBool
GGUFMetadataValueTypeString
GGUFMetadataValueTypeArray
GGUFMetadataValueTypeUint64
GGUFMetadataValueTypeInt64
GGUFMetadataValueTypeFloat64
_GGUFMetadataValueTypeCount // Unknown
)
// Types for GGUFMetadataKV.
type (
// GGUFMetadataKV is a key-value pair in the metadata of a GGUF file.
GGUFMetadataKV struct {
// Key is the key of the metadata key-value pair,
// which is no larger than 64 bytes long.
Key string `json:"key"`
// ValueType is the type of the metadata value.
ValueType GGUFMetadataValueType `json:"valueType"`
// Value is the value of the metadata key-value pair.
Value any `json:"value"`
}
// GGUFMetadataKVArrayValue is a value of a GGUFMetadataKV with type GGUFMetadataValueTypeArray.
GGUFMetadataKVArrayValue struct {
/* Basic */
// Type is the type of the array item.
Type GGUFMetadataValueType `json:"type"`
// Len is the length of the array.
Len uint64 `json:"len"`
// Array holds all array items.
Array []any `json:"array,omitempty"`
/* Appendix */
// StartOffset is the offset in bytes of the GGUFMetadataKVArrayValue in the GGUFFile file.
//
// The offset is the start of the file.
StartOffset int64 `json:"startOffset"`
// Size is the size of the array in bytes.
Size int64 `json:"size"`
}
// GGUFMetadataKVs is a list of GGUFMetadataKV.
GGUFMetadataKVs []GGUFMetadataKV
)
// Types for GGUFTensorInfo.
type (
// GGUFTensorInfo represents a tensor info in a GGUF file.
GGUFTensorInfo struct {
/* Basic */
// Name is the name of the tensor,
// which is no larger than 64 bytes long.
Name string `json:"name"`
// NDimensions is the number of dimensions of the tensor.
NDimensions uint32 `json:"nDimensions"`
// Dimensions is the dimensions of the tensor,
// the length is NDimensions.
Dimensions []uint64 `json:"dimensions"`
// Type is the type of the tensor.
Type GGMLType `json:"type"`
// Offset is the offset in bytes of the tensor's data in this file.
//
// The offset is relative to tensor data, not to the start of the file.
Offset uint64 `json:"offset"`
/* Appendix */
// StartOffset is the offset in bytes of the GGUFTensorInfo in the GGUFFile file.
//
// The offset is the start of the file.
StartOffset int64 `json:"startOffset"`
}
// GGUFTensorInfos is a list of GGUFTensorInfo.
GGUFTensorInfos []GGUFTensorInfo
)
var ErrGGUFFileInvalidFormat = errors.New("invalid GGUF format")
// ParseGGUFFile parses a GGUF file from the local given path,
// and returns the GGUFFile, or an error if any.
func ParseGGUFFile(path string, opts ...GGUFReadOption) (*GGUFFile, error) {
var o _GGUFReadOptions
for _, opt := range opts {
opt(&o)
}
var paths []string
{
rs := CompleteShardGGUFFilename(path)
if rs != nil {
paths = rs
} else {
paths = []string{path}
}
}
fs := make([]_GGUFFileReadSeeker, 0, len(paths))
defer func() {
for i := range fs {
osx.Close(fs[i])
}
}()
for i := range paths {
if o.MMap {
mf, err := osx.OpenMmapFile(paths[i])
if err != nil {
return nil, fmt.Errorf("open mmap file: %w", err)
}
fs = append(fs, _GGUFFileReadSeeker{
Closer: mf,
ReadSeeker: io.NewSectionReader(mf, 0, mf.Len()),
Size: mf.Len(),
})
continue
}
ff, err := osx.Open(paths[i])
if err != nil {
return nil, fmt.Errorf("open file: %w", err)
}
fs = append(fs, _GGUFFileReadSeeker{
Closer: ff,
ReadSeeker: ff,
Size: funcx.MustNoError(ff.Stat()).Size(),
})
}
return parseGGUFFile(fs, o)
}
type _GGUFFileReadSeeker struct {
io.Closer
io.ReadSeeker
Size int64
}
func parseGGUFFile(fs []_GGUFFileReadSeeker, o _GGUFReadOptions) (_ *GGUFFile, err error) {
var gf GGUFFile
for _, f := range fs {
var bo binary.ByteOrder = binary.LittleEndian
// magic
var magic GGUFMagic
if err = binary.Read(f, bo, &magic); err != nil {
return nil, fmt.Errorf("read magic: %w", err)
}
switch magic {
default:
return nil, ErrGGUFFileInvalidFormat
case GGUFMagicGGML, GGUFMagicGGMF, GGUFMagicGGJT:
return nil, fmt.Errorf("unsupported format: %s", magic)
case GGUFMagicGGUFLe:
case GGUFMagicGGUFBe:
bo = binary.BigEndian
}
gf.Header.Magic = magic
// version
var version GGUFVersion
if err = binary.Read(f, bo, &version); err != nil {
return nil, fmt.Errorf("read version: %w", err)
}
gf.Header.Version = version
rd := _GGUFReader{v: version, o: o, f: f, bo: bo}
// tensor count
var tensorCount uint64
if version <= GGUFVersionV1 {
tensorCount, err = rd.ReadUint64FromUint32()
} else {
tensorCount, err = rd.ReadUint64()
}
if err != nil {
return nil, fmt.Errorf("read tensor count: %w", err)
}
gf.Header.TensorCount += tensorCount
// metadata kv count
var metadataKVCount uint64
if version <= GGUFVersionV1 {
metadataKVCount, err = rd.ReadUint64FromUint32()
} else {
metadataKVCount, err = rd.ReadUint64()
}
if err != nil {
return nil, fmt.Errorf("read metadata kv count: %w", err)
}
gf.Header.MetadataKVCount += metadataKVCount
// metadata kv
{
rd := _GGUFMetadataReader{_GGUFReader: rd}
kvs := make(GGUFMetadataKVs, metadataKVCount)
for i := uint64(0); i < metadataKVCount; i++ {
kvs[i], err = rd.Read()
if err != nil {
return nil, fmt.Errorf("read metadata kv %d: %w", i, err)
}
}
for i := range kvs {
if kvs[i].Key == "split.no" {
gf.Header.MetadataKVCount--
continue
}
gf.Header.MetadataKV = append(gf.Header.MetadataKV, kvs[i])
}
}
// tensor infos
if gf.TensorInfos == nil {
tc, ok := gf.Header.MetadataKV.Get("split.tensors.count")
if ok {
gf.TensorInfos = make(GGUFTensorInfos, 0, anyx.Number[int](tc.Value))
} else {
gf.TensorInfos = make(GGUFTensorInfos, 0, tensorCount)
}
}
{
rd := _GGUFTensorInfoReader{_GGUFReader: rd}
tis := make(GGUFTensorInfos, tensorCount)
for i := uint64(0); i < tensorCount; i++ {
tis[i], err = rd.Read()
if err != nil {
return nil, fmt.Errorf("read tensor info %d: %w", i, err)
}
}
gf.TensorInfos = append(gf.TensorInfos, tis...)
}
pds, err := f.Seek(0, io.SeekCurrent)
if err != nil {
return nil, fmt.Errorf("seek padding start: %w", err)
}
// padding
var padding int64
{
// The global alignment to use, as described above.
// This can vary to allow for different alignment schemes, but it must be a multiple of 8.
// Some writers may not write the alignment.
// If the alignment is not specified, assume it is 32.
var ag uint32 = 32
if v, ok := gf.Header.MetadataKV.Get("general.alignment"); ok {
ag = v.ValueUint32()
}
padding = int64(ag) - (pds % int64(ag))
}
if len(fs) == 1 {
gf.Padding = padding
}
gf.SplitPaddings = append(gf.SplitPaddings, padding)
// tensor data offset
tensorDataStartOffset := pds + padding
if len(fs) == 1 {
gf.TensorDataStartOffset = tensorDataStartOffset
}
gf.SplitTensorDataStartOffsets = append(gf.SplitTensorDataStartOffsets, tensorDataStartOffset)
// size
size := GGUFBytesScalar(f.Size)
gf.Size += size
gf.SplitSizes = append(gf.SplitSizes, size)
// model size
modelSize := GGUFBytesScalar(f.Size - tensorDataStartOffset)
gf.ModelSize += modelSize
gf.SplitModelSizes = append(gf.SplitModelSizes, modelSize)
}
// model parameters
gf.ModelParameters = GGUFParametersScalar(gf.TensorInfos.Elements())
// bpw
if gf.ModelParameters != 0 {
gf.ModelBitsPerWeight = GGUFBitsPerWeightScalar(float64(gf.ModelSize) * 8 / float64(gf.ModelParameters))
}
return &gf, nil
}
// Types for GGUF hierarchical tensors.
type (
// IGGUFTensorInfos is an interface for GGUF tensor infos,
// which includes basic operations.
IGGUFTensorInfos interface {
// Get returns the GGUFTensorInfo with the given name,
// and true if found, and false otherwise.
Get(name string) (info GGUFTensorInfo, found bool)
// GetFileType returns the GGUFFileType.
GetFileType() GGUFFileType
// Match returns true if the name matches the given regex, and false otherwise.
Match(nameRegex *regexp.Regexp) bool
// Search returns a list of GGUFTensorInfo with the names that match the given regex.
Search(nameRegex *regexp.Regexp) (infos []GGUFTensorInfo)
// Index returns a map value to the GGUFTensorInfo with the given names,
// and the number of names found.
Index(names []string) (infos map[string]GGUFTensorInfo, found int)
// Elements returns the number of elements(parameters).
Elements() uint64
// Bytes returns the number of bytes.
Bytes() uint64
// Count returns the number of tensors.
Count() uint64
}
// GGUFLayerTensorInfos represents hierarchical tensor infos of a GGUF file,
// it can save GGUFNamedTensorInfos, GGUFTensorInfos, and GGUFTensorInfo.
GGUFLayerTensorInfos []IGGUFTensorInfos
// GGUFNamedTensorInfos is the namespace for relevant tensors,
// which must has a name.
GGUFNamedTensorInfos struct {
// Name is the name of the namespace.
Name string `json:"name"`
// GGUFLayerTensorInfos can save GGUFNamedTensorInfos, GGUFTensorInfos, or GGUFTensorInfo.
//
// If the item is type of GGUFTensorInfo, it must be the leaf node.
//
// Any branch nodes are type of GGUFNamedTensorInfos or GGUFTensorInfos,
// which can be nested.
//
// Branch nodes store in type pointer.
GGUFLayerTensorInfos `json:"items,omitempty"`
}
)
// Layers converts the GGUFTensorInfos to GGUFLayerTensorInfos.
func (gf *GGUFFile) Layers(ignores ...string) GGUFLayerTensorInfos {
return gf.TensorInfos.Layers(ignores...)
}
func (kv GGUFMetadataKV) ValueUint8() uint8 {
if kv.ValueType != GGUFMetadataValueTypeUint8 {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Number[uint8](kv.Value)
}
func (kv GGUFMetadataKV) ValueInt8() int8 {
if kv.ValueType != GGUFMetadataValueTypeInt8 {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Number[int8](kv.Value)
}
func (kv GGUFMetadataKV) ValueUint16() uint16 {
if kv.ValueType != GGUFMetadataValueTypeUint16 {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Number[uint16](kv.Value)
}
func (kv GGUFMetadataKV) ValueInt16() int16 {
if kv.ValueType != GGUFMetadataValueTypeInt16 {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Number[int16](kv.Value)
}
func (kv GGUFMetadataKV) ValueUint32() uint32 {
if kv.ValueType != GGUFMetadataValueTypeUint32 {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Number[uint32](kv.Value)
}
func (kv GGUFMetadataKV) ValueInt32() int32 {
if kv.ValueType != GGUFMetadataValueTypeInt32 {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Number[int32](kv.Value)
}
func (kv GGUFMetadataKV) ValueFloat32() float32 {
if kv.ValueType != GGUFMetadataValueTypeFloat32 {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Number[float32](kv.Value)
}
func (kv GGUFMetadataKV) ValueBool() bool {
if kv.ValueType != GGUFMetadataValueTypeBool {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Bool(kv.Value)
}
func (kv GGUFMetadataKV) ValueString() string {
if kv.ValueType != GGUFMetadataValueTypeString {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.String(kv.Value)
}
func (kv GGUFMetadataKV) ValueArray() GGUFMetadataKVArrayValue {
if kv.ValueType != GGUFMetadataValueTypeArray {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
switch t := kv.Value.(type) {
case GGUFMetadataKVArrayValue:
return t
case map[string]any:
return GGUFMetadataKVArrayValue{
Type: anyx.Number[GGUFMetadataValueType](t["type"]),
Len: anyx.Number[uint64](t["len"]),
Array: func() []any {
if vv, ok := t["array"].([]any); ok {
return vv
}
return nil
}(),
StartOffset: anyx.Number[int64](t["startOffset"]),
Size: anyx.Number[int64](t["size"]),
}
default:
panic(fmt.Errorf("invalid type: %T", kv.Value))
}
}
func (kv GGUFMetadataKV) ValueUint64() uint64 {
if kv.ValueType != GGUFMetadataValueTypeUint64 {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Number[uint64](kv.Value)
}
func (kv GGUFMetadataKV) ValueInt64() int64 {
if kv.ValueType != GGUFMetadataValueTypeInt64 {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Number[int64](kv.Value)
}
func (kv GGUFMetadataKV) ValueFloat64() float64 {
if kv.ValueType != GGUFMetadataValueTypeFloat64 {
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Number[float64](kv.Value)
}
// ValueNumeric returns the numeric values of the GGUFMetadataKV,
// and panics if the value type is not numeric.
//
// ValueNumeric is a generic function, and the type T must be constraints.Integer or constraints.Float.
//
// Compare to the GGUFMetadataKV's Value* functions,
// ValueNumeric will cast the original value to the target type.
func ValueNumeric[T constraints.Integer | constraints.Float](kv GGUFMetadataKV) T {
switch kv.ValueType {
case GGUFMetadataValueTypeUint8:
case GGUFMetadataValueTypeInt8:
case GGUFMetadataValueTypeUint16:
case GGUFMetadataValueTypeInt16:
case GGUFMetadataValueTypeUint32:
case GGUFMetadataValueTypeInt32:
case GGUFMetadataValueTypeFloat32:
case GGUFMetadataValueTypeUint64:
case GGUFMetadataValueTypeInt64:
case GGUFMetadataValueTypeFloat64:
default:
panic(fmt.Errorf("invalid type: %v", kv.ValueType))
}
return anyx.Number[T](kv.Value)
}
func (av GGUFMetadataKVArrayValue) ValuesUint8() []uint8 {
if av.Type != GGUFMetadataValueTypeUint8 {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]uint8, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.Number[uint8](av.Array[i])
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesInt8() []int8 {
if av.Type != GGUFMetadataValueTypeInt8 {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]int8, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.Number[int8](av.Array[i])
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesUint16() []uint16 {
if av.Type != GGUFMetadataValueTypeUint16 {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]uint16, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.Number[uint16](av.Array[i])
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesInt16() []int16 {
if av.Type != GGUFMetadataValueTypeInt16 {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]int16, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.Number[int16](av.Array[i])
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesUint32() []uint32 {
if av.Type != GGUFMetadataValueTypeUint32 {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]uint32, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.Number[uint32](av.Array[i])
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesInt32() []int32 {
if av.Type != GGUFMetadataValueTypeInt32 {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]int32, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.Number[int32](av.Array[i])
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesFloat32() []float32 {
if av.Type != GGUFMetadataValueTypeFloat32 {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]float32, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.Number[float32](av.Array[i])
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesBool() []bool {
if av.Type != GGUFMetadataValueTypeBool {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]bool, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.Bool(av.Array[i])
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesString() []string {
if av.Type != GGUFMetadataValueTypeString {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]string, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.String(av.Array[i])
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesArray() []GGUFMetadataKVArrayValue {
if av.Type != GGUFMetadataValueTypeArray {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]GGUFMetadataKVArrayValue, av.Len)
for i := uint64(0); i < av.Len; i++ {
switch t := av.Array[i].(type) {
case GGUFMetadataKVArrayValue:
v[i] = t
case map[string]any:
v[i] = GGUFMetadataKVArrayValue{
Type: anyx.Number[GGUFMetadataValueType](t["type"]),
Len: anyx.Number[uint64](t["len"]),
Array: func() []any {
if vv, ok := t["array"].([]any); ok {
return vv
}
return nil
}(),
StartOffset: anyx.Number[int64](t["startOffset"]),
Size: anyx.Number[int64](t["size"]),
}
default:
panic(fmt.Errorf("invalid type: %T", av.Array[i]))
}
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesUint64() []uint64 {
if av.Type != GGUFMetadataValueTypeUint64 {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]uint64, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.Number[uint64](av.Array[i])
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesInt64() []int64 {
if av.Type != GGUFMetadataValueTypeInt64 {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]int64, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.Number[int64](av.Array[i])
}
return v
}
func (av GGUFMetadataKVArrayValue) ValuesFloat64() []float64 {
if av.Type != GGUFMetadataValueTypeFloat64 {
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v := make([]float64, av.Len)
for i := uint64(0); i < av.Len; i++ {
v[i] = anyx.Number[float64](av.Array[i])
}
return v
}
// ValuesNumeric returns the numeric values of the GGUFMetadataKVArrayValue,
// and panics if the value type is not numeric.
//
// ValuesNumeric is a generic function, and the type T must be constraints.Integer or constraints.Float.
//
// Compare to the GGUFMetadataKVArrayValue's Value* functions,
// ValuesNumeric will cast the original value to the target type.
func ValuesNumeric[T constraints.Integer | constraints.Float](av GGUFMetadataKVArrayValue) []T {
v := make([]T, av.Len)
for i := uint64(0); i < av.Len; i++ {
switch av.Type {
case GGUFMetadataValueTypeUint8:
case GGUFMetadataValueTypeInt8:
case GGUFMetadataValueTypeUint16:
case GGUFMetadataValueTypeInt16:
case GGUFMetadataValueTypeUint32:
case GGUFMetadataValueTypeInt32:
case GGUFMetadataValueTypeFloat32:
case GGUFMetadataValueTypeUint64:
case GGUFMetadataValueTypeInt64:
case GGUFMetadataValueTypeFloat64:
default:
panic(fmt.Errorf("invalid type: %v", av.Type))
}
v[i] = anyx.Number[T](av.Array[i])
}
return v
}
// Get returns the GGUFMetadataKV with the given key,
// and true if found, and false otherwise.
func (kvs GGUFMetadataKVs) Get(key string) (value GGUFMetadataKV, found bool) {
for i := range kvs {
if kvs[i].Key == key {
return kvs[i], true
}
}
return GGUFMetadataKV{}, false
}
// Search returns a list of GGUFMetadataKV with the keys that match the given regex.
func (kvs GGUFMetadataKVs) Search(keyRegex *regexp.Regexp) (values []GGUFMetadataKV) {
for i := range kvs {
if keyRegex.MatchString(kvs[i].Key) {
values = append(values, kvs[i])
}
}
return values
}
// Index returns a map value to the GGUFMetadataKVs with the given keys,
// and the number of keys found.
func (kvs GGUFMetadataKVs) Index(keys []string) (values map[string]GGUFMetadataKV, found int) {
ks := make(map[string]struct{}, len(keys))
for i := range keys {
ks[keys[i]] = struct{}{}
}
values = make(map[string]GGUFMetadataKV)
for i := range kvs {
if _, ok := ks[kvs[i].Key]; ok {
values[kvs[i].Key] = kvs[i]
found++
}
if found == len(ks) {
break
}
}
return values, found
}
// Get returns the GGUFTensorInfo with the given name,
// and true if found, and false otherwise.
func (ti GGUFTensorInfo) Get(name string) (info GGUFTensorInfo, found bool) {
if ti.Name == name {
return ti, true
}
return GGUFTensorInfo{}, false
}
// GetFileType returns the GGUFFileType.
func (ti GGUFTensorInfo) GetFileType() GGUFFileType {
return GetFileType(map[GGMLType]int{ti.Type: 1})
}
// Match returns true if the name of the GGUFTensorInfo matches the given regex.
func (ti GGUFTensorInfo) Match(nameRegex *regexp.Regexp) bool {
return nameRegex.MatchString(ti.Name)
}
// Search returns a list of GGUFTensorInfo with the names that match the given regex.
func (ti GGUFTensorInfo) Search(nameRegex *regexp.Regexp) (infos []GGUFTensorInfo) {
if nameRegex.MatchString(ti.Name) {
return []GGUFTensorInfo{ti}
}
return nil
}
// Index returns a map value to the GGUFTensorInfo with the given names,
// and the number of names found.
func (ti GGUFTensorInfo) Index(names []string) (infos map[string]GGUFTensorInfo, found int) {
if len(names) == 0 {
return nil, 0
}
if names[0] == ti.Name {
return map[string]GGUFTensorInfo{ti.Name: ti}, 1
}
return nil, 0
}
// Elements returns the number of elements of the GGUFTensorInfo,
// which is inspired by
// https://github.com/ggerganov/ggml/blob/a10a8b880c059b3b29356eb9a9f8df72f03cdb6a/src/ggml.c#L2597-L2601.
func (ti GGUFTensorInfo) Elements() uint64 {
if ti.NDimensions == 0 {
return 0
}
ret := uint64(1)
for i := uint32(0); i < ti.NDimensions; i++ {
ret *= ti.Dimensions[i]
}
return ret
}
// Bytes returns the number of bytes of the GGUFTensorInfo,
// which is inspired by
// https://github.com/ggerganov/ggml/blob/a10a8b880c059b3b29356eb9a9f8df72f03cdb6a/src/ggml.c#L2609-L2626.
func (ti GGUFTensorInfo) Bytes() uint64 {
if ti.NDimensions == 0 {
return 0
}
tt, ok := ti.Type.Trait()
if !ok {
panic(fmt.Errorf("invalid type: %v", ti.Type))
}
// https://github.com/ggerganov/ggml/blob/a10a8b880c059b3b29356eb9a9f8df72f03cdb6a/src/ggml.c#L3210-L3214
nb := make([]uint64, 0, ti.NDimensions)
{
nb = append(nb, tt.TypeSize)
nb = append(nb, nb[0]*(ti.Dimensions[0]/tt.BlockSize))
for i := uint32(2); i < ti.NDimensions; i++ {
nb = append(nb, nb[i-1]*ti.Dimensions[i-1])
}
}
var ret uint64
if tt.BlockSize == 1 {
ret = tt.TypeSize
for i := uint32(0); i < ti.NDimensions; i++ {
ret += (ti.Dimensions[i] - 1) * nb[i]
}
return ret
}
ret = ti.Dimensions[0] * nb[0] / tt.BlockSize
for i := uint32(1); i < ti.NDimensions; i++ {
ret += (ti.Dimensions[i] - 1) * nb[i]
}
return ret
}
// Count returns the number of GGUF tensors of the GGUFTensorInfo,
// which is always 1.
func (ti GGUFTensorInfo) Count() uint64 {
return 1
}
// Get returns the GGUFTensorInfo with the given name,
// and true if found, and false otherwise.
func (tis GGUFTensorInfos) Get(name string) (info GGUFTensorInfo, found bool) {
for i := range tis {
if tis[i].Name == name {
return tis[i], true
}
}
return GGUFTensorInfo{}, false
}
// GetFileType returns the GGUFFileType represented the mostly GGMLType of the GGUFTensorInfos.
func (tis GGUFTensorInfos) GetFileType() GGUFFileType {
if len(tis) == 0 {
return _GGUFFileTypeCount
}
cm := make(map[GGMLType]int)
for i := range tis {
cm[tis[i].Type]++
}
return GetFileType(cm)
}
// Match returns true if a tensor of GGUFTensorInfos matches the given regex.
func (tis GGUFTensorInfos) Match(nameRegex *regexp.Regexp) bool {
for i := range tis {
if nameRegex.MatchString(tis[i].Name) {
return true
}
}
return false
}
// Search returns a list of GGUFTensorInfo with the names that match the given regex.
func (tis GGUFTensorInfos) Search(nameRegex *regexp.Regexp) (infos []GGUFTensorInfo) {
for i := range tis {
if nameRegex.MatchString(tis[i].Name) {
infos = append(infos, tis[i])
}
}
return infos
}
// Index returns a map value to the GGUFTensorInfos with the given names,
// and the number of names found.
func (tis GGUFTensorInfos) Index(names []string) (infos map[string]GGUFTensorInfo, found int) {
ns := make(map[string]struct{}, len(names))
for i := range names {
ns[names[i]] = struct{}{}
}
infos = make(map[string]GGUFTensorInfo)
for i := range tis {
if _, ok := ns[tis[i].Name]; ok {
infos[tis[i].Name] = tis[i]
found++
}
if found == len(ns) {
break
}
}
return infos, found
}
// Elements returns the number of elements of the GGUFTensorInfos.
func (tis GGUFTensorInfos) Elements() uint64 {