convert.py 42 KB

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