forked from foldl/chatllm.cpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
convert.py
4787 lines (3983 loc) · 186 KB
/
convert.py
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
"""
Convert Hugging Face models to GGML format
"""
import argparse
from ast import Dict, Tuple
from collections import OrderedDict
import json
import struct
import os
import io
import pickle
import re
from pathlib import Path
from enum import Enum, IntEnum
from pathlib import Path
from typing import IO, Any, Iterable, List, Optional, Tuple
import numpy as np
import math
from attr import dataclass
import torch
from torch import nn
from tabulate import tabulate
from tqdm import tqdm
import msgpack
from sentencepiece import SentencePieceProcessor # type: ignore
GGML_QK8_0 = 32
GGML_QK4_0 = 32
GGML_QK4_1 = 32
GGML_MEM_ALIGN = 16
class GGMLType(Enum):
F32 = 0
F16 = 1
Q4_0 = 2
Q4_1 = 3
Q8_0 = 8
class ModelType(Enum):
CHATGLM = 1
CHATGLM2 = 2
CHATGLM3 = 3
CODEGEEX2 = 4
CharacterGLM = 5
CHATGLM4 = 6
CODEGEEX4 = 7
InternLM = 0x100
InternLM2 = 0x101
InternLM3 = 0x102
LlaMA2 = 0x150
CodeLlaMA = 0x151
WizardCoder = 0x152
WizardLM = 0x153
WizardMath = 0x154
TigerBot = 0x155
LlaMA2Plus = 0x156
Megrez = 0x157
Falcon3 = 0x158
BaiChuanLlama = 0x200
BaiChuan = 0x201
DeepSeek = 0x300
DeepSeekCoder = 0x301
CodeFuseDeepSeek = 0x302
NuminaMath = 0x303
DeepSeekV2Light = 0x320
DeepSeekV2 = 0x321
Yi = 0x400
MAP_Neo = 0x401
Phi2 = 0x500
Phi2_v2 = 0x501
DolphinPhi2 = 0x510
DolphinPhi2_v2 = 0x511
Phi3 = 0x520
Phi3_ScalingSU = 0x521
Phi3_ScalingSU2 = 0x522
Phi3_ScalingSU3 = 0x523
Phi3MoE_ScalingSU = 0x530
Mistral = 0x600
Mixtral = 0x601
OpenChat = 0x602
NeuralBeagle = 0x603
Starling = 0x604
WizardLMMoE = 0x605
Mistral2 = 0x606
QWen = 0x700
QWen2 = 0x710
QWen2Tie = 0x711
QWen2MoE = 0x750
MarcoO1 = 0x751
QwQ = 0x752
BlueLM = 0x800
StableLM = 0x900
Orion = 0x1000
MiniCPM = 0x1100
MiniCPM2 = 0x1101 # updated chat template, no tie_word_embeddings=False
MiniCPM_MoE = 0x1102
MiniCPM3 = 0x1110
Persimmon = 0x1200
Fuyu = 0x1201
Gemma = 0x1300
Gemma2 = 0x1301
CohereCommand = 0x1400
CohereAya23 = 0x1401
CohereCommandR7B = 0x1402
Grok1 = 0x1500
Zhinao = 0x1600
LlaMA3 = 0x1700
SmolLM = 0x1701
GroqToolUse = 0x1702
LlaMA31 = 0x1703
LlaMA32 = 0x1704
Exaone = 0x1705
StarCoder2 = 0x1800
XVERSE = 0x1900
Index = 0x1a00
OLMoE = 0x1b00
AlphaGeometryLM = 0x1c00
GraniteMoE = 0x1d00
Granite = 0x1d01
TeleChat2 = 0x1e00
LlaMAMulti = 0x20000001
BCE_Embedding = 0x10000100
BCE_ReRanker = 0x10000101
BGE_M3 = 0x10000102
BGE_ReRankerM3 = 0x10000103
class TokenType(Enum):
UNDEFINED = 0
NORMAL = 1
UNKNOWN = 2
CONTROL = 3
USER_DEFINED = 4
UNUSED = 5
BYTE = 6
class TokenizerType(Enum):
BPE1 = 0
BPE2 = 1
Unigram = 2
g_tokenizer_type = TokenizerType.BPE1
g_special_tokens: Dict = {}
def quantize_q8_0(tensor: torch.Tensor) -> torch.CharTensor:
# equivalent to ggml_quantize_q8_0 in ggml.c
assert tensor.shape[1] % GGML_QK8_0 == 0
tensor = tensor.view(-1, GGML_QK8_0)
scale = tensor.abs().max(dim=-1, keepdim=True).values / ((1 << 7) - 1)
tensor = (tensor / scale).round().clamp(min=-128, max=127).char()
# add scale into each block
tensor = torch.cat((scale.half().view(torch.int8), tensor), dim=-1)
return tensor
def quantize_q4_0(tensor: torch.Tensor) -> torch.CharTensor:
# equivalent to ggml_quantize_q4_0 in ggml.c
assert tensor.shape[1] % GGML_QK4_0 == 0
tensor = tensor.view(-1, GGML_QK4_0)
abs_max_indices = tensor.abs().max(dim=-1, keepdim=True).indices
max_values = torch.take_along_dim(tensor, abs_max_indices, dim=-1)
scale = max_values / -8
tensor = (tensor / scale + 8).round().clamp(min=0, max=15).char()
# compress two int4 weights into a int8
tensor = tensor[:, :16] | (tensor[:, 16:] << 4)
# add scale into each block
tensor = torch.cat((scale.half().view(torch.int8), tensor), dim=-1)
return tensor
def quantize_q4_1(tensor: torch.Tensor) -> torch.CharTensor:
# equivalent to ggml_quantize_q4_1 in ggml.c
assert tensor.shape[1] % GGML_QK4_1 == 0
tensor = tensor.view(-1, GGML_QK4_1)
abs_max_indices = tensor.max(dim=-1, keepdim=True).indices
max_values = torch.take_along_dim(tensor, abs_max_indices, dim=-1)
abs_min_indices = tensor.min(dim=-1, keepdim=True).indices
min_values = torch.take_along_dim(tensor, abs_min_indices, dim=-1)
scale = (max_values - min_values) / 15
tensor = ((tensor - min_values) / scale).round().clamp(min=0, max=15).char()
# compress two int4 weights into a int8
tensor = tensor[:, :16] | (tensor[:, 16:] << 4)
# add scale into each block
tensor = torch.cat((scale.half().view(torch.int8), min_values.half().view(torch.int8), tensor), dim=-1)
return tensor
def dump_tensor(f, name: str, tensor: torch.Tensor, ggml_type: GGMLType):
assert tensor.dtype == torch.float32
# tensor name
f.write(struct.pack("i", len(name.encode())))
f.write(name.encode())
# tensor shape & dtype
f.write(struct.pack("i" * (2 + tensor.ndim), tensor.ndim, *tensor.shape, ggml_type.value))
# tensor data
if ggml_type == GGMLType.F32:
tensor = tensor.float()
elif ggml_type == GGMLType.F16:
tensor = tensor.half()
elif ggml_type == GGMLType.Q8_0:
tensor = quantize_q8_0(tensor)
elif ggml_type == GGMLType.Q4_0:
tensor = quantize_q4_0(tensor)
elif ggml_type == GGMLType.Q4_1:
tensor = quantize_q4_1(tensor)
else:
raise NotImplementedError(f"Cannot dump tensor of dtype {tensor.dtype}")
# align address
aligned_pos = (f.tell() + (GGML_MEM_ALIGN - 1)) // GGML_MEM_ALIGN * GGML_MEM_ALIGN
f.seek(aligned_pos)
tensor.numpy().tofile(f)
def load_model_file(path: Path) -> Dict:
print(f"loading {path} ...")
fp = open(path, 'rb')
first8 = fp.read(8)
fp.seek(0)
if first8[:2] == b'PK':
return torch.load(fp, map_location=torch.device('cpu')).items()
elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
from safetensors import safe_open
tensors = []
with safe_open(path, framework="pt", device="cpu") as f:
for key in f.keys():
tensors.append((key, f.get_tensor(key)))
return tensors
else:
raise ValueError(f"unknown format: {path}")
class AttributeDict(dict):
def __getattr__(self, key):
return self.__getitem__(key) if key in self else None
__setattr__ = dict.__setitem__
def transpose(weight, fan_in_fan_out):
return weight.T if fan_in_fan_out else weight
class LoRAState:
def __init__(self, path: Path, verbose: bool = False) -> None:
self.verbose = verbose
with open(path / 'adapter_config.json', 'r') as fp:
config = AttributeDict(json.load(fp))
assert config.peft_type == 'LORA', f"peft_type must be `LORA`"
self.scaling = config.lora_alpha / config.r
self.fan_in_fan_out = config.fan_in_fan_out
self.files = []
for glob in ["adapter_model.safetensors", "adapter_model.bin"]:
files = list(path.glob(glob))
if len(files) > 0:
files.sort()
self.files = files
break
if len(self.files) < 1:
raise Exception('can not find model files, or unsupported format.')
self.tensor_dict = {}
for f in self.files:
for k, v in load_model_file(f):
self.tensor_dict[k] = v
if self.verbose:
print(f"LoRA tensors: {self.tensor_dict.keys()}")
# based on: https://github.com/ymcui/Chinese-LLaMA-Alpaca-3/blob/main/scripts/merge_llama3_with_chinese_lora_low_mem.py
def merge_tensor(self, name: str, tensor: torch.Tensor) -> torch.Tensor:
saved_key = 'base_model.model.' + name
if saved_key in self.tensor_dict:
if self.verbose:
print(f"LoRA replacing: {name}")
return self.tensor_dict[saved_key]
lora_key_A = saved_key.replace('.weight','.lora_A.weight')
if lora_key_A in self.tensor_dict:
if self.verbose:
print(f"LoRA merging: {name}")
lora_key_B = saved_key.replace('.weight','.lora_B.weight')
return tensor.float() + (
transpose(
self.tensor_dict[lora_key_B].float()
@ self.tensor_dict[lora_key_A].float(), self.fan_in_fan_out) * self.scaling
)
return tensor
g_lora: LoRAState = None
def load_all_model_files(model_files) -> Dict:
global g_lora
for f in model_files:
r = {}
data = load_model_file(f)
for k, v in data:
if k in r:
raise Exception(f"tensor {k} already loaded. maybe it is stored cross files?")
r[k] = g_lora.merge_tensor(k, v) if g_lora is not None else v
yield r
def dump_state_dict(f, weight_names, model_files, ggml_type, config, state_dict_pp, loader_fun = None):
tensor_info = []
converted_names = []
# Note: incremental loading and converting
state_dict_cache = {}
remaining: List = weight_names.copy()
if loader_fun is None:
loader_fun = load_all_model_files
for state_dict in loader_fun(model_files):
this_round = {}
state_dict = state_dict_pp(config, state_dict)
for x in remaining:
if x in state_dict:
this_round[x] = state_dict[x]
del state_dict[x]
elif x in state_dict_cache:
this_round[x] = state_dict_cache[x]
del state_dict_cache[x]
else:
break
remaining = remaining[len(this_round):]
for x in state_dict:
state_dict_cache[x] = state_dict[x]
for name in tqdm(this_round.keys(), desc="Dumping ..."):
tensor: torch.Tensor = this_round[name]
tensor = tensor.float()
if tensor.ndim == 2:
if tensor.shape[1] % GGML_QK8_0 == 0:
tensor_ggml_type = ggml_type
else:
tensor_ggml_type = GGMLType.F16
else:
# 1d weight: convert it to float32
assert tensor.ndim == 1
tensor_ggml_type = GGMLType.F32
dump_tensor(f, name, tensor, tensor_ggml_type)
tensor_info.append((name, tensor.shape, tensor_ggml_type.name))
print(tabulate(tensor_info, headers=["name", "shape", "dtype"], tablefmt="psql"))
if len(tensor_info) != len(weight_names):
raise Exception(f'not all tensors are converted: {remaining}')
class SentencePieceVocab:
def __init__(self, fname_tokenizer: Path, fname_added_tokens: Optional[Path]) -> None:
self.sentencepiece_tokenizer = SentencePieceProcessor(str(fname_tokenizer))
added_tokens: Dict[str, int]
if fname_added_tokens is not None:
added_tokens = json.load(open(fname_added_tokens, encoding='utf-8'))
else:
added_tokens = {}
vocab_size: int = self.sentencepiece_tokenizer.vocab_size()
print("vocab_size ", vocab_size)
expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
actual_ids = sorted(added_tokens.values())
if expected_ids != actual_ids:
if actual_ids == list(range(len(added_tokens))):
raise Exception(f"added token IDs ({actual_ids}) are starting from 0. `added_token.json` seems WRONG.\n\nDelete it and try again.")
else:
raise Exception(f"Expected added token IDs to be sequential and start at {vocab_size}; got {actual_ids}.\n\nDelete it and try again.")
items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
self.added_tokens_list = [text for (text, idx) in items]
self.vocab_size_base: int = vocab_size
self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list)
self.fname_tokenizer = fname_tokenizer
self.fname_added_tokens = fname_added_tokens
def sentencepiece_tokens(self) -> Iterable[Tuple[bytes, float]]:
tokenizer = self.sentencepiece_tokenizer
for i in range(tokenizer.vocab_size()):
text: bytes
if tokenizer.is_unknown(i):
text = " \u2047 ".encode("utf-8")
elif tokenizer.is_control(i):
text = b""
elif tokenizer.is_byte(i):
piece = tokenizer.id_to_piece(i)
if len(piece) != 6:
raise Exception(f"Invalid token: {piece}")
byte_value = int(piece[3:-1], 16)
text = struct.pack("B", byte_value)
else:
text = tokenizer.id_to_piece(i).replace("\u2581", " ").encode("utf-8")
score: float = tokenizer.get_score(i)
yield text, score
def added_tokens(self) -> Iterable[Tuple[bytes, float]]:
for text in self.added_tokens_list:
score = -1000.0
yield text.encode("utf-8"), score
def all_tokens(self) -> Iterable[Tuple[bytes, float]]:
yield from self.sentencepiece_tokens()
yield from self.added_tokens()
def write_vocab(self, fout: io.BufferedWriter) -> None:
for text, score in self.all_tokens():
fout.write(struct.pack("i", len(text)))
fout.write(text)
fout.write(struct.pack("f", score))
# marks the end of vocab
fout.write(struct.pack("i", -1))
def __repr__(self) -> str:
return f"<SentencePieceVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
class SimpleVocab:
def __init__(self, fname_tokenizer: Path) -> None:
vocab = []
with open(fname_tokenizer, encoding='utf-8') as f:
for l in f.readlines():
l = l.split()
if len(l) != 2:
break
vocab.append((l[0], float(l[1])))
self.vocab = vocab
print("vocab_size ", len(vocab))
def sentencepiece_tokens(self) -> Iterable[Tuple[bytes, float]]:
for (piece, score) in self.vocab:
if (len(piece) == 6) and (piece[0] == '<') and (piece[5] == '>'):
byte_value = int(piece[3:-1], 16)
text = struct.pack("B", byte_value)
score = -1000.0
else:
text = piece.replace("\u2581", " ").encode("utf-8")
yield text, score
def all_tokens(self) -> Iterable[Tuple[bytes, float]]:
yield from self.sentencepiece_tokens()
def write_vocab(self, fout: io.BufferedWriter) -> None:
for text, score in self.all_tokens():
fout.write(struct.pack("i", len(text)))
fout.write(text)
fout.write(struct.pack("f", score))
# marks the end of vocab
fout.write(struct.pack("i", -1))
def __repr__(self) -> str:
return f"<SimpleVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
class UnigramTokenizerJsonVocab:
def __init__(self, fname_tokenizer: Path, fname_added_tokens: Optional[Path]) -> None:
global g_tokenizer_type
g_tokenizer_type = TokenizerType.Unigram
model = json.load(open(fname_tokenizer / "tokenizer.json", encoding='utf-8'))
if model['model']['type'] != 'Unigram':
raise Exception(f"Unigram expected, but {model['model']['type']} encountered.")
if fname_added_tokens is not None:
raise Exception(f"TODO: fname_added_tokens")
self.vocal_tokens = model['model']['vocab']
self.vocab_size: int = len(self.vocal_tokens)
print("Unigram vocab_size ", self.vocab_size)
def tokenizer_tokens(self) -> Iterable[Tuple[bytes, float]]:
for v in self.vocal_tokens:
tok = v[0]
score = v[1]
text: bytes = tok.encode('utf-8')
if tok == '<unk>':
text = " \u2047 ".encode("utf-8")
else:
text = tok.replace("\u2581", " ").encode("utf-8")
yield text, score
def all_tokens(self) -> Iterable[Tuple[bytes, float]]:
yield from self.tokenizer_tokens()
def write_vocab(self, fout: io.BufferedWriter) -> None:
for text, score in self.all_tokens():
fout.write(struct.pack("<i", len(text)))
fout.write(text)
fout.write(struct.pack("<f", score))
# marks the end of vocab
fout.write(struct.pack("i", -1))
def __repr__(self) -> str:
return f"<UnigramTokenizerJsonVocab with {self.vocab_size} tokens>"
class FastTokenizerVocab:
def __init__(self, fname_tokenizer: Path, fname_added_tokens: Optional[Path]) -> None:
global g_special_tokens
global g_tokenizer_type
g_tokenizer_type = TokenizerType.BPE2
model = json.load(open(fname_tokenizer / "tokenizer.json", encoding='utf-8'))
if model['model']['type'] != 'BPE':
raise Exception(f"BPE expected, but {model['model']['type']} encountered.")
all_tokens: Dict[str, int] = {}
if fname_added_tokens is not None:
all_tokens = json.load(open(fname_added_tokens))
for tok, tokidx in sorted([(t['content'], t['id']) for t in model['added_tokens']], key=lambda x: x[1]):
all_tokens[tok] = tokidx
g_special_tokens[tok] = tokidx
for tok in model['model']['vocab'].keys():
tokidx = model['model']['vocab'][tok]
all_tokens[tok] = tokidx
all_ids = sorted(list(all_tokens.values()))
vocab_size: int = all_ids[-1] + 1
if vocab_size != len(all_ids):
raise Exception(f'vacab size is {vocab_size}, but {len(all_ids)} tokens are loaded.')
items: OrderedDict[str, int] = OrderedDict()
items = sorted(all_tokens.items(), key=lambda text_idx: text_idx[1])
self.vocab_size: int = vocab_size
self.vocal_tokens = items
self.merges = model['model']['merges']
print("vocab_size ", self.vocab_size)
def tokenizer_tokens(self) -> Iterable[Tuple[bytes, float]]:
for tok, idx in self.vocal_tokens:
t = TokenType.NORMAL.value
if tok in g_special_tokens:
t = TokenType.USER_DEFINED.value
text = tok.encode("utf-8")
else:
matches = re.findall('<0x([0-9a-fA-F]+)>', tok)
if len(matches) == 1:
text: bytes = bytes([int(matches[0], 16)])
else:
text: bytes = tok.replace("\u2581", " ").encode("utf-8")
yield text, t
def all_tokens(self) -> Iterable[Tuple[bytes, float]]:
yield from self.tokenizer_tokens()
def write_vocab(self, fout: io.BufferedWriter) -> None:
for text, tt in self.all_tokens():
fout.write(struct.pack("i", len(text)))
fout.write(text)
fout.write(struct.pack("B", tt))
# marks the end of vocab
fout.write(struct.pack("i", -1))
for s in self.merges:
if isinstance(s, list):
s = f"{s[0]} {s[1]}"
text = s.encode('utf-8')
fout.write(struct.pack("i", len(text)))
fout.write(text)
fout.write(struct.pack("i", -1))
def __repr__(self) -> str:
return f"<FastTokenizerVocab with {self.vocab_size} tokens>"
class GenericBPETokenizerVocab:
def __init__(self, vocab_fn: Path, merges_fn: Path) -> None:
all_tokens: Dict[str, int] = {}
vocab_dict = json.load(open(vocab_fn, encoding='utf-8'))
for tok in vocab_dict.keys():
tokidx = vocab_dict[tok]
all_tokens[tok] = tokidx
all_ids = sorted(list(all_tokens.values()))
vocab_size: int = all_ids[-1] + 1
if vocab_size != len(all_ids):
raise Exception(f'vacab size is {vocab_size}, but {len(all_ids)} tokens are loaded.')
items: OrderedDict[str, int] = OrderedDict()
items = sorted(all_tokens.items(), key=lambda text_idx: text_idx[1])
self.vocab_size: int = vocab_size
self.vocal_tokens = items
with open(merges_fn, 'r', encoding='utf-8') as f:
self.merges = [l.strip() for l in f.readlines()]
if self.merges[0].startswith('#'):
self.merges.pop(0)
print("vocab_size ", self.vocab_size)
def tokenizer_tokens(self) -> Iterable[Tuple[bytes, float]]:
for tok, idx in self.vocal_tokens:
text: bytes = tok.encode('utf-8')
t = TokenType.NORMAL.value
if tok in g_special_tokens:
t = TokenType.USER_DEFINED.value
yield text, t
def all_tokens(self) -> Iterable[Tuple[bytes, float]]:
yield from self.tokenizer_tokens()
def write_vocab(self, fout: io.BufferedWriter) -> None:
for text, tt in self.all_tokens():
fout.write(struct.pack("i", len(text)))
fout.write(text)
fout.write(struct.pack("B", tt))
# marks the end of vocab
fout.write(struct.pack("i", -1))
for s in self.merges:
text = s.encode('utf-8')
fout.write(struct.pack("i", len(text)))
fout.write(text)
fout.write(struct.pack("i", -1))
def __repr__(self) -> str:
return f"<GenericBPETokenizerVocab with {self.vocab_size} tokens>"
class TikTokenizerVocab:
@staticmethod
def token_bytes_to_string(b):
from transformers.models.gpt2.tokenization_gpt2 import bytes_to_unicode
byte_encoder = bytes_to_unicode()
return ''.join([byte_encoder[ord(char)] for char in b.decode('latin-1')])
@staticmethod
def bpe(mergeable_ranks: dict[bytes, int], token: bytes, max_rank: Optional[int] = None) -> list[bytes]:
parts = [bytes([b]) for b in token]
while True:
min_idx = None
min_rank = None
for i, pair in enumerate(zip(parts[:-1], parts[1:])):
rank = mergeable_ranks.get(pair[0] + pair[1])
if rank is not None and (min_rank is None or rank < min_rank):
min_idx = i
min_rank = rank
if min_rank is None or (max_rank is not None and min_rank >= max_rank):
break
assert min_idx is not None
parts = parts[:min_idx] + [parts[min_idx] + parts[min_idx + 1]] + parts[min_idx + 2:]
return parts
def __init__(self, fname_tokenizer: Any, fname_added_tokens: Optional[Path]) -> None:
global g_tokenizer_type
g_tokenizer_type = TokenizerType.BPE2
if isinstance(fname_tokenizer, Path):
from transformers import AutoTokenizer # type: ignore[attr-defined]
tokenizer = AutoTokenizer.from_pretrained(fname_tokenizer, trust_remote_code=True)
vocab_size = max(tokenizer.get_vocab().values()) + 1
else:
tokenizer = fname_tokenizer
vocab_size = len(tokenizer.mergeable_ranks)
merges = []
vocab = {}
mergeable_ranks = tokenizer.mergeable_ranks
for token, rank in mergeable_ranks.items():
vocab[self.token_bytes_to_string(token)] = rank
if len(token) == 1:
continue
merged = TikTokenizerVocab.bpe(mergeable_ranks, token, max_rank=rank)
if len(merged) != 2:
continue
merges.append(' '.join(map(self.token_bytes_to_string, merged)))
reverse_vocab = {id_ : encoded_tok for encoded_tok, id_ in vocab.items()}
added_vocab = tokenizer.special_tokens
vocab_tokens = []
for i in range(vocab_size):
if i not in reverse_vocab:
pad_token = f"[PAD{i}]".encode("utf-8")
vocab_tokens.append((bytearray(pad_token), TokenType.USER_DEFINED.value))
elif reverse_vocab[i] in added_vocab:
vocab_tokens.append((reverse_vocab[i], TokenType.CONTROL.value))
else:
vocab_tokens.append((reverse_vocab[i], TokenType.NORMAL.value))
self.vocab_size: int = vocab_size
self.merges = merges
self.vocab_tokens = vocab_tokens
print(len(vocab_tokens))
print("vocab_size ", self.vocab_size)
def tokenizer_tokens(self) -> Iterable[Tuple[bytes, float]]:
for tok, t in self.vocab_tokens:
yield tok, t
def all_tokens(self) -> Iterable[Tuple[bytes, float]]:
yield from self.tokenizer_tokens()
def write_vocab(self, fout: io.BufferedWriter) -> None:
for tok, tt in self.all_tokens():
text = tok.encode('utf-8')
fout.write(struct.pack("i", len(text)))
fout.write(text)
fout.write(struct.pack("B", tt))
# marks the end of vocab
fout.write(struct.pack("i", -1))
for s in self.merges:
text = s.encode('utf-8')
fout.write(struct.pack("i", len(text)))
fout.write(text)
# marks the end of additional vocab
fout.write(struct.pack("i", -1))
def __repr__(self) -> str:
return f"<TikTokenizerVocab with {self.vocab_size} tokens>"
def load_vocab_from_tiktok_mergeable_ranks(path9):
import base64
PAT_STR = r"""(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\r\n\p{L}\p{N}]?\p{L}+|\p{N}| ?[^\s\p{L}\p{N}]+[\r\n]*|\s*[\r\n]+|\s+(?!\S)|\s+"""
def _load_tiktoken_bpe(tiktoken_bpe_file: str):
with open(tiktoken_bpe_file, "rb") as f:
contents = f.read()
return {
base64.b64decode(token): int(rank)
for token, rank in (line.split() for line in contents.splitlines() if line)
}
mergeable_ranks = _load_tiktoken_bpe(path9)
class TempTokenizer:
def __init__(self, mergeable_ranks) -> None:
self.mergeable_ranks = mergeable_ranks
self.special_tokens = {}
return TikTokenizerVocab(TempTokenizer(mergeable_ranks), fname_added_tokens = None)
class BaseConverter:
FILE_VERSION = 1
@classmethod
def pp(cls, config, name: str, tensor):
return tensor
@classmethod
def state_dict_pp(cls, config, state_dict):
for name in state_dict:
tensor: torch.Tensor = state_dict[name]
tensor = cls.pp(config, name, tensor)
state_dict[name] = tensor
return state_dict
@classmethod
def convert(cls, config, model_files, vocab: Any, ggml_type, save_path):
# convert all weights to fp16
with open(save_path, "wb") as f:
f.write(b"ggml") # magic
f.write(struct.pack("ii", cls.MODEL_TYPE.value, cls.FILE_VERSION)) # model type & version
cls.dump_config(f, config, ggml_type)
vocab.write_vocab(f)
weight_names = cls.get_weight_names(config)
dump_state_dict(f, weight_names, model_files, ggml_type, config, cls.state_dict_pp)
print(f"{cls.MODEL_TYPE.name} GGML model saved to {save_path}")
def permute(weights: torch.Tensor, n_head: int) -> torch.Tensor:
return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
.swapaxes(1, 2)
.reshape(weights.shape))
def permute_pair(weights: torch.Tensor, n_head: int) -> torch.Tensor:
return (weights.reshape(n_head, weights.shape[0] // n_head // 2, 2, *weights.shape[1:])
.swapaxes(1, 2)
.reshape(weights.shape))
class InternLMConverter(BaseConverter):
MODEL_TYPE = ModelType.InternLM
@classmethod
def pp(cls, config, name: str, tensor):
if name.endswith('k_proj.weight') or name.endswith('q_proj.weight'):
return permute(tensor, config.num_attention_heads)
return tensor
@staticmethod
def dump_config(f, config, ggml_type):
assert config.hidden_act == 'silu', "hidden_act must be silu"
rope_theta = 10000
rope_scaling = 1.0
num_key_value_heads = config.num_key_value_heads if config.num_key_value_heads is not None else config.num_attention_heads
if config.rotary is not None:
assert config.rotary['type'] == 'dynamic', "rotary['type'] must be dynamic"
rope_theta = config.rotary['base']
rope_scaling = config.rotary.get("scaling_factor", 1.0)
if config.bias:
assert num_key_value_heads == config.num_attention_heads, "num_key_value_heads must equal to num_attention_heads"
assert rope_theta == 10000, "rotary['base'] must be 10000"
assert rope_scaling == 1.0, "rotary['base'] must be 10000"
config_values = [
ggml_type.value,
config.vocab_size,
config.hidden_size,
config.num_attention_heads,
config.num_hidden_layers,
config.intermediate_size,
config.max_position_embeddings,
config.bos_token_id if config.bos_token_id is not None else -1,
config.eos_token_id if config.eos_token_id is not None else -1,
config.pad_token_id if config.pad_token_id is not None else -1,
config.sep_token_id if config.sep_token_id is not None else -1,
]
f.write(struct.pack("i" * len(config_values), *config_values))
if not config.bias:
config_values = [
num_key_value_heads,
]
f.write(struct.pack("i" * len(config_values), *config_values))
f.write(struct.pack("<f", rope_theta))
f.write(struct.pack("<f", rope_scaling))
@staticmethod
def get_weight_names(config):
weight_names = ["model.embed_tokens.weight"]
for i in range(config.num_hidden_layers):
if config.bias:
weight_names += [
f"model.layers.{i}.self_attn.q_proj.weight",
f"model.layers.{i}.self_attn.q_proj.bias",
f"model.layers.{i}.self_attn.k_proj.weight",
f"model.layers.{i}.self_attn.k_proj.bias",
f"model.layers.{i}.self_attn.v_proj.weight",
f"model.layers.{i}.self_attn.v_proj.bias",
f"model.layers.{i}.self_attn.o_proj.weight",
f"model.layers.{i}.self_attn.o_proj.bias",
]
else:
weight_names += [
f"model.layers.{i}.self_attn.q_proj.weight",
f"model.layers.{i}.self_attn.k_proj.weight",
f"model.layers.{i}.self_attn.v_proj.weight",
f"model.layers.{i}.self_attn.o_proj.weight",
]
weight_names += [
f"model.layers.{i}.mlp.gate_proj.weight",
f"model.layers.{i}.mlp.down_proj.weight",
f"model.layers.{i}.mlp.up_proj.weight",
f"model.layers.{i}.input_layernorm.weight",
f"model.layers.{i}.post_attention_layernorm.weight",
]
weight_names += [
"model.norm.weight",
"lm_head.weight"
]
return weight_names
class InternLM2Converter(BaseConverter):
MODEL_TYPE = ModelType.InternLM3
@classmethod
def state_dict_pp(cls, config, state_dict):
new_dict = {}
for name in state_dict:
tensor: torch.Tensor = state_dict[name]
if name.endswith('attention.wqkv.weight'):
kv_groups = config.num_attention_heads // config.num_key_value_heads
head_dim = config.hidden_size // config.num_attention_heads
gs = 2 + kv_groups
h = tensor.shape[0] // (gs * head_dim)
v = tensor.view(h, gs, head_dim, config.hidden_size)
wq = v[:, 0:kv_groups, ...].reshape(h * kv_groups * head_dim, config.hidden_size)
wk = v[:, -2, ...].reshape(h * 1 * head_dim, config.hidden_size)
wv = v[:, -1, ...].reshape(h * 1 * head_dim, config.hidden_size)
new_dict[name.replace('attention.wqkv.weight', 'self_attn.q_proj.weight')] = permute(wq, config.num_attention_heads)
new_dict[name.replace('attention.wqkv.weight', 'self_attn.k_proj.weight')] = permute(wk, config.num_key_value_heads)
new_dict[name.replace('attention.wqkv.weight', 'self_attn.v_proj.weight')] = wv
else:
old_name: str = ''
mapping = {
'model.tok_embeddings.weight': 'model.embed_tokens.weight',
'model.norm.weight': 'model.norm.weight',
'output.weight': 'lm_head.weight',
'attention.wo.weight': 'self_attn.o_proj.weight',
'feed_forward.w1.weight': 'mlp.gate_proj.weight',
'feed_forward.w2.weight': 'mlp.down_proj.weight',
'feed_forward.w3.weight': 'mlp.up_proj.weight',
'attention_norm.weight': 'input_layernorm.weight',
'ffn_norm.weight': 'post_attention_layernorm.weight',
}
for k in mapping.keys():
if name.endswith(k):
old_name = name.replace(k, mapping[k])
break
if old_name == '':
raise Exception(f'unhandled tensor {name}')
new_dict[old_name] = tensor
return new_dict
@staticmethod
def dump_config(f, config, ggml_type):
assert config.hidden_act == 'silu', "hidden_act must be silu"
assert config.bias == False, "bias must be False"
if config.rope_scaling is not None:
assert config.rope_scaling['type'] == 'dynamic', "rope_scaling['type'] must be dynamic"
rope_scaling = config.rope_scaling.get("scaling_factor", 1.0)
else:
rope_scaling = 1.0
rope_theta = config.rope_theta
num_key_value_heads = config.num_key_value_heads
if config.eos_token_id is None:
eos_token_id = -1
elif isinstance(config.eos_token_id, list):
eos_token_id = config.eos_token_id[0]
else:
eos_token_id = config.eos_token_id
config_values = [
ggml_type.value,
config.vocab_size,
config.hidden_size,
config.num_attention_heads,
config.num_hidden_layers,
config.intermediate_size,
config.max_position_embeddings,
config.bos_token_id if config.bos_token_id is not None else -1,
eos_token_id,
config.pad_token_id if config.pad_token_id is not None else -1,