1
0

convert-hf-to-gguf.py 83 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937
  1. #!/usr/bin/env python3
  2. from __future__ import annotations
  3. import argparse
  4. import contextlib
  5. import json
  6. import os
  7. import re
  8. import sys
  9. from enum import IntEnum
  10. from pathlib import Path
  11. from typing import TYPE_CHECKING, Any, ContextManager, Iterator, Sequence, cast
  12. import numpy as np
  13. import torch
  14. if TYPE_CHECKING:
  15. from torch import Tensor
  16. if 'NO_LOCAL_GGUF' not in os.environ:
  17. sys.path.insert(1, str(Path(__file__).parent / 'gguf-py'))
  18. import gguf
  19. from convert import HfVocab
  20. ###### MODEL DEFINITIONS ######
  21. class SentencePieceTokenTypes(IntEnum):
  22. NORMAL = 1
  23. UNKNOWN = 2
  24. CONTROL = 3
  25. USER_DEFINED = 4
  26. UNUSED = 5
  27. BYTE = 6
  28. class Model:
  29. def __init__(self, dir_model: Path, ftype: int, fname_out: Path, is_big_endian: bool):
  30. self.dir_model = dir_model
  31. self.ftype = ftype
  32. self.fname_out = fname_out
  33. self.is_big_endian = is_big_endian
  34. self.endianess = gguf.GGUFEndian.BIG if is_big_endian else gguf.GGUFEndian.LITTLE
  35. self.is_safetensors = self._is_model_safetensors()
  36. self.num_parts = Model.count_model_parts(self.dir_model, ".safetensors" if self.is_safetensors else ".bin")
  37. self.part_names = self._get_part_names()
  38. self.hparams = Model.load_hparams(self.dir_model)
  39. self.model_arch = self._get_model_architecture()
  40. self.gguf_writer = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[self.model_arch], endianess=self.endianess, use_temp_file=False)
  41. self.block_count = self.find_hparam(["n_layers", "num_hidden_layers", "n_layer"])
  42. def find_hparam(self, keys: Sequence[str], optional: bool = False) -> Any:
  43. key = next((k for k in keys if k in self.hparams), None)
  44. if key is not None:
  45. return self.hparams[key]
  46. if optional:
  47. return None
  48. raise KeyError(f"could not find any of: {keys}")
  49. def set_vocab(self):
  50. self._set_vocab_gpt2()
  51. def get_tensors(self) -> Iterator[tuple[str, Tensor]]:
  52. for part_name in self.part_names:
  53. print(f"gguf: loading model part '{part_name}'")
  54. ctx: ContextManager[Any]
  55. if self.is_safetensors:
  56. from safetensors import safe_open
  57. ctx = cast(ContextManager[Any], safe_open(self.dir_model / part_name, framework="pt", device="cpu"))
  58. else:
  59. ctx = contextlib.nullcontext(torch.load(str(self.dir_model / part_name), map_location="cpu", mmap=True, weights_only=True))
  60. with ctx as model_part:
  61. for name in model_part.keys():
  62. data = model_part.get_tensor(name) if self.is_safetensors else model_part[name]
  63. yield name, data
  64. def set_gguf_parameters(self):
  65. self.gguf_writer.add_name(self.dir_model.name)
  66. self.gguf_writer.add_block_count(self.block_count)
  67. if (n_ctx := self.find_hparam(["max_position_embeddings", "n_ctx"], optional=True)) is not None:
  68. self.gguf_writer.add_context_length(n_ctx)
  69. n_embd = self.find_hparam(["hidden_size", "n_embd"])
  70. self.gguf_writer.add_embedding_length(n_embd)
  71. if (n_ff := self.find_hparam(["intermediate_size", "n_inner"], optional=True)) is not None:
  72. self.gguf_writer.add_feed_forward_length(n_ff)
  73. n_head = self.find_hparam(["num_attention_heads", "n_head"])
  74. self.gguf_writer.add_head_count(n_head)
  75. if (n_head_kv := self.hparams.get("num_key_value_heads")) is not None:
  76. self.gguf_writer.add_head_count_kv(n_head_kv)
  77. if (f_rms_eps := self.hparams.get("rms_norm_eps")) is not None:
  78. self.gguf_writer.add_layer_norm_rms_eps(f_rms_eps)
  79. if (f_norm_eps := self.find_hparam(["layer_norm_eps", "layer_norm_epsilon"], optional=True)) is not None:
  80. self.gguf_writer.add_layer_norm_eps(f_norm_eps)
  81. if (n_experts := self.hparams.get("num_local_experts")) is not None:
  82. self.gguf_writer.add_expert_count(n_experts)
  83. if (n_experts_used := self.hparams.get("num_experts_per_tok")) is not None:
  84. self.gguf_writer.add_expert_used_count(n_experts_used)
  85. self.gguf_writer.add_file_type(self.ftype)
  86. def write_tensors(self):
  87. block_count = self.hparams.get("n_layers", self.hparams.get("num_hidden_layers", self.hparams.get("n_layer")))
  88. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  89. for name, data_torch in self.get_tensors():
  90. # we don't need these
  91. if name.endswith((".attention.masked_bias", ".attention.bias", ".attention.rotary_emb.inv_freq")):
  92. continue
  93. old_dtype = data_torch.dtype
  94. # convert any unsupported data types to float32
  95. if data_torch.dtype not in (torch.float16, torch.float32):
  96. data_torch = data_torch.to(torch.float32)
  97. data = data_torch.squeeze().numpy()
  98. # map tensor names
  99. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  100. if new_name is None:
  101. print(f"Can not map tensor {name!r}")
  102. sys.exit()
  103. n_dims = len(data.shape)
  104. data_dtype = data.dtype
  105. # if f32 desired, convert any float16 to float32
  106. if self.ftype == 0 and data_dtype == np.float16:
  107. data = data.astype(np.float32)
  108. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  109. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  110. data = data.astype(np.float32)
  111. # if f16 desired, convert any float32 2-dim weight tensors to float16
  112. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  113. data = data.astype(np.float16)
  114. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  115. self.gguf_writer.add_tensor(new_name, data)
  116. def write(self):
  117. self.write_tensors()
  118. self.gguf_writer.write_header_to_file()
  119. self.gguf_writer.write_kv_data_to_file()
  120. self.gguf_writer.write_tensors_to_file()
  121. self.gguf_writer.close()
  122. def write_vocab(self):
  123. self.gguf_writer.write_header_to_file()
  124. self.gguf_writer.write_kv_data_to_file()
  125. self.gguf_writer.close()
  126. @staticmethod
  127. def count_model_parts(dir_model: Path, prefix: str) -> int:
  128. num_parts = 0
  129. for filename in os.listdir(dir_model):
  130. if filename.endswith(prefix):
  131. num_parts += 1
  132. return num_parts
  133. @staticmethod
  134. def load_hparams(dir_model):
  135. with open(dir_model / "config.json", "r", encoding="utf-8") as f:
  136. return json.load(f)
  137. @staticmethod
  138. def from_model_architecture(model_architecture):
  139. if model_architecture == "GPTNeoXForCausalLM":
  140. return GPTNeoXModel
  141. if model_architecture == "BloomForCausalLM":
  142. return BloomModel
  143. if model_architecture == "MPTForCausalLM":
  144. return MPTModel
  145. if model_architecture in ("BaichuanForCausalLM", "BaiChuanForCausalLM"):
  146. return BaichuanModel
  147. if model_architecture in ("FalconForCausalLM", "RWForCausalLM"):
  148. return FalconModel
  149. if model_architecture == "GPTBigCodeForCausalLM":
  150. return StarCoderModel
  151. if model_architecture == "GPTRefactForCausalLM":
  152. return RefactModel
  153. if model_architecture == "PersimmonForCausalLM":
  154. return PersimmonModel
  155. if model_architecture in ("StableLMEpochForCausalLM", "LlavaStableLMEpochForCausalLM"):
  156. return StableLMModel
  157. if model_architecture == "QWenLMHeadModel":
  158. return QwenModel
  159. if model_architecture == "Qwen2ForCausalLM":
  160. return Model
  161. if model_architecture == "MixtralForCausalLM":
  162. return MixtralModel
  163. if model_architecture == "GPT2LMHeadModel":
  164. return GPT2Model
  165. if model_architecture == "PhiForCausalLM":
  166. return Phi2Model
  167. if model_architecture == "PlamoForCausalLM":
  168. return PlamoModel
  169. if model_architecture == "CodeShellForCausalLM":
  170. return CodeShellModel
  171. if model_architecture == "OrionForCausalLM":
  172. return OrionModel
  173. if model_architecture == "InternLM2ForCausalLM":
  174. return InternLM2Model
  175. if model_architecture == "MiniCPMForCausalLM":
  176. return MiniCPMModel
  177. if model_architecture == "BertModel":
  178. return BertModel
  179. if model_architecture == "NomicBertModel":
  180. return NomicBertModel
  181. if model_architecture == "GemmaForCausalLM":
  182. return GemmaModel
  183. return Model
  184. def _is_model_safetensors(self) -> bool:
  185. return Model.count_model_parts(self.dir_model, ".safetensors") > 0
  186. def _get_part_names(self):
  187. if self.is_safetensors:
  188. if self.num_parts == 1: # there's only one .safetensors file
  189. return ("model.safetensors",)
  190. return (f"model-{n:05}-of-{self.num_parts:05}.safetensors" for n in range(1, self.num_parts + 1))
  191. if self.num_parts == 1: # there's only one .bin file
  192. return ("pytorch_model.bin",)
  193. return (f"pytorch_model-{n:05}-of-{self.num_parts:05}.bin" for n in range(1, self.num_parts + 1))
  194. def _get_model_architecture(self) -> gguf.MODEL_ARCH:
  195. arch = self.hparams["architectures"][0]
  196. if arch == "GPTNeoXForCausalLM":
  197. return gguf.MODEL_ARCH.GPTNEOX
  198. if arch == "BloomForCausalLM":
  199. return gguf.MODEL_ARCH.BLOOM
  200. if arch == "MPTForCausalLM":
  201. return gguf.MODEL_ARCH.MPT
  202. if arch in ("BaichuanForCausalLM", "BaiChuanForCausalLM"):
  203. return gguf.MODEL_ARCH.BAICHUAN
  204. if arch in ("FalconForCausalLM", "RWForCausalLM"):
  205. return gguf.MODEL_ARCH.FALCON
  206. if arch == "GPTBigCodeForCausalLM":
  207. return gguf.MODEL_ARCH.STARCODER
  208. if arch == "GPTRefactForCausalLM":
  209. return gguf.MODEL_ARCH.REFACT
  210. if arch == "PersimmonForCausalLM":
  211. return gguf.MODEL_ARCH.PERSIMMON
  212. if arch in ("StableLMEpochForCausalLM", "LlavaStableLMEpochForCausalLM"):
  213. return gguf.MODEL_ARCH.STABLELM
  214. if arch == "QWenLMHeadModel":
  215. return gguf.MODEL_ARCH.QWEN
  216. if arch == "Qwen2ForCausalLM":
  217. return gguf.MODEL_ARCH.QWEN2
  218. if arch == "MixtralForCausalLM":
  219. return gguf.MODEL_ARCH.LLAMA
  220. if arch == "GPT2LMHeadModel":
  221. return gguf.MODEL_ARCH.GPT2
  222. if arch == "PhiForCausalLM":
  223. return gguf.MODEL_ARCH.PHI2
  224. if arch == "PlamoForCausalLM":
  225. return gguf.MODEL_ARCH.PLAMO
  226. if arch == "CodeShellForCausalLM":
  227. return gguf.MODEL_ARCH.CODESHELL
  228. if arch == "OrionForCausalLM":
  229. return gguf.MODEL_ARCH.ORION
  230. if arch == "InternLM2ForCausalLM":
  231. return gguf.MODEL_ARCH.INTERNLM2
  232. if arch == "MiniCPMForCausalLM":
  233. return gguf.MODEL_ARCH.MINICPM
  234. if arch == "BertModel":
  235. return gguf.MODEL_ARCH.BERT
  236. if arch == "NomicBertModel":
  237. return gguf.MODEL_ARCH.NOMIC_BERT
  238. if arch == "GemmaForCausalLM":
  239. return gguf.MODEL_ARCH.GEMMA
  240. raise NotImplementedError(f'Architecture "{arch}" not supported!')
  241. def _set_vocab_gpt2(self):
  242. dir_model = self.dir_model
  243. hparams = self.hparams
  244. tokens: list[bytearray] = []
  245. toktypes: list[int] = []
  246. from transformers import AutoTokenizer
  247. tokenizer = AutoTokenizer.from_pretrained(dir_model)
  248. vocab_size = hparams.get("vocab_size", len(tokenizer.vocab))
  249. assert max(tokenizer.vocab.values()) < vocab_size
  250. reverse_vocab = {id_: encoded_tok for encoded_tok, id_ in tokenizer.vocab.items()}
  251. added_vocab = tokenizer.get_added_vocab()
  252. for i in range(vocab_size):
  253. if i not in reverse_vocab:
  254. pad_token = f"[PAD{i}]".encode('utf-8')
  255. tokens.append(bytearray(pad_token))
  256. toktypes.append(gguf.TokenType.USER_DEFINED)
  257. elif reverse_vocab[i] in added_vocab:
  258. tokens.append(reverse_vocab[i])
  259. if tokenizer.added_tokens_decoder[i].special:
  260. toktypes.append(gguf.TokenType.CONTROL)
  261. else:
  262. toktypes.append(gguf.TokenType.USER_DEFINED)
  263. else:
  264. tokens.append(reverse_vocab[i])
  265. toktypes.append(gguf.TokenType.NORMAL)
  266. self.gguf_writer.add_tokenizer_model("gpt2")
  267. self.gguf_writer.add_token_list(tokens)
  268. self.gguf_writer.add_token_types(toktypes)
  269. special_vocab = gguf.SpecialVocab(dir_model, load_merges=True)
  270. special_vocab.add_to_gguf(self.gguf_writer)
  271. def _set_vocab_qwen(self):
  272. dir_model = self.dir_model
  273. hparams = self.hparams
  274. tokens: list[bytearray] = []
  275. toktypes: list[int] = []
  276. from transformers import AutoTokenizer
  277. tokenizer = AutoTokenizer.from_pretrained(dir_model, trust_remote_code=True)
  278. vocab_size = hparams["vocab_size"]
  279. assert max(tokenizer.get_vocab().values()) < vocab_size
  280. merges = []
  281. vocab = {}
  282. mergeable_ranks = tokenizer.mergeable_ranks
  283. for token, rank in mergeable_ranks.items():
  284. vocab[QwenModel.token_bytes_to_string(token)] = rank
  285. if len(token) == 1:
  286. continue
  287. merged = QwenModel.bpe(mergeable_ranks, token, max_rank=rank)
  288. assert len(merged) == 2
  289. merges.append(' '.join(map(QwenModel.token_bytes_to_string, merged)))
  290. # for this kind of tokenizer, added_vocab is not a subset of vocab, so they need to be combined
  291. added_vocab = tokenizer.special_tokens
  292. reverse_vocab = {id_ : encoded_tok for encoded_tok, id_ in (vocab | added_vocab).items()}
  293. for i in range(vocab_size):
  294. if i not in reverse_vocab:
  295. pad_token = f"[PAD{i}]".encode("utf-8")
  296. tokens.append(bytearray(pad_token))
  297. toktypes.append(gguf.TokenType.USER_DEFINED)
  298. elif reverse_vocab[i] in added_vocab:
  299. tokens.append(reverse_vocab[i])
  300. toktypes.append(gguf.TokenType.CONTROL)
  301. else:
  302. tokens.append(reverse_vocab[i])
  303. toktypes.append(gguf.TokenType.NORMAL)
  304. self.gguf_writer.add_tokenizer_model("gpt2")
  305. self.gguf_writer.add_token_list(tokens)
  306. self.gguf_writer.add_token_types(toktypes)
  307. special_vocab = gguf.SpecialVocab(dir_model, load_merges=False)
  308. special_vocab.merges = merges
  309. # only add special tokens when they were not already loaded from config.json
  310. if len(special_vocab.special_token_ids) == 0:
  311. special_vocab._set_special_token("bos", tokenizer.special_tokens["<|endoftext|>"])
  312. special_vocab._set_special_token("eos", tokenizer.special_tokens["<|endoftext|>"])
  313. # this one is usually not in config.json anyway
  314. special_vocab._set_special_token("unk", tokenizer.special_tokens["<|endoftext|>"])
  315. special_vocab.add_to_gguf(self.gguf_writer)
  316. def _set_vocab_sentencepiece(self):
  317. from sentencepiece import SentencePieceProcessor
  318. tokenizer_path = self.dir_model / 'tokenizer.model'
  319. tokens: list[bytes] = []
  320. scores: list[float] = []
  321. toktypes: list[int] = []
  322. if not tokenizer_path.is_file():
  323. print(f'Error: Missing {tokenizer_path}', file=sys.stderr)
  324. sys.exit(1)
  325. tokenizer = SentencePieceProcessor(str(tokenizer_path))
  326. vocab_size = self.hparams.get('vocab_size', tokenizer.vocab_size())
  327. for token_id in range(vocab_size):
  328. piece = tokenizer.id_to_piece(token_id)
  329. text = piece.encode("utf-8")
  330. score = tokenizer.get_score(token_id)
  331. toktype = SentencePieceTokenTypes.NORMAL
  332. if tokenizer.is_unknown(token_id):
  333. toktype = SentencePieceTokenTypes.UNKNOWN
  334. elif tokenizer.is_control(token_id):
  335. toktype = SentencePieceTokenTypes.CONTROL
  336. elif tokenizer.is_unused(token_id):
  337. toktype = SentencePieceTokenTypes.UNUSED
  338. elif tokenizer.is_byte(token_id):
  339. toktype = SentencePieceTokenTypes.BYTE
  340. tokens.append(text)
  341. scores.append(score)
  342. toktypes.append(toktype)
  343. added_tokens_file = self.dir_model / 'added_tokens.json'
  344. if added_tokens_file.is_file():
  345. with open(added_tokens_file, "r", encoding="utf-8") as f:
  346. added_tokens_json = json.load(f)
  347. for key in added_tokens_json:
  348. tokens.append(key.encode("utf-8"))
  349. scores.append(-1000.0)
  350. toktypes.append(SentencePieceTokenTypes.USER_DEFINED)
  351. self.gguf_writer.add_tokenizer_model("llama")
  352. self.gguf_writer.add_token_list(tokens)
  353. self.gguf_writer.add_token_scores(scores)
  354. self.gguf_writer.add_token_types(toktypes)
  355. special_vocab = gguf.SpecialVocab(self.dir_model, n_vocab=len(tokens))
  356. special_vocab.add_to_gguf(self.gguf_writer)
  357. def _set_vocab_hf(self):
  358. path = self.dir_model
  359. added_tokens_path = self.dir_model
  360. vocab = HfVocab(
  361. path, added_tokens_path if added_tokens_path.exists() else None
  362. )
  363. tokens = []
  364. scores = []
  365. toktypes = []
  366. for text, score, toktype in vocab.all_tokens():
  367. tokens.append(text)
  368. scores.append(score)
  369. toktypes.append(toktype)
  370. assert len(tokens) == vocab.vocab_size
  371. self.gguf_writer.add_tokenizer_model("llama")
  372. self.gguf_writer.add_token_list(tokens)
  373. self.gguf_writer.add_token_scores(scores)
  374. self.gguf_writer.add_token_types(toktypes)
  375. special_vocab = gguf.SpecialVocab(self.dir_model, n_vocab=len(tokens))
  376. special_vocab.add_to_gguf(self.gguf_writer)
  377. class GPTNeoXModel(Model):
  378. def set_gguf_parameters(self):
  379. block_count = self.hparams["num_hidden_layers"]
  380. self.gguf_writer.add_name(self.dir_model.name)
  381. self.gguf_writer.add_context_length(self.hparams["max_position_embeddings"])
  382. self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
  383. self.gguf_writer.add_block_count(block_count)
  384. self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
  385. self.gguf_writer.add_rope_dimension_count(
  386. int(self.hparams["rotary_pct"] * (self.hparams["hidden_size"] // self.hparams["num_attention_heads"])),
  387. )
  388. self.gguf_writer.add_head_count(self.hparams["num_attention_heads"])
  389. self.gguf_writer.add_parallel_residual(self.hparams.get("use_parallel_residual", True))
  390. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_eps"])
  391. class BloomModel(Model):
  392. def set_gguf_parameters(self):
  393. self.gguf_writer.add_name("Bloom")
  394. n_embed = self.hparams.get("hidden_size", self.hparams.get("n_embed"))
  395. n_head = self.hparams.get("n_head", self.hparams.get("num_attention_heads"))
  396. self.gguf_writer.add_context_length(self.hparams.get("seq_length", n_embed))
  397. self.gguf_writer.add_embedding_length(n_embed)
  398. self.gguf_writer.add_feed_forward_length(4 * n_embed)
  399. self.gguf_writer.add_block_count(self.hparams["n_layer"])
  400. self.gguf_writer.add_head_count(n_head)
  401. self.gguf_writer.add_head_count_kv(n_head)
  402. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
  403. self.gguf_writer.add_file_type(self.ftype)
  404. def write_tensors(self):
  405. block_count = self.hparams["n_layer"]
  406. tensors = dict(self.get_tensors())
  407. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  408. has_lm_head = True
  409. n_head = self.hparams.get("n_head", self.hparams.get("num_attention_heads"))
  410. n_embed = self.hparams.get("hidden_size", self.hparams.get("n_embed"))
  411. for name, data_torch in tensors.items():
  412. if "lm_head.weight" not in tensors.keys() and "output.weight" not in tensors.keys():
  413. has_lm_head = False
  414. name = re.sub(r'transformer\.', '', name)
  415. old_dtype = data_torch.dtype
  416. # convert any unsupported data types to float32
  417. if data_torch.dtype not in (torch.float16, torch.float32):
  418. data_torch = data_torch.to(torch.float32)
  419. data = data_torch.squeeze().numpy()
  420. if re.match(r"h\.\d+\.self_attention\.query_key_value\.weight", name):
  421. # Map bloom-style qkv_linear to gpt-style qkv_linear
  422. # bloom: https://github.com/huggingface/transformers/blob/main/src/transformers/models/bloom/modeling_bloom.py#L238-L252 # noqa
  423. # gpt-2: https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py#L312 # noqa
  424. qkv_weights = data.reshape((n_head, 3, n_embed // n_head, n_embed))
  425. data = np.concatenate(
  426. (
  427. qkv_weights[:, 0, :, :].reshape((-1, n_embed)),
  428. qkv_weights[:, 1, :, :].reshape((-1, n_embed)),
  429. qkv_weights[:, 2, :, :].reshape((-1, n_embed)),
  430. ),
  431. axis=0,
  432. )
  433. print("re-format attention.linear_qkv.weight")
  434. elif re.match(r"h\.\d+\.self_attention\.query_key_value\.bias", name):
  435. qkv_bias = data.reshape((n_head, 3, n_embed // n_head))
  436. data = np.concatenate(
  437. (
  438. qkv_bias[:, 0, :].reshape((n_embed,)),
  439. qkv_bias[:, 1, :].reshape((n_embed,)),
  440. qkv_bias[:, 2, :].reshape((n_embed,)),
  441. ),
  442. axis=0,
  443. )
  444. print("re-format attention.linear_qkv.bias")
  445. # map tensor names
  446. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  447. if new_name is None:
  448. print(f"Can not map tensor {name!r}")
  449. sys.exit()
  450. n_dims = len(data.shape)
  451. data_dtype = data.dtype
  452. # if f32 desired, convert any float16 to float32
  453. if self.ftype == 0 and data_dtype == np.float16:
  454. data = data.astype(np.float32)
  455. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  456. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  457. data = data.astype(np.float32)
  458. # if f16 desired, convert any float32 2-dim weight tensors to float16
  459. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  460. data = data.astype(np.float16)
  461. print(f"=> {new_name}, shape = {data.shape}, {old_dtype} --> {data.dtype}")
  462. self.gguf_writer.add_tensor(new_name, data)
  463. if not has_lm_head and name == "word_embeddings.weight":
  464. self.gguf_writer.add_tensor("output.weight", data)
  465. print(name, f"=> output.weight, shape = {data.shape}, {old_dtype} --> {data.dtype}")
  466. class MPTModel(Model):
  467. def set_gguf_parameters(self):
  468. block_count = self.hparams["n_layers"]
  469. self.gguf_writer.add_name(self.dir_model.name)
  470. self.gguf_writer.add_context_length(self.hparams["max_seq_len"])
  471. self.gguf_writer.add_embedding_length(self.hparams["d_model"])
  472. self.gguf_writer.add_block_count(block_count)
  473. self.gguf_writer.add_feed_forward_length(4 * self.hparams["d_model"])
  474. self.gguf_writer.add_head_count(self.hparams["n_heads"])
  475. if kv_n_heads := self.hparams["attn_config"].get("kv_n_heads"):
  476. self.gguf_writer.add_head_count_kv(kv_n_heads)
  477. self.gguf_writer.add_layer_norm_eps(1e-5)
  478. if self.hparams["attn_config"]["clip_qkv"] is not None:
  479. self.gguf_writer.add_clamp_kqv(self.hparams["attn_config"]["clip_qkv"])
  480. self.gguf_writer.add_max_alibi_bias(self.hparams["attn_config"]["alibi_bias_max"])
  481. def write_tensors(self):
  482. block_count = self.hparams.get("n_layers", self.hparams.get("num_hidden_layers"))
  483. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  484. for name, data_torch in self.get_tensors():
  485. # we don't need these
  486. if name.endswith((".attention.masked_bias", ".attention.bias", ".attention.rotary_emb.inv_freq")):
  487. continue
  488. old_dtype = data_torch.dtype
  489. # convert any unsupported data types to float32
  490. if data_torch.dtype not in (torch.float16, torch.float32):
  491. data_torch = data_torch.to(torch.float32)
  492. data = data_torch.squeeze().numpy()
  493. # map tensor names
  494. if "scales" in name:
  495. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias", ".scales"))
  496. if new_name is not None:
  497. new_name = new_name.replace("scales", "act.scales")
  498. else:
  499. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  500. if new_name is None:
  501. print(f"Can not map tensor {name!r}")
  502. sys.exit()
  503. n_dims = len(data.shape)
  504. data_dtype = data.dtype
  505. # if f32 desired, convert any float16 to float32
  506. if self.ftype == 0 and data_dtype == np.float16:
  507. data = data.astype(np.float32)
  508. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  509. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  510. data = data.astype(np.float32)
  511. # if f16 desired, convert any float32 2-dim weight tensors to float16
  512. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  513. data = data.astype(np.float16)
  514. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  515. self.gguf_writer.add_tensor(new_name, data)
  516. # note: MPT output is tied to (same as) wte in original model;
  517. # for easier implementation in llama.cpp it's duplicated in GGUF, though :/
  518. if new_name == "token_embd.weight":
  519. self.gguf_writer.add_tensor("output.weight", data)
  520. class OrionModel(Model):
  521. def set_vocab(self):
  522. self._set_vocab_sentencepiece()
  523. def set_gguf_parameters(self):
  524. block_count = self.hparams["num_hidden_layers"]
  525. head_count = self.hparams["num_attention_heads"]
  526. head_count_kv = self.hparams.get("num_key_value_heads", head_count)
  527. hf_repo = self.hparams.get("_name_or_path", "")
  528. ctx_length = 0
  529. if "max_sequence_length" in self.hparams:
  530. ctx_length = self.hparams["max_sequence_length"]
  531. elif "max_position_embeddings" in self.hparams:
  532. ctx_length = self.hparams["max_position_embeddings"]
  533. elif "model_max_length" in self.hparams:
  534. ctx_length = self.hparams["model_max_length"]
  535. else:
  536. print("gguf: can not find ctx length parameter.")
  537. sys.exit()
  538. self.gguf_writer.add_file_type(self.ftype)
  539. self.gguf_writer.add_name(self.dir_model.name)
  540. self.gguf_writer.add_source_hf_repo(hf_repo)
  541. self.gguf_writer.add_tensor_data_layout("Meta AI original pth")
  542. self.gguf_writer.add_context_length(ctx_length)
  543. self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
  544. self.gguf_writer.add_block_count(block_count)
  545. self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
  546. self.gguf_writer.add_head_count(head_count)
  547. self.gguf_writer.add_head_count_kv(head_count_kv)
  548. # note: config provides rms norm but it is actually layer norm
  549. # ref: https://huggingface.co/OrionStarAI/Orion-14B-Chat/blob/276a17221ce42beb45f66fac657a41540e71f4f5/modeling_orion.py#L570-L571
  550. self.gguf_writer.add_layer_norm_eps(self.hparams["rms_norm_eps"])
  551. def write_tensors(self):
  552. # Collect tensors from generator object
  553. model_kv = dict(self.get_tensors())
  554. block_count = self.hparams["num_hidden_layers"]
  555. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  556. for name, data_torch in model_kv.items():
  557. # we don't need these
  558. if name.endswith(".rotary_emb.inv_freq"):
  559. continue
  560. old_dtype = data_torch.dtype
  561. # convert any unsupported data types to float32
  562. if data_torch.dtype not in (torch.float16, torch.float32):
  563. data_torch = data_torch.to(torch.float32)
  564. data = data_torch.squeeze().numpy()
  565. # map tensor names
  566. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  567. if new_name is None:
  568. print(f"Can not map tensor {name!r}")
  569. sys.exit()
  570. n_dims = len(data.shape)
  571. data_dtype = data.dtype
  572. # if f32 desired, convert any float16 to float32
  573. if self.ftype == 0 and data_dtype == np.float16:
  574. data = data.astype(np.float32)
  575. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  576. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  577. data = data.astype(np.float32)
  578. # if f16 desired, convert any float32 2-dim weight tensors to float16
  579. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  580. data = data.astype(np.float16)
  581. print(f"{name} -> {new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  582. self.gguf_writer.add_tensor(new_name, data)
  583. class BaichuanModel(Model):
  584. def set_vocab(self):
  585. self._set_vocab_sentencepiece()
  586. def set_gguf_parameters(self):
  587. block_count = self.hparams["num_hidden_layers"]
  588. head_count = self.hparams["num_attention_heads"]
  589. head_count_kv = self.hparams.get("num_key_value_heads", head_count)
  590. hf_repo = self.hparams.get("_name_or_path", "")
  591. ctx_length = 0
  592. if "max_sequence_length" in self.hparams:
  593. ctx_length = self.hparams["max_sequence_length"]
  594. elif "max_position_embeddings" in self.hparams:
  595. ctx_length = self.hparams["max_position_embeddings"]
  596. elif "model_max_length" in self.hparams:
  597. ctx_length = self.hparams["model_max_length"]
  598. else:
  599. print("gguf: can not find ctx length parameter.")
  600. sys.exit()
  601. self.gguf_writer.add_name(self.dir_model.name)
  602. self.gguf_writer.add_source_hf_repo(hf_repo)
  603. self.gguf_writer.add_tensor_data_layout("Meta AI original pth")
  604. self.gguf_writer.add_context_length(ctx_length)
  605. self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
  606. self.gguf_writer.add_block_count(block_count)
  607. self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
  608. self.gguf_writer.add_rope_dimension_count(self.hparams["hidden_size"] // self.hparams["num_attention_heads"])
  609. self.gguf_writer.add_head_count(head_count)
  610. self.gguf_writer.add_head_count_kv(head_count_kv)
  611. self.gguf_writer.add_layer_norm_rms_eps(self.hparams["rms_norm_eps"])
  612. if self.hparams.get("rope_scaling") is not None and "factor" in self.hparams["rope_scaling"]:
  613. if self.hparams["rope_scaling"].get("type") == "linear":
  614. self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.LINEAR)
  615. self.gguf_writer.add_rope_scaling_factor(self.hparams["rope_scaling"]["factor"])
  616. def write_tensors(self):
  617. # Collect tensors from generator object
  618. model_kv = dict(self.get_tensors())
  619. block_count = self.hparams["num_hidden_layers"]
  620. head_count = self.hparams["num_attention_heads"]
  621. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  622. head_count_kv = self.hparams.get("num_key_value_heads", head_count)
  623. for i in range(block_count):
  624. if (w := model_kv.get(f"model.layers.{i}.self_attn.W_pack.weight")) is not None:
  625. print(f"Unpacking and permuting layer {i}")
  626. model_kv[f"model.layers.{i}.self_attn.q_proj.weight"] = \
  627. self._reverse_hf_permute_part(w, 0, head_count, head_count)
  628. model_kv[f"model.layers.{i}.self_attn.k_proj.weight"] = \
  629. self._reverse_hf_permute_part(w, 1, head_count, head_count_kv)
  630. model_kv[f"model.layers.{i}.self_attn.v_proj.weight"] = \
  631. self._reverse_hf_part(w, 2)
  632. del model_kv[f"model.layers.{i}.self_attn.W_pack.weight"]
  633. for name, data_torch in model_kv.items():
  634. # we don't need these
  635. if name.endswith(".rotary_emb.inv_freq"):
  636. continue
  637. old_dtype = data_torch.dtype
  638. # convert any unsupported data types to float32
  639. if data_torch.dtype not in (torch.float16, torch.float32):
  640. data_torch = data_torch.to(torch.float32)
  641. data = data_torch.squeeze().numpy()
  642. # map tensor names
  643. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  644. if new_name is None:
  645. print(f"Can not map tensor {name!r}")
  646. sys.exit()
  647. n_dims = len(data.shape)
  648. data_dtype = data.dtype
  649. # if f32 desired, convert any float16 to float32
  650. if self.ftype == 0 and data_dtype == np.float16:
  651. data = data.astype(np.float32)
  652. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  653. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  654. data = data.astype(np.float32)
  655. # if f16 desired, convert any float32 2-dim weight tensors to float16
  656. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  657. data = data.astype(np.float16)
  658. print(f"{name} -> {new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  659. self.gguf_writer.add_tensor(new_name, data)
  660. def _reverse_hf_permute(self, weights: Tensor, n_head: int, n_kv_head: int | None = None) -> Tensor:
  661. if n_kv_head is not None and n_head != n_kv_head:
  662. n_head //= n_kv_head
  663. return (
  664. weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  665. .swapaxes(1, 2)
  666. .reshape(weights.shape)
  667. )
  668. def _reverse_hf_permute_part(
  669. self, weights: Tensor, n_part: int, n_head: int, n_head_kv: int | None = None,
  670. ) -> Tensor:
  671. r = weights.shape[0] // 3
  672. return self._reverse_hf_permute(weights[r * n_part:r * n_part + r, ...], n_head, n_head_kv)
  673. def _reverse_hf_part(self, weights: Tensor, n_part: int) -> Tensor:
  674. r = weights.shape[0] // 3
  675. return weights[r * n_part:r * n_part + r, ...]
  676. class FalconModel(Model):
  677. def set_gguf_parameters(self):
  678. block_count = self.hparams.get("num_hidden_layers")
  679. if block_count is None:
  680. block_count = self.hparams["n_layer"] # old name
  681. n_head = self.hparams.get("num_attention_heads")
  682. if n_head is None:
  683. n_head = self.hparams["n_head"] # old name
  684. n_head_kv = self.hparams.get("num_kv_heads")
  685. if n_head_kv is None:
  686. n_head_kv = self.hparams.get("n_head_kv", 1) # old name
  687. self.gguf_writer.add_name("Falcon")
  688. self.gguf_writer.add_context_length(2048) # not in config.json
  689. self.gguf_writer.add_tensor_data_layout("jploski") # qkv tensor transform
  690. self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
  691. self.gguf_writer.add_feed_forward_length(4 * self.hparams["hidden_size"])
  692. self.gguf_writer.add_block_count(block_count)
  693. self.gguf_writer.add_head_count(n_head)
  694. self.gguf_writer.add_head_count_kv(n_head_kv)
  695. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
  696. self.gguf_writer.add_file_type(self.ftype)
  697. def write_tensors(self):
  698. block_count = self.hparams.get("num_hidden_layers")
  699. if block_count is None:
  700. block_count = self.hparams["n_layer"] # old name
  701. n_head = self.hparams.get("num_attention_heads")
  702. if n_head is None:
  703. n_head = self.hparams["n_head"] # old name
  704. n_head_kv = self.hparams.get("num_kv_heads")
  705. if n_head_kv is None:
  706. n_head_kv = self.hparams.get("n_head_kv", 1) # old name
  707. head_dim = self.hparams["hidden_size"] // n_head
  708. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  709. for name, data_torch in self.get_tensors():
  710. old_dtype = data_torch.dtype
  711. # convert any unsupported data types to float32
  712. if data_torch.dtype not in (torch.float16, torch.float32):
  713. data_torch = data_torch.to(torch.float32)
  714. # QKV tensor transform
  715. # The original query_key_value tensor contains n_head_kv "kv groups",
  716. # each consisting of n_head/n_head_kv query weights followed by one key
  717. # and one value weight (shared by all query heads in the kv group).
  718. # This layout makes it a big pain to work with in GGML.
  719. # So we rearrange them here,, so that we have n_head query weights
  720. # followed by n_head_kv key weights followed by n_head_kv value weights,
  721. # in contiguous fashion.
  722. # ref: https://github.com/jploski/ggml/blob/falcon40b/examples/falcon/convert-hf-to-ggml.py
  723. if "query_key_value" in name:
  724. qkv = data_torch.view(n_head_kv, n_head // n_head_kv + 2, head_dim, head_dim * n_head)
  725. q = qkv[:, :-2].reshape(n_head * head_dim, head_dim * n_head)
  726. k = qkv[:, [-2]].reshape(n_head_kv * head_dim, head_dim * n_head)
  727. v = qkv[:, [-1]].reshape(n_head_kv * head_dim, head_dim * n_head)
  728. data_torch = torch.cat((q, k, v)).reshape_as(data_torch)
  729. data = data_torch.squeeze().numpy()
  730. # map tensor names
  731. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  732. if new_name is None:
  733. print(f"Can not map tensor {name!r}")
  734. sys.exit()
  735. n_dims = len(data.shape)
  736. data_dtype = data.dtype
  737. # if f32 desired, convert any float16 to float32
  738. if self.ftype == 0 and data_dtype == np.float16:
  739. data = data.astype(np.float32)
  740. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  741. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  742. data = data.astype(np.float32)
  743. # if f16 desired, convert any float32 2-dim weight tensors to float16
  744. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  745. data = data.astype(np.float16)
  746. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  747. self.gguf_writer.add_tensor(new_name, data)
  748. class StarCoderModel(Model):
  749. def set_gguf_parameters(self):
  750. block_count = self.hparams["n_layer"]
  751. self.gguf_writer.add_name("StarCoder")
  752. self.gguf_writer.add_context_length(self.hparams["n_positions"])
  753. self.gguf_writer.add_embedding_length(self.hparams["n_embd"])
  754. self.gguf_writer.add_feed_forward_length(4 * self.hparams["n_embd"])
  755. self.gguf_writer.add_block_count(block_count)
  756. self.gguf_writer.add_head_count(self.hparams["n_head"])
  757. self.gguf_writer.add_head_count_kv(1)
  758. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
  759. self.gguf_writer.add_file_type(self.ftype)
  760. class RefactModel(Model):
  761. def set_gguf_parameters(self):
  762. hidden_dim = self.hparams["n_embd"]
  763. inner_dim = 4 * hidden_dim
  764. hidden_dim = int(2 * inner_dim / 3)
  765. multiple_of = 256
  766. ff_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
  767. block_count = self.hparams["n_layer"]
  768. self.gguf_writer.add_name("Refact")
  769. # refact uses Alibi. So this is from config.json which might be used by training.
  770. self.gguf_writer.add_context_length(self.hparams["n_positions"])
  771. self.gguf_writer.add_embedding_length(self.hparams["n_embd"])
  772. self.gguf_writer.add_feed_forward_length(ff_dim)
  773. self.gguf_writer.add_block_count(block_count)
  774. self.gguf_writer.add_head_count(self.hparams["n_head"])
  775. self.gguf_writer.add_head_count_kv(1)
  776. self.gguf_writer.add_layer_norm_rms_eps(self.hparams["layer_norm_epsilon"])
  777. self.gguf_writer.add_file_type(self.ftype)
  778. def write_tensors(self):
  779. hidden_dim = self.hparams["n_embd"]
  780. inner_dim = 4 * hidden_dim
  781. hidden_dim = int(2 * inner_dim / 3)
  782. multiple_of = 256
  783. ff_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
  784. n_head = self.hparams["n_head"]
  785. n_head_kv = 1
  786. head_dim = self.hparams["n_embd"] // n_head
  787. block_count = self.hparams["n_layer"]
  788. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  789. tensors = dict(self.get_tensors())
  790. for i in range(block_count):
  791. if (w := tensors.get(f"transformer.h.{i}.attn.kv.weight")) is not None:
  792. tensors[f"model.layers.{i}.self_attn.k_proj.weight"] = w[:n_head_kv * head_dim]
  793. tensors[f"model.layers.{i}.self_attn.v_proj.weight"] = w[n_head_kv * head_dim:]
  794. del tensors[f"transformer.h.{i}.attn.kv.weight"]
  795. if (w := tensors.get(f"transformer.h.{i}.attn.q.weight")) is not None:
  796. tensors[f"model.layers.{i}.self_attn.q_proj.weight"] = w
  797. del tensors[f"transformer.h.{i}.attn.q.weight"]
  798. if (w := tensors.get(f"transformer.h.{i}.mlp.gate_up_proj.weight")) is not None:
  799. tensors[f"model.layers.{i}.mlp.gate_proj.weight"] = w[:ff_dim]
  800. tensors[f"model.layers.{i}.mlp.up_proj.weight"] = w[ff_dim:]
  801. del tensors[f"transformer.h.{i}.mlp.gate_up_proj.weight"]
  802. for name, data_torch in tensors.items():
  803. old_dtype = data_torch.dtype
  804. # convert any unsupported data types to float32
  805. if data_torch.dtype not in (torch.float16, torch.float32):
  806. data_torch = data_torch.to(torch.float32)
  807. data = data_torch.squeeze().numpy()
  808. # map tensor names
  809. new_name = tensor_map.get_name(name, try_suffixes=(".weight",))
  810. if new_name is None:
  811. print(f"Can not map tensor {name!r}")
  812. sys.exit()
  813. n_dims = len(data.shape)
  814. data_dtype = data.dtype
  815. # if f32 desired, convert any float16 to float32
  816. if self.ftype == 0 and data_dtype == np.float16:
  817. data = data.astype(np.float32)
  818. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  819. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  820. data = data.astype(np.float32)
  821. # if f16 desired, convert any float32 2-dim weight tensors to float16
  822. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  823. data = data.astype(np.float16)
  824. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  825. self.gguf_writer.add_tensor(new_name, data)
  826. class PersimmonModel(Model):
  827. def set_gguf_parameters(self):
  828. block_count = self.hparams.get("num_layers", self.hparams.get("num_hidden_layers"))
  829. head_count = self.hparams["num_attention_heads"]
  830. head_count_kv = head_count
  831. hidden_size = self.hparams["hidden_size"]
  832. self.gguf_writer.add_name('persimmon-8b-chat')
  833. self.gguf_writer.add_context_length(self.hparams["max_position_embeddings"])
  834. self.gguf_writer.add_embedding_length(hidden_size)
  835. self.gguf_writer.add_block_count(block_count)
  836. self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
  837. # NOTE: not sure about this change - why does the model not have a rope dimension count when it is smaller
  838. # than the head size?
  839. # ref: https://github.com/ggerganov/llama.cpp/pull/4889
  840. # self.gguf_writer.add_rope_dimension_count(hidden_size // head_count)
  841. self.gguf_writer.add_rope_dimension_count(hidden_size // head_count // 2)
  842. self.gguf_writer.add_head_count(head_count)
  843. self.gguf_writer.add_head_count_kv(head_count_kv)
  844. self.gguf_writer.add_rope_freq_base(self.hparams["rope_theta"])
  845. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_eps"])
  846. def set_vocab(self):
  847. self._set_vocab_sentencepiece()
  848. # self.gguf_writer.add_bos_token_id(71013)
  849. # self.gguf_writer.add_eos_token_id(71013)
  850. def write_tensors(self):
  851. block_count = self.hparams.get("num_layers", self.hparams.get("num_hidden_layers"))
  852. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  853. for name, data_torch in self.get_tensors():
  854. if name.endswith(".self_attention.rotary_emb.inv_freq"):
  855. continue
  856. old_dtype = data_torch.dtype
  857. # TODO: FP16 conversion produces garbage outputs. (Q8_0 does not, so..?)
  858. data = data_torch.to(torch.float32).squeeze().numpy()
  859. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  860. if new_name is None:
  861. print(f"Can not map tensor {name!r}")
  862. sys.exit()
  863. n_dims = len(data.shape)
  864. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  865. self.gguf_writer.add_tensor(new_name, data)
  866. class StableLMModel(Model):
  867. def set_vocab(self):
  868. if (self.dir_model / "tokenizer.json").is_file():
  869. self._set_vocab_gpt2()
  870. else:
  871. # StableLM 2 1.6B uses a vocab in a similar format to Qwen's vocab
  872. self._set_vocab_qwen()
  873. def set_gguf_parameters(self):
  874. hparams = self.hparams
  875. block_count = hparams["num_hidden_layers"]
  876. self.gguf_writer.add_name(self.dir_model.name)
  877. self.gguf_writer.add_context_length(hparams["max_position_embeddings"])
  878. self.gguf_writer.add_embedding_length(hparams["hidden_size"])
  879. self.gguf_writer.add_block_count(block_count)
  880. self.gguf_writer.add_feed_forward_length(hparams["intermediate_size"])
  881. self.gguf_writer.add_rope_dimension_count(int(hparams["rope_pct"] * (hparams["hidden_size"] // hparams["num_attention_heads"])))
  882. self.gguf_writer.add_head_count(hparams["num_attention_heads"])
  883. self.gguf_writer.add_parallel_residual(hparams["use_parallel_residual"] if "use_parallel_residual" in hparams else True)
  884. self.gguf_writer.add_layer_norm_eps(1e-5)
  885. class MixtralModel(Model):
  886. def set_vocab(self):
  887. self._set_vocab_sentencepiece()
  888. class MiniCPMModel(Model):
  889. def set_gguf_parameters(self):
  890. block_count = self.hparams["num_hidden_layers"]
  891. self.gguf_writer.add_name("MiniCPM")
  892. self.gguf_writer.add_context_length(self.hparams["max_position_embeddings"])
  893. self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
  894. self.gguf_writer.add_block_count(block_count)
  895. self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
  896. self.gguf_writer.add_rope_dimension_count(self.hparams["hidden_size"] // self.hparams["num_attention_heads"])
  897. self.gguf_writer.add_head_count(self.hparams["num_attention_heads"])
  898. self.gguf_writer.add_head_count_kv(self.hparams["num_key_value_heads"])
  899. self.gguf_writer.add_layer_norm_rms_eps(self.hparams["rms_norm_eps"])
  900. self.gguf_writer.add_file_type(self.ftype)
  901. def set_vocab(self):
  902. self._set_vocab_hf()
  903. def _reverse_hf_permute(self, weights: Tensor, n_head: int, n_kv_head: int | None = None) -> Tensor:
  904. if n_kv_head is not None and n_head != n_kv_head:
  905. n_head //= n_kv_head
  906. return (
  907. weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  908. .swapaxes(1, 2)
  909. .reshape(weights.shape)
  910. )
  911. def write_tensors(self):
  912. block_count = self.hparams.get("n_layers", self.hparams.get("num_hidden_layers", self.hparams.get("n_layer")))
  913. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  914. n_head = self.hparams.get("num_attention_heads")
  915. n_kv_head = self.hparams.get("num_key_value_heads")
  916. for name, data_torch in self.get_tensors():
  917. # we don't need these
  918. if name.endswith((".attention.masked_bias", ".attention.bias", ".attention.rotary_emb.inv_freq")):
  919. continue
  920. old_dtype = data_torch.dtype
  921. # convert any unsupported data types to float32
  922. if data_torch.dtype not in (torch.float16, torch.float32):
  923. data_torch = data_torch.to(torch.float32)
  924. # HF models permute some of the tensors, so we need to undo that
  925. if name.endswith(("q_proj.weight")):
  926. data_torch = self._reverse_hf_permute(data_torch, n_head, n_head)
  927. if name.endswith(("k_proj.weight")):
  928. data_torch = self._reverse_hf_permute(data_torch, n_head, n_kv_head)
  929. data = data_torch.squeeze().numpy()
  930. # map tensor names
  931. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  932. if new_name is None:
  933. print(f"Can not map tensor {name!r}")
  934. sys.exit()
  935. n_dims = len(data.shape)
  936. data_dtype = data.dtype
  937. # if f32 desired, convert any float16 to float32
  938. if self.ftype == 0 and data_dtype == np.float16:
  939. data = data.astype(np.float32)
  940. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  941. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  942. data = data.astype(np.float32)
  943. # if f16 desired, convert any float32 2-dim weight tensors to float16
  944. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  945. data = data.astype(np.float16)
  946. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  947. self.gguf_writer.add_tensor(new_name, data)
  948. class QwenModel(Model):
  949. @staticmethod
  950. def token_bytes_to_string(b):
  951. from transformers.models.gpt2.tokenization_gpt2 import bytes_to_unicode
  952. byte_encoder = bytes_to_unicode()
  953. return ''.join([byte_encoder[ord(char)] for char in b.decode('latin-1')])
  954. @staticmethod
  955. def bpe(mergeable_ranks: dict[bytes, int], token: bytes, max_rank: int | None = None) -> list[bytes]:
  956. parts = [bytes([b]) for b in token]
  957. while True:
  958. min_idx = None
  959. min_rank = None
  960. for i, pair in enumerate(zip(parts[:-1], parts[1:])):
  961. rank = mergeable_ranks.get(pair[0] + pair[1])
  962. if rank is not None and (min_rank is None or rank < min_rank):
  963. min_idx = i
  964. min_rank = rank
  965. if min_rank is None or (max_rank is not None and min_rank >= max_rank):
  966. break
  967. assert min_idx is not None
  968. parts = parts[:min_idx] + [parts[min_idx] + parts[min_idx + 1]] + parts[min_idx + 2:]
  969. return parts
  970. def set_vocab(self):
  971. self._set_vocab_qwen()
  972. def set_gguf_parameters(self):
  973. self.gguf_writer.add_name("Qwen")
  974. self.gguf_writer.add_context_length(self.hparams["max_position_embeddings"])
  975. self.gguf_writer.add_block_count(self.hparams["num_hidden_layers"])
  976. self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
  977. self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
  978. self.gguf_writer.add_rope_freq_base(self.hparams["rotary_emb_base"])
  979. self.gguf_writer.add_rope_dimension_count(self.hparams["hidden_size"] // self.hparams["num_attention_heads"])
  980. self.gguf_writer.add_head_count(self.hparams["num_attention_heads"])
  981. self.gguf_writer.add_layer_norm_rms_eps(self.hparams["layer_norm_epsilon"])
  982. def write_tensors(self):
  983. block_count = self.hparams["num_hidden_layers"]
  984. model_kv = dict(self.get_tensors())
  985. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  986. for name, data_torch in model_kv.items():
  987. # we don't need these
  988. if name.endswith(".rotary_emb.inv_freq"):
  989. continue
  990. old_dtype = data_torch.dtype
  991. # convert any unsupported data types to float32
  992. if data_torch.dtype not in (torch.float16, torch.float32):
  993. data_torch = data_torch.to(torch.float32)
  994. data = data_torch.squeeze().numpy()
  995. # map tensor names
  996. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  997. if new_name is None:
  998. print(f"Can not map tensor {name!r}")
  999. sys.exit()
  1000. n_dims = len(data.shape)
  1001. data_dtype = data.dtype
  1002. # if f32 desired, convert any float16 to float32
  1003. if self.ftype == 0 and data_dtype == np.float16:
  1004. data = data.astype(np.float32)
  1005. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  1006. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  1007. data = data.astype(np.float32)
  1008. # if f16 desired, convert any float32 2-dim weight tensors to float16
  1009. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  1010. data = data.astype(np.float16)
  1011. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  1012. self.gguf_writer.add_tensor(new_name, data)
  1013. class GPT2Model(Model):
  1014. def set_gguf_parameters(self):
  1015. self.gguf_writer.add_name(self.dir_model.name)
  1016. self.gguf_writer.add_block_count(self.hparams["n_layer"])
  1017. self.gguf_writer.add_context_length(self.hparams["n_ctx"])
  1018. self.gguf_writer.add_embedding_length(self.hparams["n_embd"])
  1019. self.gguf_writer.add_feed_forward_length(4 * self.hparams["n_embd"])
  1020. self.gguf_writer.add_head_count(self.hparams["n_head"])
  1021. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
  1022. self.gguf_writer.add_file_type(self.ftype)
  1023. def write_tensors(self):
  1024. block_count = self.hparams.get("n_layers", self.hparams.get("num_hidden_layers", self.hparams.get("n_layer")))
  1025. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  1026. for name, data_torch in self.get_tensors():
  1027. # we don't need these
  1028. if name.endswith((".attention.masked_bias", ".attention.bias", ".attention.rotary_emb.inv_freq", ".attn.bias", ".attn.masked_bias")):
  1029. continue
  1030. if name.endswith((".c_attn.weight", ".c_proj.weight", ".c_fc.weight", ".c_proj.weight")):
  1031. data_torch = data_torch.transpose(1, 0)
  1032. old_dtype = data_torch.dtype
  1033. # convert any unsupported data types to float32
  1034. if data_torch.dtype not in (torch.float16, torch.float32):
  1035. data_torch = data_torch.to(torch.float32)
  1036. data = data_torch.squeeze().numpy()
  1037. # map tensor names
  1038. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  1039. if new_name is None:
  1040. print(f"Can not map tensor {name!r}")
  1041. sys.exit()
  1042. n_dims = len(data.shape)
  1043. data_dtype = data.dtype
  1044. # if f32 desired, convert any float16 to float32
  1045. if self.ftype == 0 and data_dtype == np.float16:
  1046. data = data.astype(np.float32)
  1047. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  1048. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  1049. data = data.astype(np.float32)
  1050. # if f16 desired, convert any float32 2-dim weight tensors to float16
  1051. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  1052. data = data.astype(np.float16)
  1053. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  1054. self.gguf_writer.add_tensor(new_name, data)
  1055. # note: GPT2 output is tied to (same as) wte in original model
  1056. if new_name == "token_embd.weight":
  1057. print(f"output.weight, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  1058. self.gguf_writer.add_tensor("output.weight", data)
  1059. class Phi2Model(Model):
  1060. def set_gguf_parameters(self):
  1061. block_count = self.find_hparam(["num_hidden_layers", "n_layer"])
  1062. rot_pct = self.find_hparam(["partial_rotary_factor"])
  1063. n_embd = self.find_hparam(["hidden_size", "n_embd"])
  1064. n_head = self.find_hparam(["num_attention_heads", "n_head"])
  1065. self.gguf_writer.add_name("Phi2")
  1066. self.gguf_writer.add_context_length(self.find_hparam(["n_positions", "max_position_embeddings"]))
  1067. self.gguf_writer.add_embedding_length(n_embd)
  1068. self.gguf_writer.add_feed_forward_length(4 * n_embd)
  1069. self.gguf_writer.add_block_count(block_count)
  1070. self.gguf_writer.add_head_count(n_head)
  1071. self.gguf_writer.add_head_count_kv(n_head)
  1072. self.gguf_writer.add_layer_norm_eps(self.find_hparam(["layer_norm_epsilon", "layer_norm_eps"]))
  1073. self.gguf_writer.add_rope_dimension_count(int(rot_pct * n_embd) // n_head)
  1074. self.gguf_writer.add_file_type(self.ftype)
  1075. self.gguf_writer.add_add_bos_token(False)
  1076. class PlamoModel(Model):
  1077. def set_vocab(self):
  1078. self._set_vocab_sentencepiece()
  1079. def set_gguf_parameters(self):
  1080. hparams = self.hparams
  1081. block_count = hparams["num_hidden_layers"]
  1082. self.gguf_writer.add_name("PLaMo")
  1083. self.gguf_writer.add_context_length(4096) # not in config.json
  1084. self.gguf_writer.add_embedding_length(hparams["hidden_size"])
  1085. self.gguf_writer.add_feed_forward_length(hparams["intermediate_size"])
  1086. self.gguf_writer.add_block_count(block_count)
  1087. self.gguf_writer.add_head_count(hparams["num_attention_heads"])
  1088. self.gguf_writer.add_head_count_kv(5) # hparams["num_key_value_heads"]) is wrong
  1089. self.gguf_writer.add_layer_norm_rms_eps(hparams["rms_norm_eps"])
  1090. def shuffle_attn_q_weight(self, data_torch):
  1091. assert data_torch.size() == (5120, 5120)
  1092. data_torch = data_torch.reshape(8, 5, 128, 5120)
  1093. data_torch = torch.permute(data_torch, (1, 0, 2, 3))
  1094. data_torch = torch.reshape(data_torch, (5120, 5120))
  1095. return data_torch
  1096. def shuffle_attn_output_weight(self, data_torch):
  1097. assert data_torch.size() == (5120, 5120)
  1098. data_torch = data_torch.reshape(5120, 8, 5, 128)
  1099. data_torch = torch.permute(data_torch, (0, 2, 1, 3))
  1100. data_torch = torch.reshape(data_torch, (5120, 5120))
  1101. return data_torch
  1102. def write_tensors(self):
  1103. block_count = self.hparams.get("num_layers", self.hparams.get("num_hidden_layers"))
  1104. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  1105. for name, data_torch in self.get_tensors():
  1106. if "self_attn.rotary_emb.inv_freq" in name:
  1107. continue
  1108. # map tensor names
  1109. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  1110. if new_name is None:
  1111. print(f"Can not map tensor {name!r}")
  1112. sys.exit()
  1113. # shuffle for broadcasting of gqa in ggml_mul_mat
  1114. if new_name.endswith("attn_q.weight"):
  1115. data_torch = self.shuffle_attn_q_weight(data_torch)
  1116. elif new_name.endswith("attn_output.weight"):
  1117. data_torch = self.shuffle_attn_output_weight(data_torch)
  1118. old_dtype = data_torch.dtype
  1119. # convert any unsupported data types to float32
  1120. if data_torch.dtype not in (torch.float16, torch.float32):
  1121. data_torch = data_torch.to(torch.float32)
  1122. data = data_torch.squeeze().numpy()
  1123. n_dims = len(data.shape)
  1124. data_dtype = data.dtype
  1125. # if f32 desired, convert any float16 to float32
  1126. if self.ftype == 0 and data_dtype == np.float16:
  1127. data = data.astype(np.float32)
  1128. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  1129. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  1130. data = data.astype(np.float32)
  1131. # if f16 desired, convert any float32 2-dim weight tensors to float16
  1132. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  1133. data = data.astype(np.float16)
  1134. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  1135. self.gguf_writer.add_tensor(new_name, data)
  1136. class CodeShellModel(Model):
  1137. def set_gguf_parameters(self):
  1138. block_count = self.hparams["n_layer"]
  1139. self.gguf_writer.add_name("CodeShell")
  1140. self.gguf_writer.add_context_length(self.hparams["n_positions"])
  1141. self.gguf_writer.add_embedding_length(self.hparams["n_embd"])
  1142. self.gguf_writer.add_feed_forward_length(4 * self.hparams["n_embd"])
  1143. self.gguf_writer.add_block_count(block_count)
  1144. self.gguf_writer.add_head_count(self.hparams["n_head"])
  1145. self.gguf_writer.add_head_count_kv(self.hparams["num_query_groups"])
  1146. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
  1147. self.gguf_writer.add_file_type(self.ftype)
  1148. self.gguf_writer.add_rope_freq_base(10000.0)
  1149. self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.LINEAR)
  1150. self.gguf_writer.add_rope_scaling_factor(1.0)
  1151. def write_tensors(self):
  1152. block_count = self.hparams.get("n_layers", self.hparams.get("num_hidden_layers", self.hparams.get("n_layer")))
  1153. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  1154. tensors = dict(self.get_tensors())
  1155. has_lm_head = "lm_head.weight" in tensors.keys() or "output.weight" in tensors.keys()
  1156. for name, data_torch in tensors.items():
  1157. # we don't need these
  1158. if name.endswith((".attn.rotary_emb.inv_freq")):
  1159. continue
  1160. old_dtype = data_torch.dtype
  1161. # convert any unsupported data types to float32
  1162. if data_torch.dtype not in (torch.float16, torch.float32):
  1163. data_torch = data_torch.to(torch.float32)
  1164. data = data_torch.squeeze().numpy()
  1165. # map tensor names
  1166. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  1167. if new_name is None:
  1168. print(f"Can not map tensor {name!r}")
  1169. sys.exit()
  1170. n_dims = len(data.shape)
  1171. data_dtype = data.dtype
  1172. # if f32 desired, convert any float16 to float32
  1173. if self.ftype == 0 and data_dtype == np.float16:
  1174. data = data.astype(np.float32)
  1175. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  1176. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  1177. data = data.astype(np.float32)
  1178. # if f16 desired, convert any float32 2-dim weight tensors to float16
  1179. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  1180. data = data.astype(np.float16)
  1181. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  1182. self.gguf_writer.add_tensor(new_name, data)
  1183. if not has_lm_head and name == "transformer.wte.weight":
  1184. self.gguf_writer.add_tensor("output.weight", data)
  1185. print(name, f"=> output.weight, shape = {data.shape}, {old_dtype} --> {data.dtype}")
  1186. class InternLM2Model(Model):
  1187. def set_vocab(self):
  1188. # (TODO): Is there a better way?
  1189. # Copy from _set_vocab_sentencepiece, The only difference is that we will treat the character
  1190. # \x00 specially and convert it into an emoji character to prevent it from being mistakenly
  1191. # recognized as an empty string in C++.
  1192. from sentencepiece import SentencePieceProcessor
  1193. from sentencepiece import sentencepiece_model_pb2 as model
  1194. tokenizer_path = self.dir_model / 'tokenizer.model'
  1195. tokens: list[bytes] = []
  1196. scores: list[float] = []
  1197. toktypes: list[int] = []
  1198. if not tokenizer_path.is_file():
  1199. print(f'Error: Missing {tokenizer_path}', file=sys.stderr)
  1200. sys.exit(1)
  1201. sentencepiece_model = model.ModelProto()
  1202. sentencepiece_model.ParseFromString(open(tokenizer_path, "rb").read())
  1203. add_prefix = sentencepiece_model.normalizer_spec.add_dummy_prefix
  1204. tokenizer = SentencePieceProcessor(str(tokenizer_path))
  1205. vocab_size = self.hparams.get('vocab_size', tokenizer.vocab_size())
  1206. for token_id in range(vocab_size):
  1207. piece = tokenizer.id_to_piece(token_id)
  1208. text = piece.encode("utf-8")
  1209. score = tokenizer.get_score(token_id)
  1210. if text == b"\x00":
  1211. # (TODO): fixme
  1212. # Hack here and replace the \x00 characters.
  1213. print(f"InternLM2 convert token '{text}' to '🐉'!")
  1214. text = "🐉"
  1215. toktype = SentencePieceTokenTypes.NORMAL
  1216. if tokenizer.is_unknown(token_id):
  1217. toktype = SentencePieceTokenTypes.UNKNOWN
  1218. elif tokenizer.is_control(token_id):
  1219. toktype = SentencePieceTokenTypes.CONTROL
  1220. elif tokenizer.is_unused(token_id):
  1221. toktype = SentencePieceTokenTypes.UNUSED
  1222. elif tokenizer.is_byte(token_id):
  1223. toktype = SentencePieceTokenTypes.BYTE
  1224. tokens.append(text)
  1225. scores.append(score)
  1226. toktypes.append(toktype)
  1227. added_tokens_file = self.dir_model / 'added_tokens.json'
  1228. if added_tokens_file.is_file():
  1229. with open(added_tokens_file, "r", encoding="utf-8") as f:
  1230. added_tokens_json = json.load(f)
  1231. for key in added_tokens_json:
  1232. tokens.append(key.encode("utf-8"))
  1233. scores.append(-1000.0)
  1234. toktypes.append(SentencePieceTokenTypes.USER_DEFINED)
  1235. self.gguf_writer.add_tokenizer_model("llama")
  1236. self.gguf_writer.add_token_list(tokens)
  1237. self.gguf_writer.add_token_scores(scores)
  1238. self.gguf_writer.add_token_types(toktypes)
  1239. self.gguf_writer.add_add_space_prefix(add_prefix)
  1240. special_vocab = gguf.SpecialVocab(self.dir_model, n_vocab=len(tokens))
  1241. old_eos = special_vocab.special_token_ids["eos"]
  1242. if "chat" in os.path.basename(self.dir_model.absolute()):
  1243. # For the chat model, we replace the eos with '<|im_end|>'.
  1244. special_vocab.special_token_ids["eos"] = self._try_get_sft_eos(tokenizer)
  1245. print(f"Replace eos:{old_eos} with a special token:{special_vocab.special_token_ids['eos']} \
  1246. in chat mode so that the conversation can end normally.")
  1247. special_vocab.add_to_gguf(self.gguf_writer)
  1248. def _try_get_sft_eos(self, tokenizer):
  1249. unused_145_list = tokenizer.encode('[UNUSED_TOKEN_145]')
  1250. im_end_list = tokenizer.encode('<|im_end|>')
  1251. assert (len(unused_145_list) == 1) ^ (len(im_end_list) == 1)
  1252. if len(unused_145_list) == 1:
  1253. eos_token = unused_145_list[0]
  1254. if len(im_end_list) == 1:
  1255. eos_token = im_end_list[0]
  1256. return eos_token
  1257. def _hf_permute_qk(self, weights, n_head: int, n_head_kv: int):
  1258. if n_head_kv is not None and n_head != n_head_kv:
  1259. n_head = n_head_kv
  1260. return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  1261. .swapaxes(1, 2)
  1262. .reshape(weights.shape))
  1263. def set_gguf_parameters(self):
  1264. self.gguf_writer.add_name("InternLM2")
  1265. self.gguf_writer.add_context_length(self.hparams["max_position_embeddings"])
  1266. self.gguf_writer.add_block_count(self.hparams["num_hidden_layers"])
  1267. self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
  1268. self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
  1269. self.gguf_writer.add_rope_freq_base(self.hparams["rope_theta"])
  1270. self.gguf_writer.add_head_count(self.hparams["num_attention_heads"])
  1271. self.gguf_writer.add_layer_norm_rms_eps(self.hparams["rms_norm_eps"])
  1272. self.gguf_writer.add_head_count_kv(self.hparams["num_key_value_heads"])
  1273. def post_write_tensors(self, tensor_map, name, data_torch):
  1274. old_dtype = data_torch.dtype
  1275. # convert any unsupported data types to float32
  1276. if data_torch.dtype not in (torch.float16, torch.float32):
  1277. data_torch = data_torch.to(torch.float32)
  1278. data = data_torch.squeeze().numpy()
  1279. # map tensor names
  1280. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  1281. if new_name is None:
  1282. print(f"Can not map tensor {name!r}")
  1283. sys.exit()
  1284. n_dims = len(data.shape)
  1285. data_dtype = data.dtype
  1286. # if f32 desired, convert any float16 to float32
  1287. if self.ftype == 0 and data_dtype == np.float16:
  1288. data = data.astype(np.float32)
  1289. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  1290. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  1291. data = data.astype(np.float32)
  1292. # if f16 desired, convert any float32 2-dim weight tensors to float16
  1293. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  1294. data = data.astype(np.float16)
  1295. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  1296. self.gguf_writer.add_tensor(new_name, data)
  1297. def write_tensors(self):
  1298. from einops import rearrange
  1299. num_heads = self.hparams.get("num_attention_heads")
  1300. num_kv_heads = self.hparams.get("num_key_value_heads")
  1301. hidden_size = self.hparams.get("hidden_size")
  1302. q_per_kv = num_heads // num_kv_heads
  1303. head_dim = hidden_size // num_heads
  1304. num_groups = num_heads // q_per_kv
  1305. block_count = self.hparams["num_hidden_layers"]
  1306. model_kv = dict(self.get_tensors())
  1307. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  1308. qkv_pattern = r"model\.layers\.(\d+)\.attention\.wqkv"
  1309. for name, data_torch in model_kv.items():
  1310. # we don't need these
  1311. if name.endswith(".rotary_emb.inv_freq"):
  1312. continue
  1313. if re.match(qkv_pattern, name):
  1314. bid = re.findall(qkv_pattern, name)[0]
  1315. qkv = data_torch
  1316. qkv = rearrange(qkv.T, " o (g n i) ->o g n i", g=num_groups, n=q_per_kv + 2, i=head_dim)
  1317. q, k, v = qkv[..., : q_per_kv, :], qkv[..., q_per_kv: q_per_kv + 1, :], qkv[..., q_per_kv + 1: q_per_kv + 2, :]
  1318. # The model weights of q and k equire additional reshape.
  1319. q = self._hf_permute_qk(rearrange(q, " o g n i -> o (g n i)").T, num_heads, num_heads)
  1320. k = self._hf_permute_qk(rearrange(k, " o g n i -> o (g n i)").T, num_heads, num_kv_heads)
  1321. v = rearrange(v, " o g n i -> o (g n i)").T
  1322. self.post_write_tensors(tensor_map, f"model.layers.{bid}.attention.wq.weight", q)
  1323. self.post_write_tensors(tensor_map, f"model.layers.{bid}.attention.wk.weight", k)
  1324. self.post_write_tensors(tensor_map, f"model.layers.{bid}.attention.wv.weight", v)
  1325. else:
  1326. self.post_write_tensors(tensor_map, name, data_torch)
  1327. class BertModel(Model):
  1328. def __init__(self, *args, **kwargs):
  1329. super().__init__(*args, **kwargs)
  1330. self.vocab_size = None
  1331. def set_gguf_parameters(self):
  1332. super().set_gguf_parameters()
  1333. self.gguf_writer.add_causal_attention(False)
  1334. # get pooling path
  1335. with open(self.dir_model / "modules.json", encoding="utf-8") as f:
  1336. modules = json.load(f)
  1337. pooling_path = None
  1338. for mod in modules:
  1339. if mod["type"] == "sentence_transformers.models.Pooling":
  1340. pooling_path = mod["path"]
  1341. break
  1342. # get pooling type
  1343. pooling_type = gguf.PoolingType.NONE
  1344. if pooling_path is not None:
  1345. with open(self.dir_model / pooling_path / "config.json", encoding="utf-8") as f:
  1346. pooling = json.load(f)
  1347. if pooling["pooling_mode_mean_tokens"]:
  1348. pooling_type = gguf.PoolingType.MEAN
  1349. elif pooling["pooling_mode_cls_token"]:
  1350. pooling_type = gguf.PoolingType.CLS
  1351. else:
  1352. raise NotImplementedError("Only MEAN and CLS pooling types supported")
  1353. self.gguf_writer.add_pooling_type(pooling_type.value)
  1354. def set_vocab(self):
  1355. path = self.dir_model
  1356. added_tokens_path = self.dir_model if self.dir_model.exists() else None
  1357. # use huggingface vocab to get all tokens
  1358. vocab = HfVocab(path, added_tokens_path)
  1359. tokens, scores, toktypes = zip(*vocab.all_tokens())
  1360. assert len(tokens) == vocab.vocab_size
  1361. self.vocab_size = vocab.vocab_size
  1362. # we need this to validate the size of the token_type embeddings
  1363. # though currently we are passing all zeros to the token_type embeddings
  1364. n_token_types = len(set(toktypes))
  1365. self.gguf_writer.add_token_type_count(n_token_types)
  1366. # convert to phantom space vocab
  1367. def phantom(tok, typ):
  1368. if tok.startswith(b"[") and tok.endswith(b"]"):
  1369. return tok
  1370. if tok.startswith(b"##"):
  1371. return tok[2:]
  1372. return b"\xe2\x96\x81" + tok
  1373. tokens = tuple(phantom(t, y) for t, y in zip(tokens, toktypes))
  1374. # set up bos and eos tokens (cls and sep)
  1375. self.gguf_writer.add_bos_token_id(vocab.tokenizer.cls_token_id)
  1376. self.gguf_writer.add_eos_token_id(vocab.tokenizer.sep_token_id)
  1377. # add vocab to gguf
  1378. self.gguf_writer.add_tokenizer_model("bert")
  1379. self.gguf_writer.add_token_list(tokens)
  1380. self.gguf_writer.add_token_scores(scores)
  1381. self.gguf_writer.add_token_types(toktypes)
  1382. # handle special tokens
  1383. special_vocab = gguf.SpecialVocab(self.dir_model, n_vocab=len(tokens))
  1384. special_vocab.add_to_gguf(self.gguf_writer)
  1385. def write_tensors(self):
  1386. tensor_map = gguf.get_tensor_name_map(self.model_arch, self.block_count)
  1387. tensors = dict(self.get_tensors())
  1388. for name, data_torch in tensors.items():
  1389. # we are only using BERT for embeddings so we don't need the pooling layer
  1390. if name in ("embeddings.position_ids", "pooler.dense.weight", "pooler.dense.bias"):
  1391. continue # we don't need these
  1392. # map tensor names
  1393. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  1394. if new_name is None:
  1395. print(f"Can not map tensor {name!r}")
  1396. sys.exit()
  1397. data = data_torch.squeeze().numpy()
  1398. n_dims = len(data.shape)
  1399. new_dtype: type[np.floating[Any]]
  1400. if (
  1401. self.ftype == 1 and name.endswith(".weight") and n_dims == 2
  1402. and name != "embeddings.token_type_embeddings.weight" # not used with get_rows, must be F32
  1403. ):
  1404. # if f16 desired, convert any float32 2-dim weight tensors to float16
  1405. new_dtype = np.float16
  1406. else:
  1407. # if f32 desired, convert any float16 to float32
  1408. new_dtype = np.float32
  1409. print(f"{new_name}, n_dims = {n_dims}, {data_torch.dtype} --> {new_dtype}")
  1410. if data.dtype != new_dtype:
  1411. data = data.astype(new_dtype)
  1412. self.gguf_writer.add_tensor(new_name, data)
  1413. class NomicBertModel(BertModel):
  1414. def __init__(self, *args, **kwargs):
  1415. super().__init__(*args, **kwargs)
  1416. # the HF config claims n_ctx=8192, but it uses RoPE scaling
  1417. self.hparams["n_ctx"] = 2048
  1418. # SwigLU activation
  1419. assert self.hparams["activation_function"] == "swiglu"
  1420. # this doesn't do anything in the HF version
  1421. assert self.hparams["causal"] is False
  1422. # no bias tensors
  1423. assert self.hparams["qkv_proj_bias"] is False
  1424. assert self.hparams["mlp_fc1_bias"] is False
  1425. assert self.hparams["mlp_fc2_bias"] is False
  1426. # norm at end of layer
  1427. assert self.hparams["prenorm"] is False
  1428. # standard RoPE
  1429. assert self.hparams["rotary_emb_fraction"] == 1.0
  1430. assert self.hparams["rotary_emb_interleaved"] is False
  1431. assert self.hparams["rotary_emb_scale_base"] is None
  1432. def set_gguf_parameters(self):
  1433. super().set_gguf_parameters()
  1434. self.gguf_writer.add_rope_freq_base(self.hparams["rotary_emb_base"])
  1435. def get_tensors(self):
  1436. assert self.vocab_size is not None
  1437. for name, data in super().get_tensors():
  1438. # Nomic Embed's token embeddings tensor is padded, but llama.cpp wants tensor sizes to match exactly.
  1439. if name == 'embeddings.word_embeddings.weight' and data.shape[1] != self.vocab_size:
  1440. rounded_vocab_size = (self.vocab_size + 63) // 64 * 64
  1441. assert data.shape == (rounded_vocab_size, self.hparams["n_embd"])
  1442. data = data[:self.vocab_size, :]
  1443. yield name, data
  1444. class GemmaModel(Model):
  1445. def set_vocab(self):
  1446. self._set_vocab_sentencepiece()
  1447. def set_gguf_parameters(self):
  1448. hparams = self.hparams
  1449. block_count = hparams["num_hidden_layers"]
  1450. self.gguf_writer.add_name(self.dir_model.name)
  1451. self.gguf_writer.add_context_length(hparams["max_position_embeddings"])
  1452. self.gguf_writer.add_embedding_length(hparams["hidden_size"])
  1453. self.gguf_writer.add_block_count(block_count)
  1454. self.gguf_writer.add_feed_forward_length(hparams["intermediate_size"])
  1455. self.gguf_writer.add_head_count(hparams["num_attention_heads"])
  1456. self.gguf_writer.add_head_count_kv(self.hparams["num_key_value_heads"] if "num_key_value_heads" in hparams else hparams["num_attention_heads"])
  1457. self.gguf_writer.add_layer_norm_rms_eps(self.hparams["rms_norm_eps"])
  1458. self.gguf_writer.add_key_length(hparams["head_dim"])
  1459. self.gguf_writer.add_value_length(hparams["head_dim"])
  1460. def write_tensors(self):
  1461. block_count = self.hparams.get("n_layers", self.hparams.get("num_hidden_layers", self.hparams.get("n_layer")))
  1462. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  1463. for name, data_torch in self.get_tensors():
  1464. # ref: https://github.com/huggingface/transformers/blob/fc37f38915372c15992b540dfcbbe00a916d4fc6/src/transformers/models/gemma/modeling_gemma.py#L89
  1465. if name.endswith("norm.weight"):
  1466. data_torch = data_torch + 1
  1467. old_dtype = data_torch.dtype
  1468. # convert any unsupported data types to float32
  1469. if data_torch.dtype not in (torch.float16, torch.float32):
  1470. data_torch = data_torch.to(torch.float32)
  1471. data = data_torch.squeeze().numpy()
  1472. # map tensor names
  1473. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  1474. if new_name is None:
  1475. print(f"Can not map tensor {name!r}")
  1476. sys.exit()
  1477. n_dims = len(data.shape)
  1478. data_dtype = data.dtype
  1479. data = data.astype(np.float32)
  1480. # if f16 desired, convert any float32 2-dim weight tensors to float16
  1481. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  1482. data = data.astype(np.float16)
  1483. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  1484. self.gguf_writer.add_tensor(new_name, data)
  1485. ###### CONVERSION LOGIC ######
  1486. def parse_args() -> argparse.Namespace:
  1487. parser = argparse.ArgumentParser(
  1488. description="Convert a huggingface model to a GGML compatible file")
  1489. parser.add_argument(
  1490. "--vocab-only", action="store_true",
  1491. help="extract only the vocab",
  1492. )
  1493. parser.add_argument(
  1494. "--awq-path", type=Path, default=None,
  1495. help="Path to scale awq cache file")
  1496. parser.add_argument(
  1497. "--outfile", type=Path,
  1498. help="path to write to; default: based on input",
  1499. )
  1500. parser.add_argument(
  1501. "--outtype", type=str, choices=["f32", "f16"], default="f16",
  1502. help="output format - use f32 for float32, f16 for float16",
  1503. )
  1504. parser.add_argument("--bigendian", action="store_true", help="model is executed on big endian machine")
  1505. parser.add_argument(
  1506. "model", type=Path,
  1507. help="directory containing model file",
  1508. )
  1509. return parser.parse_args()
  1510. def main() -> None:
  1511. args = parse_args()
  1512. dir_model = args.model
  1513. if args.awq_path:
  1514. sys.path.insert(1, str(Path(__file__).parent / 'awq-py'))
  1515. from awq.apply_awq import add_scale_weights # type: ignore[import-not-found]
  1516. tmp_model_path = args.model / "weighted_model"
  1517. dir_model = tmp_model_path
  1518. if tmp_model_path.is_dir():
  1519. print(f"{tmp_model_path} exists as a weighted model.")
  1520. else:
  1521. tmp_model_path.mkdir(parents=True, exist_ok=True)
  1522. print("Saving new weighted model ...")
  1523. add_scale_weights(str(args.model), str(args.awq_path), str(tmp_model_path))
  1524. print(f"Saved weighted model at {tmp_model_path}.")
  1525. if not dir_model.is_dir():
  1526. print(f'Error: {args.model} is not a directory', file=sys.stderr)
  1527. sys.exit(1)
  1528. ftype_map = {
  1529. "f32": gguf.GGMLQuantizationType.F32,
  1530. "f16": gguf.GGMLQuantizationType.F16,
  1531. }
  1532. if args.outfile is not None:
  1533. fname_out = args.outfile
  1534. else:
  1535. # output in the same directory as the model by default
  1536. fname_out = dir_model / f'ggml-model-{args.outtype}.gguf'
  1537. print(f"Loading model: {dir_model.name}")
  1538. hparams = Model.load_hparams(dir_model)
  1539. with torch.inference_mode():
  1540. model_class = Model.from_model_architecture(hparams["architectures"][0])
  1541. model_instance = model_class(dir_model, ftype_map[args.outtype], fname_out, args.bigendian)
  1542. print("Set model parameters")
  1543. model_instance.set_gguf_parameters()
  1544. print("Set model tokenizer")
  1545. model_instance.set_vocab()
  1546. if args.vocab_only:
  1547. print(f"Exporting model vocab to '{fname_out}'")
  1548. model_instance.write_vocab()
  1549. else:
  1550. print(f"Exporting model to '{fname_out}'")
  1551. model_instance.write()
  1552. print(f"Model successfully exported to '{fname_out}'")
  1553. if __name__ == '__main__':
  1554. main()