convert.py 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  1. #!/usr/bin/env python3
  2. import gguf
  3. import argparse
  4. import concurrent.futures
  5. import copy
  6. import enum
  7. import faulthandler
  8. import functools
  9. import io
  10. import itertools
  11. import json
  12. import math
  13. import mmap
  14. import pickle
  15. import re
  16. import signal
  17. import struct
  18. import sys
  19. import zipfile
  20. import numpy as np
  21. from abc import ABCMeta, abstractmethod
  22. from dataclasses import dataclass
  23. from pathlib import Path
  24. from typing import (IO, TYPE_CHECKING, Any, Callable, Dict, Iterable, List, Literal, Optional, Sequence, Tuple, TypeVar, Union)
  25. from sentencepiece import SentencePieceProcessor # type: ignore
  26. if TYPE_CHECKING:
  27. from typing_extensions import TypeAlias
  28. if hasattr(faulthandler, 'register') and hasattr(signal, 'SIGUSR1'):
  29. faulthandler.register(signal.SIGUSR1)
  30. NDArray: 'TypeAlias' = 'np.ndarray[Any, Any]'
  31. ARCH=gguf.MODEL_ARCH.LLAMA
  32. NAMES=gguf.MODEL_TENSOR_NAMES[ARCH]
  33. #
  34. # data types
  35. #
  36. @dataclass(frozen=True)
  37. class UnquantizedDataType:
  38. name: str
  39. DT_F16 = UnquantizedDataType('F16')
  40. DT_F32 = UnquantizedDataType('F32')
  41. DT_I32 = UnquantizedDataType('I32')
  42. DT_BF16 = UnquantizedDataType('BF16')
  43. DataType = Union[UnquantizedDataType]
  44. DATA_TYPE_TO_NUMPY: Dict[DataType, 'np.dtype[Any]'] = {
  45. DT_BF16: np.dtype(np.uint16),
  46. DT_F16: np.dtype(np.float16),
  47. DT_F32: np.dtype(np.float32),
  48. DT_I32: np.dtype(np.int32),
  49. }
  50. NUMPY_TYPE_TO_DATA_TYPE: Dict['np.dtype[Any]', DataType] = \
  51. {dtype: data_type for (data_type, dtype) in DATA_TYPE_TO_NUMPY.items()}
  52. SAFETENSORS_DATA_TYPES: Dict[str, DataType] = {
  53. 'BF16': DT_BF16,
  54. 'F16': DT_F16,
  55. 'F32': DT_F32,
  56. 'I32': DT_I32,
  57. }
  58. # TODO: match this with `llama_ftype`
  59. # TODO: rename to LLAMAFileType
  60. # TODO: move to `gguf.py`
  61. class GGMLFileType(enum.IntEnum):
  62. AllF32 = 0
  63. MostlyF16 = 1 # except 1d tensors
  64. def type_for_tensor(self, name: str, tensor: 'LazyTensor') -> DataType:
  65. if len(tensor.shape) == 1:
  66. # 1D tensors are always F32.
  67. return DT_F32
  68. elif self == GGMLFileType.AllF32:
  69. return DT_F32
  70. elif self == GGMLFileType.MostlyF16:
  71. return DT_F16
  72. else:
  73. raise ValueError(self)
  74. #
  75. # hparams loading
  76. #
  77. @dataclass
  78. class Params:
  79. n_vocab: int
  80. n_embd: int
  81. n_mult: int
  82. n_layer: int
  83. n_ctx: int
  84. n_ff: int
  85. n_head: int
  86. n_head_kv: int
  87. f_norm_eps: float
  88. f_rope_freq_base: Optional[float] = None
  89. f_rope_scale: Optional[float] = None
  90. ftype: Optional[GGMLFileType] = None
  91. # path to the directory containing the model files
  92. path_model: Optional['Path'] = None
  93. @staticmethod
  94. def find_n_mult(n_ff: int, n_embd: int) -> int:
  95. # hardcoded magic range
  96. for n_mult in range(8192, 1, -1):
  97. calc_ff = (((8*n_embd) // 3 + n_mult - 1) // n_mult)*n_mult
  98. if calc_ff == n_ff:
  99. return n_mult
  100. raise Exception(f"failed to find n_mult for (n_ff={n_ff}, n_embd={n_embd}).")
  101. @staticmethod
  102. def guessed(model: 'LazyModel') -> 'Params':
  103. # try transformer naming first
  104. n_vocab, n_embd = model["model.embed_tokens.weight"].shape if "model.embed_tokens.weight" in model else model["tok_embeddings.weight"].shape
  105. # try transformer naming first
  106. if "model.layers.0.self_attn.q_proj.weight" in model:
  107. n_layer=next(i for i in itertools.count() if f"model.layers.{i}.self_attn.q_proj.weight" not in model)
  108. elif "model.layers.0.self_attn.W_pack.weight" in model: # next: try baichuan naming
  109. n_layer=next(i for i in itertools.count() if f"model.layers.{i}.self_attn.W_pack.weight" not in model)
  110. else:
  111. n_layer=next(i for i in itertools.count() if f"layers.{i}.attention.wq.weight" not in model)
  112. if n_layer < 1:
  113. raise Exception("failed to guess 'n_layer'. This model is unknown or unsupported.\n"
  114. "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
  115. n_head = n_embd // 128 # guessed
  116. n_mult = 256 # guessed
  117. # TODO: verify this
  118. n_ff = int(2 * (4 * n_embd) / 3)
  119. n_ff = n_mult * ((n_ff + n_mult - 1) // n_mult)
  120. return Params(
  121. n_vocab = n_vocab,
  122. n_embd = n_embd,
  123. n_mult = n_mult,
  124. n_layer = n_layer,
  125. n_ctx = -1,
  126. n_ff = n_ff,
  127. n_head = n_head,
  128. n_head_kv = n_head,
  129. f_norm_eps = 1e-5,
  130. )
  131. @staticmethod
  132. def loadHFTransformerJson(model: 'LazyModel', config_path: 'Path') -> 'Params':
  133. config = json.load(open(config_path))
  134. n_vocab = config["vocab_size"]
  135. n_embd = config["hidden_size"]
  136. n_layer = config["num_hidden_layers"]
  137. n_ff = config["intermediate_size"]
  138. n_head = config["num_attention_heads"]
  139. n_head_kv = config["num_key_value_heads"] if "num_key_value_heads" in config else n_head
  140. f_norm_eps = config["rms_norm_eps"]
  141. f_rope_freq_base = config["rope_theta"] if "rope_theta" in config else None
  142. rope_scaling = config.get("rope_scaling")
  143. if isinstance(rope_scaling, dict) and rope_scaling.get("type") == "linear":
  144. f_rope_scale = config["rope_scaling"].get("factor")
  145. else:
  146. f_rope_scale = None
  147. n_mult = Params.find_n_mult(n_ff, n_embd)
  148. if "max_sequence_length" in config:
  149. n_ctx = config["max_sequence_length"]
  150. elif "max_position_embeddings" in config:
  151. n_ctx = config["max_position_embeddings"]
  152. else:
  153. raise Exception("failed to guess 'n_ctx'. This model is unknown or unsupported.\n"
  154. "Suggestion: provide 'config.json' of the model in the same directory containing model files.")
  155. return Params(
  156. n_vocab = n_vocab,
  157. n_embd = n_embd,
  158. n_mult = n_mult,
  159. n_layer = n_layer,
  160. n_ctx = n_ctx,
  161. n_ff = n_ff,
  162. n_head = n_head,
  163. n_head_kv = n_head_kv,
  164. f_norm_eps = f_norm_eps,
  165. f_rope_freq_base = f_rope_freq_base,
  166. f_rope_scale = f_rope_scale,
  167. )
  168. # LLaMA v2 70B params.json
  169. # {"dim": 8192, "multiple_of": 4096, "ffn_dim_multiplier": 1.3, "n_heads": 64, "n_kv_heads": 8, "n_layers": 80, "norm_eps": 1e-05, "vocab_size": -1
  170. @staticmethod
  171. def loadOriginalParamsJson(model: 'LazyModel', config_path: 'Path') -> 'Params':
  172. config = json.load(open(config_path))
  173. n_vocab = config["vocab_size"] if "vocab_size" in config else -1
  174. n_embd = config["dim"]
  175. n_layer = config["n_layers"]
  176. n_mult = config["multiple_of"]
  177. n_ff = -1
  178. n_head = config["n_heads"]
  179. n_head_kv = config["n_kv_heads"] if "n_kv_heads" in config else n_head
  180. f_norm_eps = config["norm_eps"]
  181. f_rope_freq_base = config["rope_theta"] if "rope_theta" in config else None
  182. # hack to determine LLaMA v1 vs v2 vs CodeLlama
  183. if f_rope_freq_base and f_rope_freq_base == 1000000:
  184. # CodeLlama
  185. n_ctx = 16384
  186. elif config["norm_eps"] == 1e-05:
  187. # LLaMA v2
  188. n_ctx = 4096
  189. else:
  190. # LLaMA v1
  191. n_ctx = 2048
  192. if n_vocab == -1:
  193. n_vocab = model["tok_embeddings.weight"].shape[0]
  194. if n_ff == -1:
  195. n_ff = model["layers.0.feed_forward.w1.weight"].shape[0]
  196. return Params(
  197. n_vocab = n_vocab,
  198. n_embd = n_embd,
  199. n_mult = n_mult,
  200. n_layer = n_layer,
  201. n_ctx = n_ctx,
  202. n_ff = n_ff,
  203. n_head = n_head,
  204. n_head_kv = n_head_kv,
  205. f_norm_eps = f_norm_eps,
  206. f_rope_freq_base = f_rope_freq_base,
  207. )
  208. @staticmethod
  209. def load(model_plus: 'ModelPlus') -> 'Params':
  210. hf_config_path = model_plus.paths[0].parent / "config.json"
  211. orig_config_path = model_plus.paths[0].parent / "params.json"
  212. if hf_config_path.exists():
  213. params = Params.loadHFTransformerJson(model_plus.model, hf_config_path)
  214. elif orig_config_path.exists():
  215. params = Params.loadOriginalParamsJson(model_plus.model, orig_config_path)
  216. else:
  217. params = Params.guessed(model_plus.model)
  218. params.path_model = model_plus.paths[0].parent
  219. return params
  220. #
  221. # vocab
  222. #
  223. class BpeVocab:
  224. def __init__(self, fname_tokenizer: Path, fname_added_tokens: Optional[Path]) -> None:
  225. self.bpe_tokenizer = json.loads(open(str(fname_tokenizer), encoding="utf-8").read())
  226. added_tokens: Dict[str, int]
  227. if fname_added_tokens is not None:
  228. added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
  229. else:
  230. added_tokens = {}
  231. vocab_size: int = len(self.bpe_tokenizer)
  232. expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
  233. actual_ids = sorted(added_tokens.values())
  234. if expected_ids != actual_ids:
  235. raise Exception(f"Expected added token IDs to be sequential and start at {len(added_tokens)}; got {actual_ids}")
  236. items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
  237. self.added_tokens_list = [text for (text, idx) in items]
  238. self.vocab_size_base: int = vocab_size
  239. self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list)
  240. self.fname_tokenizer = fname_tokenizer
  241. self.fname_added_tokens = fname_added_tokens
  242. def bpe_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  243. tokenizer = self.bpe_tokenizer
  244. from transformers.models.gpt2 import tokenization_gpt2
  245. byte_encoder = tokenization_gpt2.bytes_to_unicode()
  246. byte_decoder = {v: k for k, v in byte_encoder.items()}
  247. for i, item in enumerate(tokenizer):
  248. text: bytes = item.encode("utf-8")
  249. score: float = -i
  250. yield text, score, gguf.TokenType.USER_DEFINED
  251. def added_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  252. for text in self.added_tokens_list:
  253. score = -1000.0
  254. yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED
  255. def all_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  256. yield from self.bpe_tokens()
  257. yield from self.added_tokens()
  258. def __repr__(self) -> str:
  259. return f"BpeVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  260. class SentencePieceVocab:
  261. def __init__(self, fname_tokenizer: Path, fname_added_tokens: Optional[Path]) -> None:
  262. self.sentencepiece_tokenizer = SentencePieceProcessor(str(fname_tokenizer))
  263. added_tokens: Dict[str, int]
  264. if fname_added_tokens is not None:
  265. added_tokens = json.load(open(fname_added_tokens, encoding="utf-8"))
  266. else:
  267. added_tokens = {}
  268. vocab_size: int = self.sentencepiece_tokenizer.vocab_size()
  269. expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
  270. actual_ids = sorted(added_tokens.values())
  271. if expected_ids != actual_ids:
  272. raise Exception(f"Expected added token IDs to be sequential and start at {len(added_tokens)}; got {actual_ids}")
  273. items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
  274. self.added_tokens_list = [text for (text, idx) in items]
  275. self.vocab_size_base: int = vocab_size
  276. self.vocab_size: int = self.vocab_size_base + len(self.added_tokens_list)
  277. self.fname_tokenizer = fname_tokenizer
  278. self.fname_added_tokens = fname_added_tokens
  279. def sentencepiece_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  280. tokenizer = self.sentencepiece_tokenizer
  281. for i in range(tokenizer.vocab_size()):
  282. piece = tokenizer.id_to_piece(i)
  283. text: bytes = piece.encode("utf-8")
  284. score: float = tokenizer.get_score(i)
  285. toktype = gguf.TokenType.NORMAL
  286. if tokenizer.is_unknown(i):
  287. toktype = gguf.TokenType.UNKNOWN
  288. if tokenizer.is_control(i):
  289. toktype = gguf.TokenType.CONTROL
  290. # NOTE: I think added_tokens are user defined.
  291. # ref: https://github.com/google/sentencepiece/blob/master/src/sentencepiece_model.proto
  292. # if tokenizer.is_user_defined(i): toktype = gguf.TokenType.USER_DEFINED
  293. if tokenizer.is_unused(i):
  294. toktype = gguf.TokenType.UNUSED
  295. if tokenizer.is_byte(i):
  296. toktype = gguf.TokenType.BYTE
  297. yield text, score, toktype
  298. def added_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  299. for text in self.added_tokens_list:
  300. score = -1000.0
  301. yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED
  302. def all_tokens(self) -> Iterable[Tuple[bytes, float, gguf.TokenType]]:
  303. yield from self.sentencepiece_tokens()
  304. yield from self.added_tokens()
  305. def __repr__(self) -> str:
  306. return f"<SentencePieceVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  307. Vocab = Union[BpeVocab, SentencePieceVocab]
  308. #
  309. # data loading
  310. # TODO: reuse (probably move to gguf.py?)
  311. #
  312. def permute(weights: NDArray, n_head: int, n_head_kv: int) -> NDArray:
  313. #print( "permute debug " + str(weights.shape[0]) + " x " + str(weights.shape[1]) + " nhead " + str(n_head) + " nheadkv " + str(n_kv_head) )
  314. if n_head_kv is not None and n_head != n_head_kv:
  315. n_head //= n_head_kv
  316. return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  317. .swapaxes(1, 2)
  318. .reshape(weights.shape))
  319. class Tensor(metaclass=ABCMeta):
  320. data_type: DataType
  321. @abstractmethod
  322. def astype(self, data_type: DataType) -> 'Tensor': ...
  323. @abstractmethod
  324. def permute(self, n_head: int, n_head_kv: int) -> 'Tensor': ...
  325. @abstractmethod
  326. def permute_part(self, n_part: int, n_head: int) -> 'UnquantizedTensor': ...
  327. @abstractmethod
  328. def part(self, n_part: int) -> 'UnquantizedTensor': ...
  329. @abstractmethod
  330. def to_ggml(self) -> 'GGMLCompatibleTensor': ...
  331. def bf16_to_fp32(bf16_arr: np.ndarray) -> np.ndarray:
  332. assert bf16_arr.dtype == np.uint16, f"Input array should be of dtype uint16, but got {bf16_arr.dtype}"
  333. fp32_arr = bf16_arr.astype(np.uint32) << 16
  334. return fp32_arr.view(np.float32)
  335. class UnquantizedTensor(Tensor):
  336. def __init__(self, ndarray: NDArray) -> None:
  337. assert isinstance(ndarray, np.ndarray)
  338. self.ndarray = ndarray
  339. self.data_type = NUMPY_TYPE_TO_DATA_TYPE[ndarray.dtype]
  340. def astype(self, data_type: DataType) -> Tensor:
  341. dtype = DATA_TYPE_TO_NUMPY[data_type]
  342. if self.data_type == DT_BF16:
  343. self.ndarray = bf16_to_fp32(self.ndarray)
  344. return UnquantizedTensor(self.ndarray.astype(dtype))
  345. def to_ggml(self) -> 'UnquantizedTensor':
  346. return self
  347. def permute_part(self, n_part: int, n_head: int) -> 'UnquantizedTensor':
  348. r = self.ndarray.shape[0] // 3
  349. return UnquantizedTensor(permute(self.ndarray[r * n_part : r * n_part + r, ...], n_head))
  350. def part(self, n_part: int) -> 'UnquantizedTensor':
  351. r = self.ndarray.shape[0] // 3
  352. return UnquantizedTensor(self.ndarray[r * n_part : r * n_part + r, ...])
  353. def permute(self, n_head: int, n_head_kv: int) -> 'UnquantizedTensor':
  354. return UnquantizedTensor(permute(self.ndarray, n_head, n_head_kv))
  355. def load_unquantized(lazy_tensor: 'LazyTensor', expected_dtype: Any = None, convert: bool = False) -> NDArray:
  356. tensor = lazy_tensor.load()
  357. assert isinstance(tensor, UnquantizedTensor)
  358. # double-check:
  359. actual_shape = list(tensor.ndarray.shape)
  360. assert actual_shape == lazy_tensor.shape, (actual_shape, lazy_tensor.shape)
  361. if expected_dtype is not None and expected_dtype != tensor.ndarray.dtype:
  362. if convert:
  363. tensor.ndarray = tensor.ndarray.astype(expected_dtype)
  364. else:
  365. raise ValueError(f'expected this tensor to have dtype {expected_dtype}, got {tensor.ndarray.dtype}')
  366. return tensor.ndarray
  367. GGMLCompatibleTensor = Union[UnquantizedTensor]
  368. class DeferredPermutedTensor(Tensor):
  369. def __init__(self, base: Tensor, n_head: int, n_head_kv: int) -> None:
  370. self.base = base
  371. self.n_head = n_head
  372. self.data_type = self.base.data_type
  373. def astype(self, data_type: DataType) -> Tensor:
  374. return self.base.astype(data_type).permute(self.n_head, self.n_head_kv)
  375. def to_ggml(self) -> GGMLCompatibleTensor:
  376. return self.base.to_ggml().permute(self.n_head, self.n_head_kv)
  377. def permute(self, n_head: int, n_head_kv: int) -> Tensor:
  378. raise Exception("shouldn't permute twice")
  379. @dataclass
  380. class LazyTensor:
  381. _load: Callable[[], Tensor]
  382. shape: List[int]
  383. data_type: DataType
  384. description: str
  385. def load(self) -> Tensor:
  386. ret = self._load()
  387. assert ret.data_type == self.data_type, (self.data_type, ret.data_type, self.description)
  388. return ret
  389. def astype(self, data_type: DataType) -> 'LazyTensor':
  390. self.validate_conversion_to(data_type)
  391. def load() -> Tensor:
  392. return self.load().astype(data_type)
  393. return LazyTensor(load, self.shape, data_type, f'convert({data_type}) {self.description}')
  394. def validate_conversion_to(self, data_type: DataType) -> None:
  395. if data_type == self.data_type:
  396. return
  397. LazyModel = Dict[str, LazyTensor]
  398. @dataclass
  399. class ModelPlus:
  400. model: LazyModel
  401. paths: List[Path] # Where this was read from.
  402. format: Literal['ggml', 'torch', 'safetensors']
  403. vocab: Optional[Vocab] # For GGML models (which have vocab built in), the vocab.
  404. def merge_sharded(models: List[LazyModel]) -> LazyModel:
  405. # Original LLaMA models have each file contain one part of each tensor.
  406. # Use a dict instead of a set to preserve order.
  407. names = {name: None for model in models for name in model}
  408. def convert(name: str) -> LazyTensor:
  409. lazy_tensors: List[LazyTensor] = [model[name] for model in models]
  410. if len(lazy_tensors) == 1:
  411. # only one file; don't go through this procedure since there might
  412. # be quantized tensors
  413. return lazy_tensors[0]
  414. if len(lazy_tensors[0].shape) == 1:
  415. # the tensor is just duplicated in every file
  416. return lazy_tensors[0]
  417. if name.startswith('tok_embeddings.') or \
  418. name.endswith('.attention.wo.weight') or \
  419. name.endswith('.feed_forward.w2.weight'):
  420. # split by columns
  421. axis = 1
  422. else:
  423. # split by rows
  424. axis = 0
  425. concatenated_shape = list(lazy_tensors[0].shape)
  426. concatenated_shape[axis] = sum(tensor.shape[axis] for tensor in lazy_tensors)
  427. def load() -> UnquantizedTensor:
  428. ndarrays = [load_unquantized(tensor) for tensor in lazy_tensors]
  429. concatenated: NDArray = np.concatenate(ndarrays, axis=axis)
  430. return UnquantizedTensor(concatenated)
  431. description = 'concatenated[[' + '] | ['.join(lt.description for lt in lazy_tensors) + ']]'
  432. return LazyTensor(load, concatenated_shape, lazy_tensors[0].data_type, description)
  433. return {name: convert(name) for name in names}
  434. def merge_multifile_models(models_plus: List[ModelPlus]) -> ModelPlus:
  435. formats = set(mp.format for mp in models_plus)
  436. assert len(formats) == 1, "different formats?"
  437. format = formats.pop()
  438. paths = [path for mp in models_plus for path in mp.paths]
  439. # Use the first non-None vocab, if any.
  440. try:
  441. vocab = next(mp.vocab for mp in models_plus if mp.vocab is not None)
  442. except StopIteration:
  443. vocab = None
  444. if any("model.embed_tokens.weight" in mp.model for mp in models_plus):
  445. # Transformers models put different tensors in different files, but
  446. # don't split indivdual tensors between files.
  447. model: LazyModel = {}
  448. for mp in models_plus:
  449. model.update(mp.model)
  450. else:
  451. model = merge_sharded([mp.model for mp in models_plus])
  452. return ModelPlus(model, paths, format, vocab)
  453. def permute_lazy(lazy_tensor: LazyTensor, n_head: int, n_head_kv: int) -> LazyTensor:
  454. def load() -> Tensor:
  455. return lazy_tensor.load().permute(n_head, n_head_kv)
  456. return LazyTensor(load, lazy_tensor.shape, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  457. def permute_part_lazy(lazy_tensor: LazyTensor, n_part: int, n_head: int) -> LazyTensor:
  458. def load() -> Tensor:
  459. return lazy_tensor.load().permute_part(n_part, n_head)
  460. s = lazy_tensor.shape.copy()
  461. s[0] = s[0] // 3
  462. return LazyTensor(load, s, lazy_tensor.data_type, f'permute({n_head}) ' + lazy_tensor.description)
  463. def part_lazy(lazy_tensor: LazyTensor, n_part: int) -> LazyTensor:
  464. def load() -> Tensor:
  465. return lazy_tensor.load().part(n_part)
  466. s = lazy_tensor.shape.copy()
  467. s[0] = s[0] // 3
  468. return LazyTensor(load, s, lazy_tensor.data_type, 'part ' + lazy_tensor.description)
  469. # Functionality that simulates `torch.load` but where individual tensors are
  470. # only loaded into memory on demand, not all at once.
  471. # PyTorch can't do this natively as of time of writing:
  472. # - https://github.com/pytorch/pytorch/issues/64327
  473. # This allows us to de-shard without multiplying RAM usage, and also
  474. # conveniently drops the PyTorch dependency (though we still need numpy).
  475. @dataclass
  476. class LazyStorageKind:
  477. data_type: DataType
  478. @dataclass
  479. class LazyStorage:
  480. load: Callable[[int, int], NDArray]
  481. kind: LazyStorageKind
  482. description: str
  483. class LazyUnpickler(pickle.Unpickler):
  484. def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile):
  485. super().__init__(fp)
  486. self.data_base_path = data_base_path
  487. self.zip_file = zip_file
  488. def persistent_load(self, pid: Any) -> Any:
  489. assert pid[0] == 'storage'
  490. assert isinstance(pid[1], LazyStorageKind)
  491. data_type = pid[1].data_type
  492. filename_stem = pid[2]
  493. filename = self.data_base_path + '/' + filename_stem
  494. info = self.zip_file.getinfo(filename)
  495. def load(offset: int, elm_count: int) -> NDArray:
  496. dtype = DATA_TYPE_TO_NUMPY.get(data_type)
  497. if dtype is None:
  498. raise Exception("tensor stored in unsupported format")
  499. fp = self.zip_file.open(info)
  500. fp.seek(offset * dtype.itemsize)
  501. size = elm_count * dtype.itemsize
  502. data = fp.read(size)
  503. assert len(data) == size
  504. return np.frombuffer(data, dtype)
  505. description = f'storage data_type={data_type} path-in-zip={filename} path={self.zip_file.filename}'
  506. return LazyStorage(load=load, kind=pid[1], description=description)
  507. # @staticmethod
  508. def lazy_rebuild_tensor_v2(storage: Any, storage_offset: Any, size: Any, stride: Any,
  509. # pyright: ignore[reportSelfClsParameterName]
  510. requires_grad: Any, backward_hooks: Any, metadata: Any = None) -> LazyTensor:
  511. assert isinstance(storage, LazyStorage)
  512. def load() -> UnquantizedTensor:
  513. elm_count = stride[0] * size[0]
  514. return UnquantizedTensor(storage.load(storage_offset, elm_count).reshape(size))
  515. description = f'pickled storage_offset={storage_offset} in {storage.description}'
  516. return LazyTensor(load, list(size), storage.kind.data_type, description)
  517. # @staticmethod
  518. def rebuild_from_type_v2(func, new_type, args, state):
  519. return func(*args)
  520. CLASSES: Dict[Any, Any] = {
  521. ('torch._tensor', '_rebuild_from_type_v2'): rebuild_from_type_v2,
  522. ('torch._utils', '_rebuild_tensor_v2'): lazy_rebuild_tensor_v2,
  523. ('torch', 'BFloat16Storage'): LazyStorageKind(DT_BF16),
  524. ('torch', 'HalfStorage'): LazyStorageKind(DT_F16),
  525. ('torch', 'FloatStorage'): LazyStorageKind(DT_F32),
  526. ('torch', 'IntStorage'): LazyStorageKind(DT_I32),
  527. ('torch', 'Tensor'): LazyTensor,
  528. }
  529. def find_class(self, module: str, name: str) -> Any:
  530. if not module.startswith('torch'):
  531. return super().find_class(module, name)
  532. return self.CLASSES[(module, name)]
  533. def lazy_load_torch_file(outer_fp: IO[bytes], path: Path) -> ModelPlus:
  534. zf = zipfile.ZipFile(outer_fp)
  535. pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')]
  536. assert len(pickle_paths) == 1, pickle_paths
  537. pickle_fp = zf.open(pickle_paths[0], 'r')
  538. unpickler = LazyUnpickler(pickle_fp,
  539. data_base_path=pickle_paths[0][:-4],
  540. zip_file=zf)
  541. model = unpickler.load()
  542. as_dict = dict(model.items())
  543. return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
  544. def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
  545. header_size, = struct.unpack('<Q', fp.read(8))
  546. header: Dict[str, Dict[str, Any]] = json.loads(fp.read(header_size))
  547. # Use mmap for the actual data to avoid race conditions with the file offset.
  548. mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
  549. byte_buf = mapped[8 + header_size:]
  550. def convert(info: Dict[str, Any]) -> LazyTensor:
  551. data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
  552. numpy_dtype = DATA_TYPE_TO_NUMPY[data_type]
  553. shape: List[int] = info['shape']
  554. begin, end = info['data_offsets']
  555. assert 0 <= begin <= end <= len(byte_buf)
  556. assert end - begin == math.prod(shape) * numpy_dtype.itemsize
  557. buf = byte_buf[begin:end]
  558. def load() -> UnquantizedTensor:
  559. return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
  560. description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
  561. return LazyTensor(load, shape, data_type, description)
  562. model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
  563. return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
  564. def must_read(fp: IO[bytes], length: int) -> bytes:
  565. ret = fp.read(length)
  566. if len(ret) < length:
  567. raise Exception("unexpectedly reached end of file")
  568. return ret
  569. @functools.lru_cache(maxsize=None)
  570. def lazy_load_file(path: Path) -> ModelPlus:
  571. fp = open(path, 'rb')
  572. first8 = fp.read(8)
  573. fp.seek(0)
  574. if first8[:2] == b'PK':
  575. # A zip file, i.e. PyTorch format
  576. return lazy_load_torch_file(fp, path)
  577. elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
  578. # Probably safetensors
  579. return lazy_load_safetensors_file(fp, path)
  580. else:
  581. raise ValueError(f"unknown format: {path}")
  582. In = TypeVar('In')
  583. Out = TypeVar('Out')
  584. def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int) -> Iterable[Out]:
  585. '''Parallel map, but with backpressure. If the caller doesn't call `next`
  586. fast enough, this will stop calling `func` at some point rather than
  587. letting results pile up in memory. Specifically, there is a max of one
  588. output value buffered per thread.'''
  589. with concurrent.futures.ThreadPoolExecutor() as executor:
  590. futures: List[concurrent.futures.Future[Out]] = []
  591. items_rev = list(iterable)[::-1]
  592. for i in range(min(concurrency, len(items_rev))):
  593. futures.append(executor.submit(func, items_rev.pop()))
  594. while futures:
  595. result = futures.pop(0).result()
  596. if items_rev:
  597. futures.append(executor.submit(func, items_rev.pop()))
  598. yield result
  599. def check_vocab_size(params: Params, vocab: Vocab) -> None:
  600. if params.n_vocab != vocab.vocab_size:
  601. assert isinstance(vocab, BpeVocab) or isinstance(vocab, SentencePieceVocab)
  602. if params.n_vocab == vocab.vocab_size_base:
  603. print("Ignoring added_tokens.json since model matches vocab size without it.")
  604. vocab.added_tokens_list = []
  605. vocab.vocab_size = vocab.vocab_size_base
  606. return
  607. msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer}"
  608. if vocab.fname_added_tokens is not None:
  609. msg += f" combined with {vocab.fname_added_tokens}"
  610. msg += f" has {vocab.vocab_size})."
  611. if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20 and vocab.fname_added_tokens is None:
  612. msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
  613. raise Exception(msg)
  614. class OutputFile:
  615. def __init__(self, fname_out: Path) -> None:
  616. self.gguf = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH])
  617. def add_meta_arch(self, params: Params) -> None:
  618. name = "LLaMA"
  619. if (params.n_ctx == 4096):
  620. name = "LLaMA v2"
  621. if params.path_model:
  622. name = str(params.path_model.parent).split('/')[-1]
  623. self.gguf.add_name (name)
  624. self.gguf.add_context_length (params.n_ctx)
  625. self.gguf.add_embedding_length (params.n_embd)
  626. self.gguf.add_block_count (params.n_layer)
  627. self.gguf.add_feed_forward_length (params.n_ff)
  628. self.gguf.add_rope_dimension_count(params.n_embd // params.n_head)
  629. self.gguf.add_head_count (params.n_head)
  630. self.gguf.add_head_count_kv (params.n_head_kv)
  631. self.gguf.add_layer_norm_rms_eps (params.f_norm_eps)
  632. if params.f_rope_freq_base:
  633. self.gguf.add_rope_freq_base(params.f_rope_freq_base)
  634. if params.f_rope_scale:
  635. self.gguf.add_rope_scale_linear(params.f_rope_scale)
  636. if params.ftype:
  637. self.gguf.add_file_type(params.ftype)
  638. def add_meta_vocab(self, vocab: Vocab) -> None:
  639. tokens = []
  640. scores = []
  641. toktypes = []
  642. # NOTE: `all_tokens` returns the the base vocabulary and added tokens
  643. # TODO: add special tokens?
  644. for text, score, toktype in vocab.all_tokens():
  645. tokens.append(text)
  646. scores.append(score)
  647. toktypes.append(toktype)
  648. self.gguf.add_tokenizer_model("llama")
  649. self.gguf.add_token_list(tokens)
  650. self.gguf.add_token_scores(scores)
  651. self.gguf.add_token_types(toktypes)
  652. def add_tensor_info(self, name: str, tensor: LazyTensor) -> None:
  653. n_elements = 1
  654. for dim in tensor.shape:
  655. n_elements *= dim
  656. data_type = DATA_TYPE_TO_NUMPY[tensor.data_type]
  657. data_nbytes = n_elements * data_type.itemsize
  658. self.gguf.add_tensor_info(name, tensor.shape, data_type, data_nbytes)
  659. def write_meta(self) -> None:
  660. self.gguf.write_header_to_file()
  661. self.gguf.write_kv_data_to_file()
  662. def write_tensor_info(self) -> None:
  663. self.gguf.write_ti_data_to_file()
  664. def close(self) -> None:
  665. self.gguf.close()
  666. @staticmethod
  667. def write_vocab_only(fname_out: Path, params: Params, vocab: Vocab) -> None:
  668. check_vocab_size(params, vocab)
  669. of = OutputFile(fname_out)
  670. # meta data
  671. of.add_meta_arch(params)
  672. of.add_meta_vocab(vocab)
  673. of.write_meta()
  674. of.close()
  675. @staticmethod
  676. def write_all(fname_out: Path, params: Params, model: LazyModel, vocab: Vocab) -> None:
  677. check_vocab_size(params, vocab)
  678. of = OutputFile(fname_out)
  679. # meta data
  680. of.add_meta_arch(params)
  681. of.add_meta_vocab(vocab)
  682. # tensor info
  683. for name, lazy_tensor in model.items():
  684. of.add_tensor_info(name, lazy_tensor)
  685. of.write_meta()
  686. of.write_tensor_info()
  687. def do_item(item: Tuple[str, LazyTensor]) -> NDArray:
  688. name, lazy_tensor = item
  689. return lazy_tensor.load().to_ggml().ndarray
  690. # tensor data
  691. ndarrays = bounded_parallel_map(do_item, model.items(), concurrency=8)
  692. for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
  693. size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
  694. padi = len(str(len(model)))
  695. print(f"[{i+1:{padi}d}/{len(model)}] Writing tensor {name:38s} | size {size:16} | type {lazy_tensor.data_type}")
  696. of.gguf.write_tensor_data(ndarray)
  697. of.close()
  698. def pick_output_type(model: LazyModel, output_type_str: Optional[str]) -> GGMLFileType:
  699. wq_type = model[NAMES[gguf.MODEL_TENSOR.ATTN_Q].format(bid=0)+".weight"].data_type
  700. if output_type_str == "f32" or (output_type_str is None and wq_type == DT_F32):
  701. return GGMLFileType.AllF32
  702. if output_type_str == "f16" or (output_type_str is None and wq_type in (DT_F16, DT_BF16)):
  703. return GGMLFileType.MostlyF16
  704. name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
  705. raise Exception(f"Unexpected combination of types: {name_to_type}")
  706. def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
  707. return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
  708. for (name, tensor) in model.items()}
  709. def convert_model_names(model: LazyModel, params: Params) -> LazyModel:
  710. tmap = gguf.get_tensor_name_map(ARCH, params.n_layer)
  711. tmp = model
  712. # HF models permut or pack some of the tensors, so we need to undo that
  713. for i in itertools.count():
  714. if f"model.layers.{i}.self_attn.q_proj.weight" in model:
  715. print(f"Permuting layer {i}")
  716. tmp[f"model.layers.{i}.self_attn.q_proj.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.q_proj.weight"], params.n_head, params.n_head)
  717. tmp[f"model.layers.{i}.self_attn.k_proj.weight"] = permute_lazy(model[f"model.layers.{i}.self_attn.k_proj.weight"], params.n_head, params.n_head_kv)
  718. #tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
  719. elif f"model.layers.{i}.self_attn.W_pack.weight" in model:
  720. print(f"Unpacking and permuting layer {i}")
  721. tmp[f"model.layers.{i}.self_attn.q_proj.weight"] = permute_part_lazy(model[f"model.layers.{i}.self_attn.W_pack.weight"], 0, params.n_head, params.n_head)
  722. tmp[f"model.layers.{i}.self_attn.k_proj.weight"] = permute_part_lazy(model[f"model.layers.{i}.self_attn.W_pack.weight"], 1, params.n_head, params.n_head_kv)
  723. tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = part_lazy (model[f"model.layers.{i}.self_attn.W_pack.weight"], 2)
  724. else:
  725. break
  726. out: LazyModel = {}
  727. for name, lazy_tensor in model.items():
  728. name_new = name
  729. if name in tmap:
  730. name_new = tmap[name]
  731. elif name.endswith(".weight") and name[:-7] in tmap:
  732. name_new = tmap[name[:-7]] + ".weight"
  733. elif name.endswith(".bias") and name[:-5] in tmap:
  734. name_new = tmap[name[:-5]] + ".bias"
  735. else:
  736. raise Exception(f"Unexpected tensor name: {name}")
  737. if gguf.should_skip_tensor_TMP(ARCH, params.n_layer, name_new):
  738. print(f"skipping tensor {name_new}")
  739. continue
  740. else:
  741. print(f"{name:48s} -> {name_new:40s} | {lazy_tensor.data_type} | {lazy_tensor.shape}")
  742. out[name_new] = lazy_tensor
  743. return out
  744. def nth_multifile_path(path: Path, n: int) -> Optional[Path]:
  745. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  746. the nth path in the model.
  747. '''
  748. # Support the following patterns:
  749. patterns: List[Tuple[str, str]] = [
  750. # - x.00.pth, x.01.pth, etc.
  751. (r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
  752. # - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
  753. (r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
  754. # x.bin, x.bin.1, etc.
  755. (r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
  756. ]
  757. for regex, replacement in patterns:
  758. if re.search(regex, path.name):
  759. new_path = path.with_name(re.sub(regex, replacement, path.name))
  760. if new_path.exists():
  761. return new_path
  762. return None
  763. def find_multifile_paths(path: Path) -> List[Path]:
  764. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  765. the whole list of paths in the model.
  766. '''
  767. ret: List[Path] = []
  768. for i in itertools.count():
  769. nth_path = nth_multifile_path(path, i)
  770. if nth_path is None:
  771. break
  772. ret.append(nth_path)
  773. if not ret:
  774. # No matches. This should only happen if the file was named, e.g.,
  775. # foo.0, and there was no file named foo. Oh well, try to process it
  776. # as a single file.
  777. return [path]
  778. return ret
  779. def load_some_model(path: Path) -> ModelPlus:
  780. '''Load a model of any supported format.'''
  781. # Be extra-friendly and accept either a file or a directory:
  782. if path.is_dir():
  783. # Check if it's a set of safetensors files first
  784. files = list(path.glob("model-00001-of-*.safetensors"))
  785. if not files:
  786. # Try the PyTorch patterns too, with lower priority
  787. globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin"]
  788. files = [file for glob in globs for file in path.glob(glob)]
  789. if not files:
  790. raise Exception(f"Can't find model in directory {path}")
  791. if len(files) > 1:
  792. raise Exception(f"Found multiple models in {path}, not sure which to pick: {files}")
  793. path = files[0]
  794. paths = find_multifile_paths(path)
  795. models_plus: List[ModelPlus] = []
  796. for path in paths:
  797. print(f"Loading model file {path}")
  798. models_plus.append(lazy_load_file(path))
  799. model_plus = merge_multifile_models(models_plus)
  800. return model_plus
  801. def load_vocab(path: Path, vocabtype: Optional[str]) -> Union[BpeVocab, SentencePieceVocab]:
  802. # Be extra-friendly and accept either a file or a directory. Also, if it's
  803. # a directory, it might be the model directory, and tokenizer.model might
  804. # be in the parent of that.
  805. if path.is_dir():
  806. vocab_file = "tokenizer.model"
  807. if vocabtype == 'bpe':
  808. vocab_file = "vocab.json"
  809. path2 = path / vocab_file
  810. # Use `.parent` instead of /.. to handle the symlink case better.
  811. path3 = path.parent / vocab_file
  812. if path2.exists():
  813. path = path2
  814. elif path3.exists():
  815. path = path3
  816. else:
  817. raise FileNotFoundError(
  818. f"Could not find {vocab_file} in {path} or its parent; "
  819. "if it's in another directory, pass the directory as --vocab-dir")
  820. print(f"Loading vocab file '{path}', type '{vocabtype}'")
  821. added_tokens_path = path.parent / "added_tokens.json"
  822. if vocabtype == "bpe":
  823. return BpeVocab(path, added_tokens_path if added_tokens_path.exists() else None)
  824. elif vocabtype == "spm":
  825. return SentencePieceVocab(path, added_tokens_path if added_tokens_path.exists() else None)
  826. else:
  827. raise ValueError(f"Unsupported vocabulary type {vocabtype}")
  828. def default_outfile(model_paths: List[Path], file_type: GGMLFileType) -> Path:
  829. namestr = {
  830. GGMLFileType.AllF32: "f32",
  831. GGMLFileType.MostlyF16: "f16",
  832. }[file_type]
  833. ret = model_paths[0].parent / f"ggml-model-{namestr}.gguf"
  834. if ret in model_paths:
  835. sys.stderr.write(
  836. f"Error: Default output path ({ret}) would overwrite the input. "
  837. "Please explicitly specify a path using --outfile.\n")
  838. sys.exit(1)
  839. return ret
  840. def do_dump_model(model_plus: ModelPlus) -> None:
  841. print(f"model_plus.paths = {model_plus.paths!r}")
  842. print(f"model_plus.format = {model_plus.format!r}")
  843. print(f"model_plus.vocab = {model_plus.vocab!r}")
  844. for name, lazy_tensor in model_plus.model.items():
  845. print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}")
  846. def main(args_in: Optional[List[str]] = None) -> None:
  847. parser = argparse.ArgumentParser(description="Convert a LLaMa model to a GGML compatible file")
  848. parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
  849. parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
  850. parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
  851. parser.add_argument("--outtype", choices=["f32", "f16"], help="output format (default: based on input)")
  852. parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
  853. parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
  854. parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.pth, *.pt, *.bin)")
  855. parser.add_argument("--vocabtype", choices=["spm", "bpe"], help="vocab format (default: spm)", default="spm")
  856. parser.add_argument("--ctx", type=int, help="model training context (default: based on input)")
  857. args = parser.parse_args(args_in)
  858. if args.dump_single:
  859. model_plus = lazy_load_file(args.model)
  860. do_dump_model(model_plus)
  861. model_plus = load_some_model(args.model)
  862. params = Params.load(model_plus)
  863. if params.n_ctx == -1:
  864. if args.ctx is None:
  865. raise Exception("The model doesn't have a context size, and you didn't specify one with --ctx\n"
  866. "Please specify one with --ctx:\n"
  867. " - LLaMA v1: --ctx 2048\n"
  868. " - LLaMA v2: --ctx 4096\n")
  869. params.n_ctx = args.ctx
  870. if args.outtype:
  871. params.ftype = {
  872. "f32": GGMLFileType.AllF32,
  873. "f16": GGMLFileType.MostlyF16,
  874. }[args.outtype]
  875. print(f"params = {params}")
  876. vocab: Vocab
  877. if args.vocab_only:
  878. vocab = load_vocab(args.vocab_dir or args.model, args.vocabtype)
  879. assert args.outfile, "need --outfile if using --vocab-only"
  880. outfile = args.outfile
  881. OutputFile.write_vocab_only(outfile, params, vocab)
  882. print(f"Wrote {outfile}")
  883. else:
  884. if args.dump:
  885. do_dump_model(model_plus)
  886. return
  887. if model_plus.vocab is not None and args.vocab_dir is None:
  888. vocab = model_plus.vocab
  889. else:
  890. vocab_dir = args.vocab_dir if args.vocab_dir else model_plus.paths[0].parent
  891. vocab = load_vocab(vocab_dir, args.vocabtype)
  892. model = model_plus.model
  893. model = convert_model_names(model, params)
  894. ftype = pick_output_type(model, args.outtype)
  895. model = convert_to_output_type(model, ftype)
  896. outfile = args.outfile or default_outfile(model_plus.paths, ftype)
  897. params.ftype = ftype
  898. print(f"Writing {outfile}, format {ftype}")
  899. OutputFile.write_all(outfile, params, model, vocab)
  900. print(f"Wrote {outfile}")
  901. if __name__ == '__main__':
  902. main()