convert.py 41 KB

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