convert.py 43 KB

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