1
0

convert-hf-to-gguf.py 54 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267
  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, cast, Optional
  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. # check for any of the given keys in the dictionary and return the value of the first key found
  20. def get_key_opts(d, keys):
  21. for k in keys:
  22. if k in d:
  23. return d[k]
  24. print(f"Could not find any of {keys}")
  25. sys.exit()
  26. ###### MODEL DEFINITIONS ######
  27. class SentencePieceTokenTypes(IntEnum):
  28. NORMAL = 1
  29. UNKNOWN = 2
  30. CONTROL = 3
  31. USER_DEFINED = 4
  32. UNUSED = 5
  33. BYTE = 6
  34. class Model:
  35. def __init__(self, dir_model: Path, ftype: int, fname_out: Path, is_big_endian: bool):
  36. self.dir_model = dir_model
  37. self.ftype = ftype
  38. self.fname_out = fname_out
  39. self.is_big_endian = is_big_endian
  40. self.endianess = gguf.GGUFEndian.BIG if is_big_endian else gguf.GGUFEndian.LITTLE
  41. self.is_safetensors = self._is_model_safetensors()
  42. self.num_parts = Model.count_model_parts(self.dir_model, ".safetensors" if self.is_safetensors else ".bin")
  43. self.part_names = self._get_part_names()
  44. self.hparams = Model.load_hparams(self.dir_model)
  45. self.model_arch = self._get_model_architecture()
  46. self.gguf_writer = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[self.model_arch], endianess=self.endianess, use_temp_file=False)
  47. def set_vocab(self):
  48. self._set_vocab_gpt2()
  49. def get_tensors(self) -> Iterator[tuple[str, Tensor]]:
  50. for part_name in self.part_names:
  51. print(f"gguf: loading model part '{part_name}'")
  52. ctx: ContextManager[Any]
  53. if self.is_safetensors:
  54. from safetensors import safe_open
  55. ctx = cast(ContextManager[Any], safe_open(self.dir_model / part_name, framework="pt", device="cpu"))
  56. else:
  57. ctx = contextlib.nullcontext(torch.load(str(self.dir_model / part_name), map_location="cpu", mmap=True, weights_only=True))
  58. with ctx as model_part:
  59. for name in model_part.keys():
  60. data = model_part.get_tensor(name) if self.is_safetensors else model_part[name]
  61. yield name, data
  62. def set_gguf_parameters(self):
  63. self.gguf_writer.add_name(self.dir_model.name)
  64. self.gguf_writer.add_block_count(self.hparams.get(
  65. "n_layers", self.hparams.get("num_hidden_layers", self.hparams.get("n_layer")),
  66. ))
  67. if (n_ctx := self.hparams.get("max_position_embeddings")) is not None:
  68. self.gguf_writer.add_context_length(n_ctx)
  69. if (n_embd := self.hparams.get("hidden_size")) is not None:
  70. self.gguf_writer.add_embedding_length(n_embd)
  71. if (n_ff := self.hparams.get("intermediate_size")) is not None:
  72. self.gguf_writer.add_feed_forward_length(n_ff)
  73. if (n_head := self.hparams.get("num_attention_heads")) is not None:
  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 (n_rms_eps := self.hparams.get("rms_norm_eps")) is not None:
  78. self.gguf_writer.add_layer_norm_rms_eps(n_rms_eps)
  79. if (n_experts := self.hparams.get("num_local_experts")) is not None:
  80. self.gguf_writer.add_expert_count(n_experts)
  81. if (n_experts_used := self.hparams.get("num_experts_per_tok")) is not None:
  82. self.gguf_writer.add_expert_used_count(n_experts_used)
  83. self.gguf_writer.add_parallel_residual(self.hparams.get("use_parallel_residual", True))
  84. def write_tensors(self):
  85. block_count = self.hparams.get("n_layers", self.hparams.get("num_hidden_layers", self.hparams.get("n_layer")))
  86. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  87. for name, data_torch in self.get_tensors():
  88. # we don't need these
  89. if name.endswith((".attention.masked_bias", ".attention.bias", ".attention.rotary_emb.inv_freq")):
  90. continue
  91. old_dtype = data_torch.dtype
  92. # convert any unsupported data types to float32
  93. if data_torch.dtype not in (torch.float16, torch.float32):
  94. data_torch = data_torch.to(torch.float32)
  95. data = data_torch.squeeze().numpy()
  96. # map tensor names
  97. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  98. if new_name is None:
  99. print(f"Can not map tensor {name!r}")
  100. sys.exit()
  101. n_dims = len(data.shape)
  102. data_dtype = data.dtype
  103. # if f32 desired, convert any float16 to float32
  104. if self.ftype == 0 and data_dtype == np.float16:
  105. data = data.astype(np.float32)
  106. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  107. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  108. data = data.astype(np.float32)
  109. # if f16 desired, convert any float32 2-dim weight tensors to float16
  110. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  111. data = data.astype(np.float16)
  112. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  113. self.gguf_writer.add_tensor(new_name, data)
  114. def write(self):
  115. self.write_tensors()
  116. self.gguf_writer.write_header_to_file()
  117. self.gguf_writer.write_kv_data_to_file()
  118. self.gguf_writer.write_tensors_to_file()
  119. self.gguf_writer.close()
  120. def write_vocab(self):
  121. self.gguf_writer.write_header_to_file()
  122. self.gguf_writer.write_kv_data_to_file()
  123. self.gguf_writer.close()
  124. @staticmethod
  125. def count_model_parts(dir_model: Path, prefix: str) -> int:
  126. num_parts = 0
  127. for filename in os.listdir(dir_model):
  128. if filename.endswith(prefix):
  129. num_parts += 1
  130. return num_parts
  131. @staticmethod
  132. def load_hparams(dir_model):
  133. with open(dir_model / "config.json", "r", encoding="utf-8") as f:
  134. return json.load(f)
  135. @staticmethod
  136. def from_model_architecture(model_architecture):
  137. if model_architecture == "GPTNeoXForCausalLM":
  138. return GPTNeoXModel
  139. if model_architecture == "BloomForCausalLM":
  140. return BloomModel
  141. if model_architecture == "MPTForCausalLM":
  142. return MPTModel
  143. if model_architecture in ("BaichuanForCausalLM", "BaiChuanForCausalLM"):
  144. return BaichuanModel
  145. if model_architecture in ("FalconForCausalLM", "RWForCausalLM"):
  146. return FalconModel
  147. if model_architecture == "GPTBigCodeForCausalLM":
  148. return StarCoderModel
  149. if model_architecture == "GPTRefactForCausalLM":
  150. return RefactModel
  151. if model_architecture == "PersimmonForCausalLM":
  152. return PersimmonModel
  153. if model_architecture in ("StableLMEpochForCausalLM", "LlavaStableLMEpochForCausalLM"):
  154. return StableLMModel
  155. if model_architecture == "QWenLMHeadModel":
  156. return QwenModel
  157. if model_architecture == "MixtralForCausalLM":
  158. return MixtralModel
  159. if model_architecture == "GPT2LMHeadModel":
  160. return GPT2Model
  161. if model_architecture == "PhiForCausalLM":
  162. return Phi2Model
  163. if model_architecture == "PlamoForCausalLM":
  164. return PlamoModel
  165. return Model
  166. def _is_model_safetensors(self) -> bool:
  167. return Model.count_model_parts(self.dir_model, ".safetensors") > 0
  168. def _get_part_names(self):
  169. if self.is_safetensors:
  170. if self.num_parts == 1: # there's only one .safetensors file
  171. return ("model.safetensors",)
  172. return (f"model-{n:05}-of-{self.num_parts:05}.safetensors" for n in range(1, self.num_parts + 1))
  173. if self.num_parts == 1: # there's only one .bin file
  174. return ("pytorch_model.bin",)
  175. return (f"pytorch_model-{n:05}-of-{self.num_parts:05}.bin" for n in range(1, self.num_parts + 1))
  176. def _get_model_architecture(self) -> gguf.MODEL_ARCH:
  177. arch = self.hparams["architectures"][0]
  178. if arch == "GPTNeoXForCausalLM":
  179. return gguf.MODEL_ARCH.GPTNEOX
  180. if arch == "BloomForCausalLM":
  181. return gguf.MODEL_ARCH.BLOOM
  182. if arch == "MPTForCausalLM":
  183. return gguf.MODEL_ARCH.MPT
  184. if arch in ("BaichuanForCausalLM", "BaiChuanForCausalLM"):
  185. return gguf.MODEL_ARCH.BAICHUAN
  186. if arch in ("FalconForCausalLM", "RWForCausalLM"):
  187. return gguf.MODEL_ARCH.FALCON
  188. if arch == "GPTBigCodeForCausalLM":
  189. return gguf.MODEL_ARCH.STARCODER
  190. if arch == "GPTRefactForCausalLM":
  191. return gguf.MODEL_ARCH.REFACT
  192. if arch == "PersimmonForCausalLM":
  193. return gguf.MODEL_ARCH.PERSIMMON
  194. if arch in ("StableLMEpochForCausalLM", "LlavaStableLMEpochForCausalLM"):
  195. return gguf.MODEL_ARCH.STABLELM
  196. if arch == "QWenLMHeadModel":
  197. return gguf.MODEL_ARCH.QWEN
  198. if arch == "MixtralForCausalLM":
  199. return gguf.MODEL_ARCH.LLAMA
  200. if arch == "GPT2LMHeadModel":
  201. return gguf.MODEL_ARCH.GPT2
  202. if arch == "PhiForCausalLM":
  203. return gguf.MODEL_ARCH.PHI2
  204. if arch == "PlamoForCausalLM":
  205. return gguf.MODEL_ARCH.PLAMO
  206. raise NotImplementedError(f'Architecture "{arch}" not supported!')
  207. def _set_vocab_gpt2(self):
  208. dir_model = self.dir_model
  209. hparams = self.hparams
  210. tokens: list[bytearray] = []
  211. toktypes: list[int] = []
  212. from transformers import AutoTokenizer
  213. tokenizer = AutoTokenizer.from_pretrained(dir_model)
  214. vocab_size = hparams.get("vocab_size", len(tokenizer.vocab))
  215. assert max(tokenizer.vocab.values()) < vocab_size
  216. reverse_vocab = {id_: encoded_tok for encoded_tok, id_ in tokenizer.vocab.items()}
  217. added_vocab = tokenizer.get_added_vocab()
  218. for i in range(vocab_size):
  219. if i not in reverse_vocab:
  220. pad_token = f"[PAD{i}]".encode('utf-8')
  221. tokens.append(bytearray(pad_token))
  222. toktypes.append(gguf.TokenType.USER_DEFINED)
  223. elif reverse_vocab[i] in added_vocab:
  224. tokens.append(reverse_vocab[i])
  225. if tokenizer.added_tokens_decoder[i].special:
  226. toktypes.append(gguf.TokenType.CONTROL)
  227. else:
  228. toktypes.append(gguf.TokenType.USER_DEFINED)
  229. else:
  230. tokens.append(reverse_vocab[i])
  231. toktypes.append(gguf.TokenType.NORMAL)
  232. self.gguf_writer.add_tokenizer_model("gpt2")
  233. self.gguf_writer.add_token_list(tokens)
  234. self.gguf_writer.add_token_types(toktypes)
  235. special_vocab = gguf.SpecialVocab(dir_model, load_merges=True)
  236. special_vocab.add_to_gguf(self.gguf_writer)
  237. def _set_vocab_sentencepiece(self):
  238. from sentencepiece import SentencePieceProcessor
  239. tokenizer_path = self.dir_model / 'tokenizer.model'
  240. tokens: list[bytes] = []
  241. scores: list[float] = []
  242. toktypes: list[int] = []
  243. if not tokenizer_path.is_file():
  244. print(f'Error: Missing {tokenizer_path}', file=sys.stderr)
  245. sys.exit(1)
  246. tokenizer = SentencePieceProcessor(str(tokenizer_path))
  247. vocab_size = self.hparams.get('vocab_size', tokenizer.vocab_size())
  248. for token_id in range(vocab_size):
  249. piece = tokenizer.id_to_piece(token_id)
  250. text = piece.encode("utf-8")
  251. score = tokenizer.get_score(token_id)
  252. toktype = SentencePieceTokenTypes.NORMAL
  253. if tokenizer.is_unknown(token_id):
  254. toktype = SentencePieceTokenTypes.UNKNOWN
  255. elif tokenizer.is_control(token_id):
  256. toktype = SentencePieceTokenTypes.CONTROL
  257. elif tokenizer.is_unused(token_id):
  258. toktype = SentencePieceTokenTypes.UNUSED
  259. elif tokenizer.is_byte(token_id):
  260. toktype = SentencePieceTokenTypes.BYTE
  261. tokens.append(text)
  262. scores.append(score)
  263. toktypes.append(toktype)
  264. added_tokens_file = self.dir_model / 'added_tokens.json'
  265. if added_tokens_file.is_file():
  266. with open(added_tokens_file, "r", encoding="utf-8") as f:
  267. added_tokens_json = json.load(f)
  268. for key in added_tokens_json:
  269. tokens.append(key.encode("utf-8"))
  270. scores.append(-1000.0)
  271. toktypes.append(SentencePieceTokenTypes.USER_DEFINED)
  272. self.gguf_writer.add_tokenizer_model("llama")
  273. self.gguf_writer.add_token_list(tokens)
  274. self.gguf_writer.add_token_scores(scores)
  275. self.gguf_writer.add_token_types(toktypes)
  276. special_vocab = gguf.SpecialVocab(self.dir_model, n_vocab=len(tokens))
  277. special_vocab.add_to_gguf(self.gguf_writer)
  278. class GPTNeoXModel(Model):
  279. def set_gguf_parameters(self):
  280. block_count = self.hparams["num_hidden_layers"]
  281. self.gguf_writer.add_name(self.dir_model.name)
  282. self.gguf_writer.add_context_length(self.hparams["max_position_embeddings"])
  283. self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
  284. self.gguf_writer.add_block_count(block_count)
  285. self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
  286. self.gguf_writer.add_rope_dimension_count(
  287. int(self.hparams["rotary_pct"] * (self.hparams["hidden_size"] // self.hparams["num_attention_heads"])),
  288. )
  289. self.gguf_writer.add_head_count(self.hparams["num_attention_heads"])
  290. self.gguf_writer.add_parallel_residual(self.hparams.get("use_parallel_residual", True))
  291. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_eps"])
  292. class BloomModel(Model):
  293. def set_gguf_parameters(self):
  294. self.gguf_writer.add_name("Bloom")
  295. n_embed = self.hparams.get("hidden_size", self.hparams.get("n_embed"))
  296. n_head = self.hparams.get("n_head", self.hparams.get("num_attention_heads"))
  297. self.gguf_writer.add_context_length(self.hparams.get("seq_length", n_embed))
  298. self.gguf_writer.add_embedding_length(n_embed)
  299. self.gguf_writer.add_feed_forward_length(4 * n_embed)
  300. self.gguf_writer.add_block_count(self.hparams["n_layer"])
  301. self.gguf_writer.add_head_count(n_head)
  302. self.gguf_writer.add_head_count_kv(n_head)
  303. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
  304. self.gguf_writer.add_file_type(self.ftype)
  305. def write_tensors(self):
  306. block_count = self.hparams["n_layer"]
  307. tensors = dict(self.get_tensors())
  308. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  309. has_lm_head = True
  310. n_head = self.hparams.get("n_head", self.hparams.get("num_attention_heads"))
  311. n_embed = self.hparams.get("hidden_size", self.hparams.get("n_embed"))
  312. for name, data_torch in tensors.items():
  313. if "lm_head.weight" not in tensors.keys() and "output.weight" not in tensors.keys():
  314. has_lm_head = False
  315. name = re.sub(r'transformer\.', '', name)
  316. old_dtype = data_torch.dtype
  317. # convert any unsupported data types to float32
  318. if data_torch.dtype not in (torch.float16, torch.float32):
  319. data_torch = data_torch.to(torch.float32)
  320. data = data_torch.squeeze().numpy()
  321. if re.match(r"h\.\d+\.self_attention\.query_key_value\.weight", name):
  322. # Map bloom-style qkv_linear to gpt-style qkv_linear
  323. # bloom: https://github.com/huggingface/transformers/blob/main/src/transformers/models/bloom/modeling_bloom.py#L238-L252 # noqa
  324. # gpt-2: https://github.com/huggingface/transformers/blob/main/src/transformers/models/gpt2/modeling_gpt2.py#L312 # noqa
  325. qkv_weights = data.reshape((n_head, 3, n_embed // n_head, n_embed))
  326. data = np.concatenate(
  327. (
  328. qkv_weights[:, 0, :, :].reshape((-1, n_embed)),
  329. qkv_weights[:, 1, :, :].reshape((-1, n_embed)),
  330. qkv_weights[:, 2, :, :].reshape((-1, n_embed)),
  331. ),
  332. axis=0,
  333. )
  334. print("re-format attention.linear_qkv.weight")
  335. elif re.match(r"h\.\d+\.self_attention\.query_key_value\.bias", name):
  336. qkv_bias = data.reshape((n_head, 3, n_embed // n_head))
  337. data = np.concatenate(
  338. (
  339. qkv_bias[:, 0, :].reshape((n_embed,)),
  340. qkv_bias[:, 1, :].reshape((n_embed,)),
  341. qkv_bias[:, 2, :].reshape((n_embed,)),
  342. ),
  343. axis=0,
  344. )
  345. print("re-format attention.linear_qkv.bias")
  346. # map tensor names
  347. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  348. if new_name is None:
  349. print(f"Can not map tensor {name!r}")
  350. sys.exit()
  351. n_dims = len(data.shape)
  352. data_dtype = data.dtype
  353. # if f32 desired, convert any float16 to float32
  354. if self.ftype == 0 and data_dtype == np.float16:
  355. data = data.astype(np.float32)
  356. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  357. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  358. data = data.astype(np.float32)
  359. # if f16 desired, convert any float32 2-dim weight tensors to float16
  360. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  361. data = data.astype(np.float16)
  362. print(f"=> {new_name}, shape = {data.shape}, {old_dtype} --> {data.dtype}")
  363. self.gguf_writer.add_tensor(new_name, data)
  364. if not has_lm_head and name == "word_embeddings.weight":
  365. self.gguf_writer.add_tensor("output.weight", data)
  366. print(name, f"=> output.weight, shape = {data.shape}, {old_dtype} --> {data.dtype}")
  367. class MPTModel(Model):
  368. def set_gguf_parameters(self):
  369. block_count = self.hparams["n_layers"]
  370. self.gguf_writer.add_name(self.dir_model.name)
  371. self.gguf_writer.add_context_length(self.hparams["max_seq_len"])
  372. self.gguf_writer.add_embedding_length(self.hparams["d_model"])
  373. self.gguf_writer.add_block_count(block_count)
  374. self.gguf_writer.add_feed_forward_length(4 * self.hparams["d_model"])
  375. self.gguf_writer.add_head_count(self.hparams["n_heads"])
  376. if kv_n_heads := self.hparams["attn_config"].get("kv_n_heads"):
  377. self.gguf_writer.add_head_count_kv(kv_n_heads)
  378. self.gguf_writer.add_layer_norm_eps(1e-5)
  379. if self.hparams["attn_config"]["clip_qkv"] is not None:
  380. self.gguf_writer.add_clamp_kqv(self.hparams["attn_config"]["clip_qkv"])
  381. self.gguf_writer.add_max_alibi_bias(self.hparams["attn_config"]["alibi_bias_max"])
  382. def write_tensors(self):
  383. block_count = self.hparams.get("n_layers", self.hparams.get("num_hidden_layers"))
  384. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  385. for name, data_torch in self.get_tensors():
  386. # we don't need these
  387. if name.endswith((".attention.masked_bias", ".attention.bias", ".attention.rotary_emb.inv_freq")):
  388. continue
  389. old_dtype = data_torch.dtype
  390. # convert any unsupported data types to float32
  391. if data_torch.dtype not in (torch.float16, torch.float32):
  392. data_torch = data_torch.to(torch.float32)
  393. data = data_torch.squeeze().numpy()
  394. # map tensor names
  395. if "scales" in name:
  396. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias", ".scales"))
  397. new_name = new_name.replace("scales", "act.scales")
  398. else:
  399. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  400. if new_name is None:
  401. print(f"Can not map tensor {name!r}")
  402. sys.exit()
  403. n_dims = len(data.shape)
  404. data_dtype = data.dtype
  405. # if f32 desired, convert any float16 to float32
  406. if self.ftype == 0 and data_dtype == np.float16:
  407. data = data.astype(np.float32)
  408. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  409. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  410. data = data.astype(np.float32)
  411. # if f16 desired, convert any float32 2-dim weight tensors to float16
  412. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  413. data = data.astype(np.float16)
  414. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  415. self.gguf_writer.add_tensor(new_name, data)
  416. # note: MPT output is tied to (same as) wte in original model;
  417. # for easier implementation in llama.cpp it's duplicated in GGUF, though :/
  418. if new_name == "token_embd.weight":
  419. self.gguf_writer.add_tensor("output.weight", data)
  420. class BaichuanModel(Model):
  421. def set_vocab(self):
  422. self._set_vocab_sentencepiece()
  423. def set_gguf_parameters(self):
  424. block_count = self.hparams["num_hidden_layers"]
  425. head_count = self.hparams["num_attention_heads"]
  426. head_count_kv = self.hparams.get("num_key_value_heads", head_count)
  427. hf_repo = self.hparams.get("_name_or_path", "")
  428. ctx_length = 0
  429. if "max_sequence_length" in self.hparams:
  430. ctx_length = self.hparams["max_sequence_length"]
  431. elif "max_position_embeddings" in self.hparams:
  432. ctx_length = self.hparams["max_position_embeddings"]
  433. elif "model_max_length" in self.hparams:
  434. ctx_length = self.hparams["model_max_length"]
  435. else:
  436. print("gguf: can not find ctx length parameter.")
  437. sys.exit()
  438. self.gguf_writer.add_name(self.dir_model.name)
  439. self.gguf_writer.add_source_hf_repo(hf_repo)
  440. self.gguf_writer.add_tensor_data_layout("Meta AI original pth")
  441. self.gguf_writer.add_context_length(ctx_length)
  442. self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
  443. self.gguf_writer.add_block_count(block_count)
  444. self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
  445. self.gguf_writer.add_rope_dimension_count(self.hparams["hidden_size"] // self.hparams["num_attention_heads"])
  446. self.gguf_writer.add_head_count(head_count)
  447. self.gguf_writer.add_head_count_kv(head_count_kv)
  448. self.gguf_writer.add_layer_norm_rms_eps(self.hparams["rms_norm_eps"])
  449. if self.hparams.get("rope_scaling") is not None and "factor" in self.hparams["rope_scaling"]:
  450. if self.hparams["rope_scaling"].get("type") == "linear":
  451. self.gguf_writer.add_rope_scaling_type(gguf.RopeScalingType.LINEAR)
  452. self.gguf_writer.add_rope_scaling_factor(self.hparams["rope_scaling"]["factor"])
  453. def write_tensors(self):
  454. # Collect tensors from generator object
  455. model_kv = dict(self.get_tensors())
  456. block_count = self.hparams["num_hidden_layers"]
  457. head_count = self.hparams["num_attention_heads"]
  458. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  459. head_count_kv = self.hparams.get("num_key_value_heads", head_count)
  460. for i in range(block_count):
  461. if (w := model_kv.get(f"model.layers.{i}.self_attn.W_pack.weight")) is not None:
  462. print(f"Unpacking and permuting layer {i}")
  463. model_kv[f"model.layers.{i}.self_attn.q_proj.weight"] = \
  464. self._reverse_hf_permute_part(w, 0, head_count, head_count)
  465. model_kv[f"model.layers.{i}.self_attn.k_proj.weight"] = \
  466. self._reverse_hf_permute_part(w, 1, head_count, head_count_kv)
  467. model_kv[f"model.layers.{i}.self_attn.v_proj.weight"] = \
  468. self._reverse_hf_part(w, 2)
  469. del model_kv[f"model.layers.{i}.self_attn.W_pack.weight"]
  470. for name, data_torch in model_kv.items():
  471. # we don't need these
  472. if name.endswith(".rotary_emb.inv_freq"):
  473. continue
  474. old_dtype = data_torch.dtype
  475. # convert any unsupported data types to float32
  476. if data_torch.dtype not in (torch.float16, torch.float32):
  477. data_torch = data_torch.to(torch.float32)
  478. data = data_torch.squeeze().numpy()
  479. # map tensor names
  480. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  481. if new_name is None:
  482. print(f"Can not map tensor {name!r}")
  483. sys.exit()
  484. n_dims = len(data.shape)
  485. data_dtype = data.dtype
  486. # if f32 desired, convert any float16 to float32
  487. if self.ftype == 0 and data_dtype == np.float16:
  488. data = data.astype(np.float32)
  489. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  490. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  491. data = data.astype(np.float32)
  492. # if f16 desired, convert any float32 2-dim weight tensors to float16
  493. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  494. data = data.astype(np.float16)
  495. print(f"{name} -> {new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  496. self.gguf_writer.add_tensor(new_name, data)
  497. def _reverse_hf_permute(self, weights: Tensor, n_head: int, n_kv_head: int | None = None) -> Tensor:
  498. if n_kv_head is not None and n_head != n_kv_head:
  499. n_head //= n_kv_head
  500. return (
  501. weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  502. .swapaxes(1, 2)
  503. .reshape(weights.shape)
  504. )
  505. def _reverse_hf_permute_part(
  506. self, weights: Tensor, n_part: int, n_head: int, n_head_kv: int | None = None,
  507. ) -> Tensor:
  508. r = weights.shape[0] // 3
  509. return self._reverse_hf_permute(weights[r * n_part:r * n_part + r, ...], n_head, n_head_kv)
  510. def _reverse_hf_part(self, weights: Tensor, n_part: int) -> Tensor:
  511. r = weights.shape[0] // 3
  512. return weights[r * n_part:r * n_part + r, ...]
  513. class FalconModel(Model):
  514. def set_gguf_parameters(self):
  515. block_count = self.hparams.get("num_hidden_layers")
  516. if block_count is None:
  517. block_count = self.hparams["n_layer"] # old name
  518. n_head = self.hparams.get("num_attention_heads")
  519. if n_head is None:
  520. n_head = self.hparams["n_head"] # old name
  521. n_head_kv = self.hparams.get("num_kv_heads")
  522. if n_head_kv is None:
  523. n_head_kv = self.hparams.get("n_head_kv", 1) # old name
  524. self.gguf_writer.add_name("Falcon")
  525. self.gguf_writer.add_context_length(2048) # not in config.json
  526. self.gguf_writer.add_tensor_data_layout("jploski") # qkv tensor transform
  527. self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
  528. self.gguf_writer.add_feed_forward_length(4 * self.hparams["hidden_size"])
  529. self.gguf_writer.add_block_count(block_count)
  530. self.gguf_writer.add_head_count(n_head)
  531. self.gguf_writer.add_head_count_kv(n_head_kv)
  532. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
  533. self.gguf_writer.add_file_type(self.ftype)
  534. def write_tensors(self):
  535. block_count = self.hparams.get("num_hidden_layers")
  536. if block_count is None:
  537. block_count = self.hparams["n_layer"] # old name
  538. n_head = self.hparams.get("num_attention_heads")
  539. if n_head is None:
  540. n_head = self.hparams["n_head"] # old name
  541. n_head_kv = self.hparams.get("num_kv_heads")
  542. if n_head_kv is None:
  543. n_head_kv = self.hparams.get("n_head_kv", 1) # old name
  544. head_dim = self.hparams["hidden_size"] // n_head
  545. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  546. for name, data_torch in self.get_tensors():
  547. old_dtype = data_torch.dtype
  548. # convert any unsupported data types to float32
  549. if data_torch.dtype not in (torch.float16, torch.float32):
  550. data_torch = data_torch.to(torch.float32)
  551. # QKV tensor transform
  552. # The original query_key_value tensor contains n_head_kv "kv groups",
  553. # each consisting of n_head/n_head_kv query weights followed by one key
  554. # and one value weight (shared by all query heads in the kv group).
  555. # This layout makes it a big pain to work with in GGML.
  556. # So we rearrange them here,, so that we have n_head query weights
  557. # followed by n_head_kv key weights followed by n_head_kv value weights,
  558. # in contiguous fashion.
  559. # ref: https://github.com/jploski/ggml/blob/falcon40b/examples/falcon/convert-hf-to-ggml.py
  560. if "query_key_value" in name:
  561. qkv = data_torch.view(n_head_kv, n_head // n_head_kv + 2, head_dim, head_dim * n_head)
  562. q = qkv[:, :-2].reshape(n_head * head_dim, head_dim * n_head)
  563. k = qkv[:, [-2]].reshape(n_head_kv * head_dim, head_dim * n_head)
  564. v = qkv[:, [-1]].reshape(n_head_kv * head_dim, head_dim * n_head)
  565. data_torch = torch.cat((q, k, v)).reshape_as(data_torch)
  566. data = data_torch.squeeze().numpy()
  567. # map tensor names
  568. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  569. if new_name is None:
  570. print(f"Can not map tensor {name!r}")
  571. sys.exit()
  572. n_dims = len(data.shape)
  573. data_dtype = data.dtype
  574. # if f32 desired, convert any float16 to float32
  575. if self.ftype == 0 and data_dtype == np.float16:
  576. data = data.astype(np.float32)
  577. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  578. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  579. data = data.astype(np.float32)
  580. # if f16 desired, convert any float32 2-dim weight tensors to float16
  581. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  582. data = data.astype(np.float16)
  583. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  584. self.gguf_writer.add_tensor(new_name, data)
  585. class StarCoderModel(Model):
  586. def set_gguf_parameters(self):
  587. block_count = self.hparams["n_layer"]
  588. self.gguf_writer.add_name("StarCoder")
  589. self.gguf_writer.add_context_length(self.hparams["n_positions"])
  590. self.gguf_writer.add_embedding_length(self.hparams["n_embd"])
  591. self.gguf_writer.add_feed_forward_length(4 * self.hparams["n_embd"])
  592. self.gguf_writer.add_block_count(block_count)
  593. self.gguf_writer.add_head_count(self.hparams["n_head"])
  594. self.gguf_writer.add_head_count_kv(1)
  595. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
  596. self.gguf_writer.add_file_type(self.ftype)
  597. class RefactModel(Model):
  598. def set_gguf_parameters(self):
  599. hidden_dim = self.hparams["n_embd"]
  600. inner_dim = 4 * hidden_dim
  601. hidden_dim = int(2 * inner_dim / 3)
  602. multiple_of = 256
  603. ff_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
  604. block_count = self.hparams["n_layer"]
  605. self.gguf_writer.add_name("Refact")
  606. # refact uses Alibi. So this is from config.json which might be used by training.
  607. self.gguf_writer.add_context_length(self.hparams["n_positions"])
  608. self.gguf_writer.add_embedding_length(self.hparams["n_embd"])
  609. self.gguf_writer.add_feed_forward_length(ff_dim)
  610. self.gguf_writer.add_block_count(block_count)
  611. self.gguf_writer.add_head_count(self.hparams["n_head"])
  612. self.gguf_writer.add_head_count_kv(1)
  613. self.gguf_writer.add_layer_norm_rms_eps(self.hparams["layer_norm_epsilon"])
  614. self.gguf_writer.add_file_type(self.ftype)
  615. def write_tensors(self):
  616. hidden_dim = self.hparams["n_embd"]
  617. inner_dim = 4 * hidden_dim
  618. hidden_dim = int(2 * inner_dim / 3)
  619. multiple_of = 256
  620. ff_dim = multiple_of * ((hidden_dim + multiple_of - 1) // multiple_of)
  621. n_head = self.hparams["n_head"]
  622. n_head_kv = 1
  623. head_dim = self.hparams["n_embd"] // n_head
  624. block_count = self.hparams["n_layer"]
  625. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  626. tensors = dict(self.get_tensors())
  627. for i in range(block_count):
  628. if (w := tensors.get(f"transformer.h.{i}.attn.kv.weight")) is not None:
  629. tensors[f"model.layers.{i}.self_attn.k_proj.weight"] = w[:n_head_kv * head_dim]
  630. tensors[f"model.layers.{i}.self_attn.v_proj.weight"] = w[n_head_kv * head_dim:]
  631. del tensors[f"transformer.h.{i}.attn.kv.weight"]
  632. if (w := tensors.get(f"transformer.h.{i}.attn.q.weight")) is not None:
  633. tensors[f"model.layers.{i}.self_attn.q_proj.weight"] = w
  634. del tensors[f"transformer.h.{i}.attn.q.weight"]
  635. if (w := tensors.get(f"transformer.h.{i}.mlp.gate_up_proj.weight")) is not None:
  636. tensors[f"model.layers.{i}.mlp.gate_proj.weight"] = w[:ff_dim]
  637. tensors[f"model.layers.{i}.mlp.up_proj.weight"] = w[ff_dim:]
  638. del tensors[f"transformer.h.{i}.mlp.gate_up_proj.weight"]
  639. for name, data_torch in tensors.items():
  640. old_dtype = data_torch.dtype
  641. # convert any unsupported data types to float32
  642. if data_torch.dtype not in (torch.float16, torch.float32):
  643. data_torch = data_torch.to(torch.float32)
  644. data = data_torch.squeeze().numpy()
  645. # map tensor names
  646. new_name = tensor_map.get_name(name, try_suffixes=(".weight",))
  647. if new_name is None:
  648. print(f"Can not map tensor {name!r}")
  649. sys.exit()
  650. n_dims = len(data.shape)
  651. data_dtype = data.dtype
  652. # if f32 desired, convert any float16 to float32
  653. if self.ftype == 0 and data_dtype == np.float16:
  654. data = data.astype(np.float32)
  655. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  656. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  657. data = data.astype(np.float32)
  658. # if f16 desired, convert any float32 2-dim weight tensors to float16
  659. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  660. data = data.astype(np.float16)
  661. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  662. self.gguf_writer.add_tensor(new_name, data)
  663. class PersimmonModel(Model):
  664. def set_gguf_parameters(self):
  665. block_count = self.hparams.get("num_layers", self.hparams.get("num_hidden_layers"))
  666. head_count = self.hparams["num_attention_heads"]
  667. head_count_kv = head_count
  668. hidden_size = self.hparams["hidden_size"]
  669. self.gguf_writer.add_name('persimmon-8b-chat')
  670. self.gguf_writer.add_context_length(self.hparams["max_position_embeddings"])
  671. self.gguf_writer.add_embedding_length(hidden_size)
  672. self.gguf_writer.add_block_count(block_count)
  673. self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
  674. # NOTE: not sure about this change - why does the model not have a rope dimension count when it is smaller
  675. # than the head size?
  676. # ref: https://github.com/ggerganov/llama.cpp/pull/4889
  677. # self.gguf_writer.add_rope_dimension_count(hidden_size // head_count)
  678. self.gguf_writer.add_rope_dimension_count(hidden_size // head_count // 2)
  679. self.gguf_writer.add_head_count(head_count)
  680. self.gguf_writer.add_head_count_kv(head_count_kv)
  681. self.gguf_writer.add_rope_freq_base(self.hparams["rope_theta"])
  682. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_eps"])
  683. self.gguf_writer.add_layer_norm_rms_eps(self.hparams["rms_norm_eps"])
  684. def set_vocab(self):
  685. self._set_vocab_sentencepiece()
  686. # self.gguf_writer.add_bos_token_id(71013)
  687. # self.gguf_writer.add_eos_token_id(71013)
  688. def write_tensors(self):
  689. block_count = self.hparams.get("num_layers", self.hparams.get("num_hidden_layers"))
  690. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  691. for name, data_torch in self.get_tensors():
  692. if name.endswith(".self_attention.rotary_emb.inv_freq"):
  693. continue
  694. old_dtype = data_torch.dtype
  695. # TODO: FP16 conversion produces garbage outputs. (Q8_0 does not, so..?)
  696. data = data_torch.to(torch.float32).squeeze().numpy()
  697. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  698. if new_name is None:
  699. print(f"Can not map tensor {name!r}")
  700. sys.exit()
  701. n_dims = len(data.shape)
  702. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  703. self.gguf_writer.add_tensor(new_name, data)
  704. class StableLMModel(Model):
  705. def set_gguf_parameters(self):
  706. hparams = self.hparams
  707. block_count = hparams["num_hidden_layers"]
  708. self.gguf_writer.add_name(self.dir_model.name)
  709. self.gguf_writer.add_context_length(hparams["max_position_embeddings"])
  710. self.gguf_writer.add_embedding_length(hparams["hidden_size"])
  711. self.gguf_writer.add_block_count(block_count)
  712. self.gguf_writer.add_feed_forward_length(hparams["intermediate_size"])
  713. self.gguf_writer.add_rope_dimension_count(int(hparams["rope_pct"] * (hparams["hidden_size"] // hparams["num_attention_heads"])))
  714. self.gguf_writer.add_head_count(hparams["num_attention_heads"])
  715. self.gguf_writer.add_parallel_residual(hparams["use_parallel_residual"] if "use_parallel_residual" in hparams else True)
  716. self.gguf_writer.add_layer_norm_eps(1e-5)
  717. class MixtralModel(Model):
  718. def set_vocab(self):
  719. self._set_vocab_sentencepiece()
  720. class QwenModel(Model):
  721. @staticmethod
  722. def token_bytes_to_string(b):
  723. from transformers.models.gpt2.tokenization_gpt2 import bytes_to_unicode
  724. byte_encoder = bytes_to_unicode()
  725. return ''.join([byte_encoder[ord(char)] for char in b.decode('latin-1')])
  726. @staticmethod
  727. def bpe(mergeable_ranks: dict[bytes, int], token: bytes, max_rank: Optional[int] = None) -> list[bytes]:
  728. parts = [bytes([b]) for b in token]
  729. while True:
  730. min_idx = None
  731. min_rank = None
  732. for i, pair in enumerate(zip(parts[:-1], parts[1:])):
  733. rank = mergeable_ranks.get(pair[0] + pair[1])
  734. if rank is not None and (min_rank is None or rank < min_rank):
  735. min_idx = i
  736. min_rank = rank
  737. if min_rank is None or (max_rank is not None and min_rank >= max_rank):
  738. break
  739. assert min_idx is not None
  740. parts = parts[:min_idx] + [parts[min_idx] + parts[min_idx + 1]] + parts[min_idx + 2:]
  741. return parts
  742. def set_vocab(self):
  743. dir_model = self.dir_model
  744. hparams = self.hparams
  745. tokens: list[bytearray] = []
  746. toktypes: list[int] = []
  747. from transformers import AutoTokenizer
  748. tokenizer = AutoTokenizer.from_pretrained(dir_model, trust_remote_code=True)
  749. vocab_size = hparams["vocab_size"]
  750. assert max(tokenizer.get_vocab().values()) < vocab_size
  751. merges = []
  752. vocab = {}
  753. mergeable_ranks = tokenizer.mergeable_ranks
  754. for token, rank in mergeable_ranks.items():
  755. vocab[self.token_bytes_to_string(token)] = rank
  756. if len(token) == 1:
  757. continue
  758. merged = QwenModel.bpe(mergeable_ranks, token, max_rank=rank)
  759. assert len(merged) == 2
  760. merges.append(' '.join(map(self.token_bytes_to_string, merged)))
  761. reverse_vocab = {id_ : encoded_tok for encoded_tok, id_ in vocab.items()}
  762. added_vocab = tokenizer.special_tokens
  763. for i in range(vocab_size):
  764. if i not in reverse_vocab:
  765. pad_token = f"[PAD{i}]".encode("utf-8")
  766. tokens.append(bytearray(pad_token))
  767. toktypes.append(gguf.TokenType.USER_DEFINED)
  768. elif reverse_vocab[i] in added_vocab:
  769. tokens.append(reverse_vocab[i])
  770. toktypes.append(gguf.TokenType.CONTROL)
  771. else:
  772. tokens.append(reverse_vocab[i])
  773. toktypes.append(gguf.TokenType.NORMAL)
  774. self.gguf_writer.add_tokenizer_model("gpt2")
  775. self.gguf_writer.add_token_list(tokens)
  776. self.gguf_writer.add_token_types(toktypes)
  777. special_vocab = gguf.SpecialVocab(dir_model, load_merges=False)
  778. special_vocab.merges = merges
  779. special_vocab._set_special_token("bos", tokenizer.special_tokens["<|endoftext|>"])
  780. special_vocab._set_special_token("eos", tokenizer.special_tokens["<|endoftext|>"])
  781. special_vocab._set_special_token("unk", tokenizer.special_tokens["<|endoftext|>"])
  782. special_vocab.add_to_gguf(self.gguf_writer)
  783. def set_gguf_parameters(self):
  784. self.gguf_writer.add_name("Qwen")
  785. self.gguf_writer.add_context_length(self.hparams["max_position_embeddings"])
  786. self.gguf_writer.add_block_count(self.hparams["num_hidden_layers"])
  787. self.gguf_writer.add_embedding_length(self.hparams["hidden_size"])
  788. self.gguf_writer.add_feed_forward_length(self.hparams["intermediate_size"])
  789. self.gguf_writer.add_rope_freq_base(self.hparams["rotary_emb_base"])
  790. self.gguf_writer.add_rope_dimension_count(self.hparams["hidden_size"] // self.hparams["num_attention_heads"])
  791. self.gguf_writer.add_head_count(self.hparams["num_attention_heads"])
  792. self.gguf_writer.add_layer_norm_rms_eps(self.hparams["layer_norm_epsilon"])
  793. def write_tensors(self):
  794. block_count = self.hparams["num_hidden_layers"]
  795. model_kv = dict(self.get_tensors())
  796. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  797. for name, data_torch in model_kv.items():
  798. # we don't need these
  799. if name.endswith(".rotary_emb.inv_freq"):
  800. continue
  801. old_dtype = data_torch.dtype
  802. # convert any unsupported data types to float32
  803. if data_torch.dtype not in (torch.float16, torch.float32):
  804. data_torch = data_torch.to(torch.float32)
  805. data = data_torch.squeeze().numpy()
  806. # map tensor names
  807. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  808. if new_name is None:
  809. print(f"Can not map tensor {name!r}")
  810. sys.exit()
  811. n_dims = len(data.shape)
  812. data_dtype = data.dtype
  813. # if f32 desired, convert any float16 to float32
  814. if self.ftype == 0 and data_dtype == np.float16:
  815. data = data.astype(np.float32)
  816. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  817. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  818. data = data.astype(np.float32)
  819. # if f16 desired, convert any float32 2-dim weight tensors to float16
  820. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  821. data = data.astype(np.float16)
  822. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  823. self.gguf_writer.add_tensor(new_name, data)
  824. class GPT2Model(Model):
  825. def set_gguf_parameters(self):
  826. self.gguf_writer.add_name(self.dir_model.name)
  827. self.gguf_writer.add_block_count(self.hparams["n_layer"])
  828. self.gguf_writer.add_context_length(self.hparams["n_ctx"])
  829. self.gguf_writer.add_embedding_length(self.hparams["n_embd"])
  830. self.gguf_writer.add_feed_forward_length(4 * self.hparams["n_embd"])
  831. self.gguf_writer.add_head_count(self.hparams["n_head"])
  832. self.gguf_writer.add_layer_norm_eps(self.hparams["layer_norm_epsilon"])
  833. self.gguf_writer.add_file_type(self.ftype)
  834. def write_tensors(self):
  835. block_count = self.hparams.get("n_layers", self.hparams.get("num_hidden_layers", self.hparams.get("n_layer")))
  836. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  837. for name, data_torch in self.get_tensors():
  838. # we don't need these
  839. if name.endswith((".attention.masked_bias", ".attention.bias", ".attention.rotary_emb.inv_freq", ".attn.bias")):
  840. continue
  841. if name.endswith((".c_attn.weight", ".c_proj.weight", ".c_fc.weight", ".c_proj.weight")):
  842. data_torch = data_torch.transpose(1, 0)
  843. old_dtype = data_torch.dtype
  844. # convert any unsupported data types to float32
  845. if data_torch.dtype not in (torch.float16, torch.float32):
  846. data_torch = data_torch.to(torch.float32)
  847. data = data_torch.squeeze().numpy()
  848. # map tensor names
  849. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  850. if new_name is None:
  851. print(f"Can not map tensor {name!r}")
  852. sys.exit()
  853. n_dims = len(data.shape)
  854. data_dtype = data.dtype
  855. # if f32 desired, convert any float16 to float32
  856. if self.ftype == 0 and data_dtype == np.float16:
  857. data = data.astype(np.float32)
  858. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  859. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  860. data = data.astype(np.float32)
  861. # if f16 desired, convert any float32 2-dim weight tensors to float16
  862. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  863. data = data.astype(np.float16)
  864. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  865. self.gguf_writer.add_tensor(new_name, data)
  866. # note: GPT2 output is tied to (same as) wte in original model
  867. if new_name == "token_embd.weight":
  868. print(f"output.weight, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  869. self.gguf_writer.add_tensor("output.weight", data)
  870. class Phi2Model(Model):
  871. def set_gguf_parameters(self):
  872. block_count = get_key_opts(self.hparams, ["num_hidden_layers", "n_layer"])
  873. rot_pct = get_key_opts(self.hparams, ["partial_rotary_factor"])
  874. n_embd = get_key_opts(self.hparams, ["hidden_size", "n_embd"])
  875. n_head = get_key_opts(self.hparams, ["num_attention_heads", "n_head"])
  876. self.gguf_writer.add_name("Phi2")
  877. self.gguf_writer.add_context_length(get_key_opts(self.hparams, ["n_positions", "max_position_embeddings"]))
  878. self.gguf_writer.add_embedding_length(n_embd)
  879. self.gguf_writer.add_feed_forward_length(4 * n_embd)
  880. self.gguf_writer.add_block_count(block_count)
  881. self.gguf_writer.add_head_count(n_head)
  882. self.gguf_writer.add_head_count_kv(n_head)
  883. self.gguf_writer.add_layer_norm_eps(get_key_opts(self.hparams, ["layer_norm_epsilon", "layer_norm_eps"]))
  884. self.gguf_writer.add_rope_dimension_count(int(rot_pct * n_embd) // n_head)
  885. self.gguf_writer.add_file_type(self.ftype)
  886. self.gguf_writer.add_add_bos_token(False)
  887. class PlamoModel(Model):
  888. def set_vocab(self):
  889. self._set_vocab_sentencepiece()
  890. def set_gguf_parameters(self):
  891. hparams = self.hparams
  892. block_count = hparams["num_hidden_layers"]
  893. self.gguf_writer.add_name("PLaMo")
  894. self.gguf_writer.add_context_length(4096) # not in config.json
  895. self.gguf_writer.add_embedding_length(hparams["hidden_size"])
  896. self.gguf_writer.add_feed_forward_length(hparams["intermediate_size"])
  897. self.gguf_writer.add_block_count(block_count)
  898. self.gguf_writer.add_head_count(hparams["num_attention_heads"])
  899. self.gguf_writer.add_head_count_kv(5) # hparams["num_key_value_heads"]) is wrong
  900. self.gguf_writer.add_layer_norm_rms_eps(hparams["rms_norm_eps"])
  901. def shuffle_attn_q_weight(self, data_torch):
  902. assert data_torch.size() == (5120, 5120)
  903. data_torch = data_torch.reshape(8, 5, 128, 5120)
  904. data_torch = torch.permute(data_torch, (1, 0, 2, 3))
  905. data_torch = torch.reshape(data_torch, (5120, 5120))
  906. return data_torch
  907. def shuffle_attn_output_weight(self, data_torch):
  908. assert data_torch.size() == (5120, 5120)
  909. data_torch = data_torch.reshape(5120, 8, 5, 128)
  910. data_torch = torch.permute(data_torch, (0, 2, 1, 3))
  911. data_torch = torch.reshape(data_torch, (5120, 5120))
  912. return data_torch
  913. def write_tensors(self):
  914. block_count = self.hparams.get("num_layers", self.hparams.get("num_hidden_layers"))
  915. tensor_map = gguf.get_tensor_name_map(self.model_arch, block_count)
  916. for name, data_torch in self.get_tensors():
  917. if "self_attn.rotary_emb.inv_freq" in name:
  918. continue
  919. # map tensor names
  920. new_name = tensor_map.get_name(name, try_suffixes=(".weight", ".bias"))
  921. if new_name is None:
  922. print(f"Can not map tensor {name!r}")
  923. sys.exit()
  924. # shuffle for broadcasting of gqa in ggml_mul_mat
  925. if new_name.endswith("attn_q.weight"):
  926. data_torch = self.shuffle_attn_q_weight(data_torch)
  927. elif new_name.endswith("attn_output.weight"):
  928. data_torch = self.shuffle_attn_output_weight(data_torch)
  929. old_dtype = data_torch.dtype
  930. # convert any unsupported data types to float32
  931. if data_torch.dtype not in (torch.float16, torch.float32):
  932. data_torch = data_torch.to(torch.float32)
  933. data = data_torch.squeeze().numpy()
  934. n_dims = len(data.shape)
  935. data_dtype = data.dtype
  936. # if f32 desired, convert any float16 to float32
  937. if self.ftype == 0 and data_dtype == np.float16:
  938. data = data.astype(np.float32)
  939. # TODO: Why cant we use these float16 as-is? There should be not reason to store float16 as float32
  940. if self.ftype == 1 and data_dtype == np.float16 and n_dims == 1:
  941. data = data.astype(np.float32)
  942. # if f16 desired, convert any float32 2-dim weight tensors to float16
  943. if self.ftype == 1 and data_dtype == np.float32 and name.endswith(".weight") and n_dims == 2:
  944. data = data.astype(np.float16)
  945. print(f"{new_name}, n_dims = {n_dims}, {old_dtype} --> {data.dtype}")
  946. self.gguf_writer.add_tensor(new_name, data)
  947. ###### CONVERSION LOGIC ######
  948. def parse_args() -> argparse.Namespace:
  949. parser = argparse.ArgumentParser(
  950. description="Convert a huggingface model to a GGML compatible file")
  951. parser.add_argument(
  952. "--vocab-only", action="store_true",
  953. help="extract only the vocab",
  954. )
  955. parser.add_argument(
  956. "--awq-path", type=Path, default=None,
  957. help="Path to scale awq cache file")
  958. parser.add_argument(
  959. "--outfile", type=Path,
  960. help="path to write to; default: based on input",
  961. )
  962. parser.add_argument(
  963. "--outtype", type=str, choices=["f32", "f16"], default="f16",
  964. help="output format - use f32 for float32, f16 for float16",
  965. )
  966. parser.add_argument("--bigendian", action="store_true", help="model is executed on big endian machine")
  967. parser.add_argument(
  968. "model", type=Path,
  969. help="directory containing model file",
  970. )
  971. return parser.parse_args()
  972. def main() -> None:
  973. args = parse_args()
  974. dir_model = args.model
  975. if args.awq_path:
  976. sys.path.insert(1, str(Path(__file__).parent / 'awq-py'))
  977. from awq.apply_awq import add_scale_weights
  978. tmp_model_path = args.model / "weighted_model"
  979. dir_model = tmp_model_path
  980. if tmp_model_path.is_dir():
  981. print(f"{tmp_model_path} exists as a weighted model.")
  982. else:
  983. tmp_model_path.mkdir(parents=True, exist_ok=True)
  984. print("Saving new weighted model ...")
  985. add_scale_weights(str(args.model), str(args.awq_path), str(tmp_model_path))
  986. print(f"Saved weighted model at {tmp_model_path}.")
  987. if not dir_model.is_dir():
  988. print(f'Error: {args.model} is not a directory', file=sys.stderr)
  989. sys.exit(1)
  990. ftype_map = {
  991. "f32": gguf.GGMLQuantizationType.F32,
  992. "f16": gguf.GGMLQuantizationType.F16,
  993. }
  994. if args.outfile is not None:
  995. fname_out = args.outfile
  996. else:
  997. # output in the same directory as the model by default
  998. fname_out = dir_model / f'ggml-model-{args.outtype}.gguf'
  999. print(f"Loading model: {dir_model.name}")
  1000. hparams = Model.load_hparams(dir_model)
  1001. with torch.inference_mode():
  1002. model_class = Model.from_model_architecture(hparams["architectures"][0])
  1003. model_instance = model_class(dir_model, ftype_map[args.outtype], fname_out, args.bigendian)
  1004. print("Set model parameters")
  1005. model_instance.set_gguf_parameters()
  1006. print("Set model tokenizer")
  1007. model_instance.set_vocab()
  1008. if args.vocab_only:
  1009. print(f"Exporting model vocab to '{fname_out}'")
  1010. model_instance.write_vocab()
  1011. else:
  1012. print(f"Exporting model to '{fname_out}'")
  1013. model_instance.write()
  1014. print(f"Model successfully exported to '{fname_out}'")
  1015. if __name__ == '__main__':
  1016. main()