convert.py 42 KB

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