convert.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714
  1. #!/usr/bin/env python3
  2. from __future__ import annotations
  3. import logging
  4. import argparse
  5. import concurrent.futures
  6. import enum
  7. import faulthandler
  8. import functools
  9. import itertools
  10. import json
  11. import math
  12. import mmap
  13. import os
  14. import pickle
  15. import re
  16. import signal
  17. import struct
  18. import sys
  19. import textwrap
  20. import time
  21. import zipfile
  22. from abc import ABC, abstractmethod
  23. from concurrent.futures import ProcessPoolExecutor, ThreadPoolExecutor
  24. from dataclasses import dataclass
  25. from pathlib import Path
  26. from typing import TYPE_CHECKING, Any, Callable, ClassVar, IO, Iterable, Literal, Protocol, TypeVar, runtime_checkable, Optional
  27. import numpy as np
  28. from sentencepiece import SentencePieceProcessor
  29. if 'NO_LOCAL_GGUF' not in os.environ:
  30. sys.path.insert(1, str(Path(__file__).parent / 'gguf-py'))
  31. import gguf
  32. if TYPE_CHECKING:
  33. from typing_extensions import Self, TypeAlias
  34. logger = logging.getLogger("convert")
  35. if hasattr(faulthandler, 'register') and hasattr(signal, 'SIGUSR1'):
  36. faulthandler.register(signal.SIGUSR1)
  37. NDArray: TypeAlias = 'np.ndarray[Any, Any]'
  38. ARCH = gguf.MODEL_ARCH.LLAMA
  39. DEFAULT_CONCURRENCY = 8
  40. ADDED_TOKENS_FILE = 'added_tokens.json'
  41. FAST_TOKENIZER_FILE = 'tokenizer.json'
  42. #
  43. # data types
  44. #
  45. @dataclass(frozen=True)
  46. class DataType:
  47. name: str
  48. dtype: np.dtype[Any]
  49. valid_conversions: list[str]
  50. def elements_to_bytes(self, n_elements: int) -> int:
  51. return n_elements * self.dtype.itemsize
  52. @dataclass(frozen=True)
  53. class UnquantizedDataType(DataType):
  54. pass
  55. DT_F16 = UnquantizedDataType('F16', dtype = np.dtype(np.float16), valid_conversions = ['F32', 'Q8_0'])
  56. DT_F32 = UnquantizedDataType('F32', dtype = np.dtype(np.float32), valid_conversions = ['F16', 'Q8_0'])
  57. DT_I32 = UnquantizedDataType('I32', dtype = np.dtype(np.int16), valid_conversions = [])
  58. DT_BF16 = UnquantizedDataType('BF16', dtype = np.dtype(np.uint16), valid_conversions = ['F32', 'F16', 'Q8_0'])
  59. @dataclass(frozen=True)
  60. class QuantizedDataType(DataType):
  61. block_size: int
  62. quantized_dtype: np.dtype[Any]
  63. ggml_type: gguf.GGMLQuantizationType
  64. def quantize(self, arr: NDArray) -> NDArray:
  65. raise NotImplementedError(f'Quantization for {self.name} not implemented')
  66. def elements_to_bytes(self, n_elements: int) -> int:
  67. assert n_elements % self.block_size == 0, f'Invalid number of elements {n_elements} for {self.name} with block size {self.block_size}'
  68. return self.quantized_dtype.itemsize * (n_elements // self.block_size)
  69. @dataclass(frozen=True)
  70. class Q8_0QuantizedDataType(QuantizedDataType):
  71. # Mini Q8_0 quantization in Python!
  72. def quantize(self, arr: NDArray) -> NDArray:
  73. assert arr.size % self.block_size == 0 and arr.size != 0, f'Bad array size {arr.size}'
  74. assert arr.dtype == np.float32, f'Bad array type {arr.dtype}'
  75. n_blocks = arr.size // self.block_size
  76. blocks = arr.reshape((n_blocks, self.block_size))
  77. # Much faster implementation of block quantization contributed by @Cebtenzzre
  78. def quantize_blocks_q8_0(blocks: NDArray) -> Iterable[tuple[Any, Any]]:
  79. d = abs(blocks).max(axis = 1) / np.float32(127)
  80. with np.errstate(divide = 'ignore'):
  81. qs = (blocks / d[:, None]).round()
  82. qs[d == 0] = 0
  83. yield from zip(d, qs)
  84. return np.fromiter(quantize_blocks_q8_0(blocks), count = n_blocks, dtype = self.quantized_dtype)
  85. DT_Q8_0 = Q8_0QuantizedDataType('Q8_0',
  86. dtype = np.dtype(np.float32), valid_conversions = [],
  87. ggml_type = gguf.GGMLQuantizationType.Q8_0, block_size = 32,
  88. quantized_dtype = np.dtype([('d', '<f2'), ('qs', 'i1', (32,))]))
  89. # Quantized types skipped here because they may also map to np.float32
  90. NUMPY_TYPE_TO_DATA_TYPE: dict[np.dtype[Any], DataType] = {}
  91. for dt in (DT_BF16, DT_F16, DT_F32, DT_I32):
  92. if dt.dtype in NUMPY_TYPE_TO_DATA_TYPE:
  93. raise ValueError(f'Invalid duplicate data type {dt}')
  94. NUMPY_TYPE_TO_DATA_TYPE[dt.dtype] = dt
  95. SAFETENSORS_DATA_TYPES: dict[str, DataType] = {
  96. 'BF16': DT_BF16,
  97. 'F16': DT_F16,
  98. 'F32': DT_F32,
  99. 'I32': DT_I32,
  100. }
  101. # TODO: match this with `llama_ftype`
  102. # TODO: rename to LLAMAFileType
  103. # TODO: move to `gguf.py`
  104. class GGMLFileType(enum.IntEnum):
  105. AllF32 = 0
  106. MostlyF16 = 1 # except 1d tensors
  107. MostlyQ8_0 = 7 # except 1d tensors
  108. def type_for_tensor(self, name: str, tensor: LazyTensor) -> DataType:
  109. dt = GGML_FILE_TYPE_TO_DATA_TYPE.get(self)
  110. if dt is None:
  111. raise ValueError(self)
  112. # Convert all 1D tensors to F32. Most of the codebase that takes in 1D tensors only handles F32 tensors, and most of the outputs tensors are F32.
  113. # Also The 1d tensors aren't much of a performance/size issue. So instead of having to have separate F32 and F16 implementations of both, just convert everything to F32 for now.
  114. return dt if len(tensor.shape) > 1 else DT_F32
  115. GGML_FILE_TYPE_TO_DATA_TYPE: dict[GGMLFileType, DataType] = {
  116. GGMLFileType.AllF32 : DT_F32,
  117. GGMLFileType.MostlyF16 : DT_F16,
  118. GGMLFileType.MostlyQ8_0: DT_Q8_0,
  119. }
  120. #
  121. # hparams loading
  122. #
  123. @dataclass
  124. class Params:
  125. n_vocab: int
  126. n_embd: int
  127. n_layer: int
  128. n_ctx: int
  129. n_ff: int
  130. n_head: int
  131. n_head_kv: int
  132. n_experts: int | None = None
  133. n_experts_used: int | None = None
  134. f_norm_eps: float | None = None
  135. rope_scaling_type: gguf.RopeScalingType | None = None
  136. f_rope_freq_base: float | None = None
  137. f_rope_scale: float | None = None
  138. n_orig_ctx: int | None = None
  139. rope_finetuned: bool | None = None
  140. ftype: GGMLFileType | None = None
  141. # path to the directory containing the model files
  142. path_model: Path | None = None
  143. @staticmethod
  144. def guessed(model: LazyModel) -> Params:
  145. # try transformer naming first
  146. n_vocab, n_embd = model["model.embed_tokens.weight"].shape if "model.embed_tokens.weight" in model else model["tok_embeddings.weight"].shape
  147. # try transformer naming first
  148. if "model.layers.0.self_attn.q_proj.weight" in model:
  149. n_layer = next(i for i in itertools.count() if f"model.layers.{i}.self_attn.q_proj.weight" not in model)
  150. elif "model.layers.0.self_attn.W_pack.weight" in model: # next: try baichuan naming
  151. n_layer = next(i for i in itertools.count() if f"model.layers.{i}.self_attn.W_pack.weight" not in model)
  152. else:
  153. n_layer = next(i for i in itertools.count() if f"layers.{i}.attention.wq.weight" not in model)
  154. if n_layer < 1:
  155. msg = """\
  156. failed to guess 'n_layer'. This model is unknown or unsupported.
  157. Suggestion: provide 'config.json' of the model in the same directory containing model files."""
  158. raise KeyError(textwrap.dedent(msg))
  159. n_head = n_embd // 128 # guessed
  160. n_mult = 256 # guessed
  161. # TODO: verify this
  162. n_ff = int(2 * (4 * n_embd) / 3)
  163. n_ff = n_mult * ((n_ff + n_mult - 1) // n_mult)
  164. return Params(
  165. n_vocab = n_vocab,
  166. n_embd = n_embd,
  167. n_layer = n_layer,
  168. n_ctx = -1,
  169. n_ff = n_ff,
  170. n_head = n_head,
  171. n_head_kv = n_head,
  172. f_norm_eps = 1e-5,
  173. )
  174. @staticmethod
  175. def loadHFTransformerJson(model: LazyModel, config_path: Path) -> Params:
  176. with open(config_path) as f:
  177. config = json.load(f)
  178. rope_scaling_type = f_rope_scale = n_orig_ctx = rope_finetuned = None
  179. rope_scaling = config.get("rope_scaling")
  180. if rope_scaling is not None and (typ := rope_scaling.get("type")):
  181. rope_factor = rope_scaling.get("factor")
  182. f_rope_scale = rope_factor
  183. if typ == "linear":
  184. rope_scaling_type = gguf.RopeScalingType.LINEAR
  185. elif typ == "yarn":
  186. rope_scaling_type = gguf.RopeScalingType.YARN
  187. n_orig_ctx = rope_scaling['original_max_position_embeddings']
  188. rope_finetuned = rope_scaling['finetuned']
  189. else:
  190. raise NotImplementedError(f'Unknown rope scaling type: {typ}')
  191. if "max_sequence_length" in config:
  192. n_ctx = config["max_sequence_length"]
  193. elif "max_position_embeddings" in config:
  194. n_ctx = config["max_position_embeddings"]
  195. else:
  196. msg = """\
  197. failed to guess 'n_ctx'. This model is unknown or unsupported.
  198. Suggestion: provide 'config.json' of the model in the same directory containing model files."""
  199. raise KeyError(textwrap.dedent(msg))
  200. n_experts = None
  201. n_experts_used = None
  202. if "num_local_experts" in config:
  203. n_experts = config["num_local_experts"]
  204. n_experts_used = config["num_experts_per_tok"]
  205. return Params(
  206. n_vocab = config["vocab_size"],
  207. n_embd = config["hidden_size"],
  208. n_layer = config["num_hidden_layers"],
  209. n_ctx = n_ctx,
  210. n_ff = config["intermediate_size"],
  211. n_head = (n_head := config["num_attention_heads"]),
  212. n_head_kv = config.get("num_key_value_heads", n_head),
  213. n_experts = n_experts,
  214. n_experts_used = n_experts_used,
  215. f_norm_eps = config["rms_norm_eps"],
  216. f_rope_freq_base = config.get("rope_theta"),
  217. rope_scaling_type = rope_scaling_type,
  218. f_rope_scale = f_rope_scale,
  219. n_orig_ctx = n_orig_ctx,
  220. rope_finetuned = rope_finetuned,
  221. )
  222. # LLaMA v2 70B params.json
  223. # {"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}
  224. @staticmethod
  225. def loadOriginalParamsJson(model: LazyModel, config_path: Path) -> Params:
  226. with open(config_path) as f:
  227. config = json.load(f)
  228. n_experts = None
  229. n_experts_used = None
  230. f_rope_freq_base = None
  231. n_ff = None
  232. # hack to determine LLaMA v1 vs v2 vs CodeLlama
  233. if config.get("moe"):
  234. # Mixtral
  235. n_ctx = 32768
  236. elif config.get("rope_theta") == 1000000:
  237. # CodeLlama
  238. n_ctx = 16384
  239. elif config["norm_eps"] == 1e-05:
  240. # LLaMA v2
  241. n_ctx = 4096
  242. else:
  243. # LLaMA v1
  244. n_ctx = 2048
  245. if "layers.0.feed_forward.w1.weight" in model:
  246. n_ff = model["layers.0.feed_forward.w1.weight"].shape[0]
  247. if config.get("moe"):
  248. n_ff = model["layers.0.feed_forward.experts.0.w1.weight"].shape[0]
  249. n_experts = config["moe"]["num_experts"]
  250. n_experts_used = config["moe"]["num_experts_per_tok"]
  251. f_rope_freq_base = 1e6
  252. assert n_ff is not None
  253. return Params(
  254. n_vocab = model["tok_embeddings.weight"].shape[0],
  255. n_embd = config["dim"],
  256. n_layer = config["n_layers"],
  257. n_ctx = n_ctx,
  258. n_ff = n_ff,
  259. n_head = (n_head := config["n_heads"]),
  260. n_head_kv = config.get("n_kv_heads", n_head),
  261. n_experts = n_experts,
  262. n_experts_used = n_experts_used,
  263. f_norm_eps = config["norm_eps"],
  264. f_rope_freq_base = config.get("rope_theta", f_rope_freq_base),
  265. )
  266. @staticmethod
  267. def load(model_plus: ModelPlus) -> Params:
  268. hf_config_path = model_plus.paths[0].parent / "config.json"
  269. orig_config_path = model_plus.paths[0].parent / "params.json"
  270. if hf_config_path.exists():
  271. params = Params.loadHFTransformerJson(model_plus.model, hf_config_path)
  272. elif orig_config_path.exists():
  273. params = Params.loadOriginalParamsJson(model_plus.model, orig_config_path)
  274. elif model_plus.format != 'none':
  275. params = Params.guessed(model_plus.model)
  276. else:
  277. raise ValueError('Cannot guess params when model format is none')
  278. params.path_model = model_plus.paths[0].parent
  279. return params
  280. @dataclass
  281. class Metadata:
  282. name: Optional[str] = None
  283. author: Optional[str] = None
  284. version: Optional[str] = None
  285. url: Optional[str] = None
  286. description: Optional[str] = None
  287. licence: Optional[str] = None
  288. source_url: Optional[str] = None
  289. source_hf_repo: Optional[str] = None
  290. @staticmethod
  291. def load(metadata_path: Path) -> Metadata:
  292. if metadata_path is None or not metadata_path.exists():
  293. return Metadata()
  294. with open(metadata_path, 'r') as file:
  295. data = json.load(file)
  296. # Create a new Metadata instance
  297. metadata = Metadata()
  298. # Assigning values to Metadata attributes if they exist in the JSON file
  299. # This is based on LLM_KV_NAMES mapping in llama.cpp
  300. metadata.name = data.get("general.name")
  301. metadata.author = data.get("general.author")
  302. metadata.version = data.get("general.version")
  303. metadata.url = data.get("general.url")
  304. metadata.description = data.get("general.description")
  305. metadata.license = data.get("general.license")
  306. metadata.source_url = data.get("general.source.url")
  307. metadata.source_hf_repo = data.get("general.source.huggingface.repository")
  308. return metadata
  309. #
  310. # vocab
  311. #
  312. @runtime_checkable
  313. class BaseVocab(Protocol):
  314. tokenizer_model: ClassVar[str]
  315. name: ClassVar[str]
  316. class NoVocab(BaseVocab):
  317. tokenizer_model = "no_vocab"
  318. name = "no_vocab"
  319. def __repr__(self) -> str:
  320. return "<NoVocab for a model without integrated vocabulary>"
  321. @runtime_checkable
  322. class Vocab(BaseVocab, Protocol):
  323. vocab_size: int
  324. added_tokens_dict: dict[str, int]
  325. added_tokens_list: list[str]
  326. fname_tokenizer: Path
  327. def __init__(self, base_path: Path): ...
  328. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]: ...
  329. class BpeVocab(Vocab):
  330. tokenizer_model = "gpt2"
  331. name = "bpe"
  332. def __init__(self, base_path: Path):
  333. added_tokens: dict[str, int] = {}
  334. if (fname_tokenizer := base_path / 'vocab.json').exists():
  335. # "slow" tokenizer
  336. with open(fname_tokenizer, encoding="utf-8") as f:
  337. self.vocab = json.load(f)
  338. try:
  339. # FIXME: Verify that added tokens here _cannot_ overlap with the main vocab.
  340. with open(base_path / ADDED_TOKENS_FILE, encoding="utf-8") as f:
  341. added_tokens = json.load(f)
  342. except FileNotFoundError:
  343. pass
  344. else:
  345. # "fast" tokenizer
  346. fname_tokenizer = base_path / FAST_TOKENIZER_FILE
  347. # if this fails, FileNotFoundError propagates to caller
  348. with open(fname_tokenizer, encoding="utf-8") as f:
  349. tokenizer_json = json.load(f)
  350. tokenizer_model: dict[str, Any] = tokenizer_json['model']
  351. if (
  352. tokenizer_model['type'] != 'BPE' or tokenizer_model.get('byte_fallback', False)
  353. or tokenizer_json['decoder']['type'] != 'ByteLevel'
  354. ):
  355. raise FileNotFoundError('Cannot find GPT-2 BPE tokenizer')
  356. self.vocab = tokenizer_model["vocab"]
  357. if (added := tokenizer_json.get('added_tokens')) is not None:
  358. # Added tokens here can be duplicates of the main vocabulary.
  359. added_tokens = {item['content']: item['id']
  360. for item in added
  361. if item['content'] not in self.vocab}
  362. vocab_size = len(self.vocab)
  363. expected_ids = list(range(vocab_size, vocab_size + len(added_tokens)))
  364. actual_ids = sorted(added_tokens.values())
  365. if expected_ids != actual_ids:
  366. expected_end_id = vocab_size + len(actual_ids) - 1
  367. raise ValueError(f"Expected the {len(actual_ids)} added token ID(s) to be sequential in the range "
  368. f"{vocab_size} - {expected_end_id}; got {actual_ids}")
  369. items = sorted(added_tokens.items(), key=lambda text_idx: text_idx[1])
  370. self.added_tokens_dict = added_tokens
  371. self.added_tokens_list = [text for (text, idx) in items]
  372. self.vocab_size_base = vocab_size
  373. self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
  374. self.fname_tokenizer = fname_tokenizer
  375. def bpe_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  376. reverse_vocab = {id: encoded_tok for encoded_tok, id in self.vocab.items()}
  377. for i, _ in enumerate(self.vocab):
  378. yield reverse_vocab[i], 0.0, gguf.TokenType.NORMAL
  379. def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  380. for text in self.added_tokens_list:
  381. score = -1000.0
  382. yield text.encode("utf-8"), score, gguf.TokenType.CONTROL
  383. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  384. yield from self.bpe_tokens()
  385. yield from self.added_tokens()
  386. def __repr__(self) -> str:
  387. return f"<BpeVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  388. class SentencePieceVocab(Vocab):
  389. tokenizer_model = "llama"
  390. name = "spm"
  391. def __init__(self, base_path: Path):
  392. added_tokens: dict[str, int] = {}
  393. if (fname_tokenizer := base_path / 'tokenizer.model').exists():
  394. # normal location
  395. try:
  396. with open(base_path / ADDED_TOKENS_FILE, encoding="utf-8") as f:
  397. added_tokens = json.load(f)
  398. except FileNotFoundError:
  399. pass
  400. elif not (fname_tokenizer := base_path.parent / 'tokenizer.model').exists():
  401. # not found in alternate location either
  402. raise FileNotFoundError('Cannot find tokenizer.model')
  403. self.sentencepiece_tokenizer = SentencePieceProcessor()
  404. self.sentencepiece_tokenizer.LoadFromFile(str(fname_tokenizer))
  405. vocab_size = self.sentencepiece_tokenizer.vocab_size()
  406. new_tokens = {id: piece for piece, id in added_tokens.items() if id >= vocab_size}
  407. expected_new_ids = list(range(vocab_size, vocab_size + len(new_tokens)))
  408. actual_new_ids = sorted(new_tokens.keys())
  409. if expected_new_ids != actual_new_ids:
  410. raise ValueError(f"Expected new token IDs {expected_new_ids} to be sequential; got {actual_new_ids}")
  411. # Token pieces that were added to the base vocabulary.
  412. self.added_tokens_dict = added_tokens
  413. self.added_tokens_list = [new_tokens[id] for id in actual_new_ids]
  414. self.vocab_size_base = vocab_size
  415. self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
  416. self.fname_tokenizer = fname_tokenizer
  417. def sentencepiece_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  418. tokenizer = self.sentencepiece_tokenizer
  419. for i in range(tokenizer.vocab_size()):
  420. piece = tokenizer.IdToPiece(i)
  421. text = piece.encode("utf-8")
  422. score: float = tokenizer.GetScore(i)
  423. toktype = gguf.TokenType.NORMAL
  424. if tokenizer.IsUnknown(i):
  425. toktype = gguf.TokenType.UNKNOWN
  426. if tokenizer.IsControl(i):
  427. toktype = gguf.TokenType.CONTROL
  428. # NOTE: I think added_tokens are user defined.
  429. # ref: https://github.com/google/sentencepiece/blob/master/src/sentencepiece_model.proto
  430. # if tokenizer.is_user_defined(i): toktype = gguf.TokenType.USER_DEFINED
  431. if tokenizer.IsUnused(i):
  432. toktype = gguf.TokenType.UNUSED
  433. if tokenizer.IsByte(i):
  434. toktype = gguf.TokenType.BYTE
  435. yield text, score, toktype
  436. def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  437. for text in self.added_tokens_list:
  438. score = -1000.0
  439. yield text.encode("utf-8"), score, gguf.TokenType.USER_DEFINED
  440. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  441. yield from self.sentencepiece_tokens()
  442. yield from self.added_tokens()
  443. def __repr__(self) -> str:
  444. return f"<SentencePieceVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  445. class LlamaHfVocab(Vocab):
  446. tokenizer_model = "llama"
  447. name = "hfft"
  448. def __init__(self, base_path: Path):
  449. fname_tokenizer = base_path / FAST_TOKENIZER_FILE
  450. # if this fails, FileNotFoundError propagates to caller
  451. with open(fname_tokenizer, encoding='utf-8') as f:
  452. tokenizer_json = json.load(f)
  453. # pre-check so we know if we need transformers
  454. tokenizer_model: dict[str, Any] = tokenizer_json['model']
  455. is_llama3 = (
  456. tokenizer_model['type'] == 'BPE' and tokenizer_model.get('ignore_merges', False)
  457. and not tokenizer_model.get('byte_fallback', True)
  458. )
  459. if is_llama3:
  460. raise TypeError('Llama 3 must be converted with BpeVocab')
  461. if not is_llama3 and (
  462. tokenizer_model['type'] != 'BPE' or not tokenizer_model.get('byte_fallback', False)
  463. or tokenizer_json['decoder']['type'] != 'Sequence'
  464. ):
  465. raise FileNotFoundError('Cannot find Llama BPE tokenizer')
  466. try:
  467. from transformers import AutoTokenizer
  468. except ImportError as e:
  469. raise ImportError(
  470. "To use LlamaHfVocab, please install the `transformers` package. "
  471. "You can install it with `pip install transformers`."
  472. ) from e
  473. # Allow the tokenizer to default to slow or fast versions.
  474. # Explicitly set tokenizer to use local paths.
  475. self.tokenizer = AutoTokenizer.from_pretrained(
  476. base_path,
  477. cache_dir=base_path,
  478. local_files_only=True,
  479. )
  480. assert self.tokenizer.is_fast # assume tokenizer.json is used
  481. # Initialize lists and dictionaries for added tokens
  482. self.added_tokens_list = []
  483. self.added_tokens_dict = dict()
  484. self.added_tokens_ids = set()
  485. # Process added tokens
  486. for tok, tokidx in sorted(
  487. self.tokenizer.get_added_vocab().items(), key=lambda x: x[1]
  488. ):
  489. # Only consider added tokens that are not in the base vocabulary
  490. if tokidx >= self.tokenizer.vocab_size:
  491. self.added_tokens_list.append(tok)
  492. self.added_tokens_dict[tok] = tokidx
  493. self.added_tokens_ids.add(tokidx)
  494. # Store special tokens and their IDs
  495. self.specials = {
  496. tok: self.tokenizer.get_vocab()[tok]
  497. for tok in self.tokenizer.all_special_tokens
  498. }
  499. self.special_ids = set(self.tokenizer.all_special_ids)
  500. # Set vocabulary sizes
  501. self.vocab_size_base = self.tokenizer.vocab_size
  502. self.vocab_size = self.vocab_size_base + len(self.added_tokens_list)
  503. self.fname_tokenizer = fname_tokenizer
  504. def hf_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  505. reverse_vocab = {
  506. id: encoded_tok for encoded_tok, id in self.tokenizer.get_vocab().items()
  507. }
  508. for token_id in range(self.vocab_size_base):
  509. # Skip processing added tokens here
  510. if token_id in self.added_tokens_ids:
  511. continue
  512. # Convert token text to bytes
  513. token_text = reverse_vocab[token_id].encode("utf-8")
  514. # Yield token text, score, and type
  515. yield token_text, self.get_token_score(token_id), self.get_token_type(
  516. token_id, token_text, self.special_ids # Reuse already stored special IDs
  517. )
  518. def get_token_type(self, token_id: int, token_text: bytes, special_ids: set[int]) -> gguf.TokenType:
  519. # Special case for byte tokens
  520. if re.fullmatch(br"<0x[0-9A-Fa-f]{2}>", token_text):
  521. return gguf.TokenType.BYTE
  522. # Determine token type based on whether it's a special token
  523. return gguf.TokenType.CONTROL if token_id in special_ids else gguf.TokenType.NORMAL
  524. def get_token_score(self, token_id: int) -> float:
  525. # Placeholder for actual logic to determine the token's score
  526. # This needs to be implemented based on specific requirements
  527. return -1000.0 # Default score
  528. def added_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  529. for text in self.added_tokens_list:
  530. if text in self.specials:
  531. toktype = self.get_token_type(self.specials[text], b'', self.special_ids)
  532. score = self.get_token_score(self.specials[text])
  533. else:
  534. toktype = gguf.TokenType.USER_DEFINED
  535. score = -1000.0
  536. yield text.encode("utf-8"), score, toktype
  537. def has_newline_token(self):
  538. return "<0x0A>" in self.tokenizer.vocab or "\n" in self.tokenizer.vocab
  539. def all_tokens(self) -> Iterable[tuple[bytes, float, gguf.TokenType]]:
  540. yield from self.hf_tokens()
  541. yield from self.added_tokens()
  542. def __repr__(self) -> str:
  543. return f"<LlamaHfVocab with {self.vocab_size_base} base tokens and {len(self.added_tokens_list)} added tokens>"
  544. #
  545. # data loading
  546. # TODO: reuse (probably move to gguf.py?)
  547. #
  548. def permute(weights: NDArray, n_head: int, n_head_kv: int) -> NDArray:
  549. if n_head_kv is not None and n_head != n_head_kv:
  550. n_head = n_head_kv
  551. return (weights.reshape(n_head, 2, weights.shape[0] // n_head // 2, *weights.shape[1:])
  552. .swapaxes(1, 2)
  553. .reshape(weights.shape))
  554. class Tensor(ABC):
  555. ndarray: NDArray
  556. data_type: DataType
  557. @abstractmethod
  558. def astype(self, data_type: DataType) -> Self: ...
  559. @abstractmethod
  560. def permute(self, n_head: int, n_head_kv: int) -> Self: ...
  561. @abstractmethod
  562. def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> Self: ...
  563. @abstractmethod
  564. def part(self, n_part: int) -> Self: ...
  565. @abstractmethod
  566. def to_ggml(self) -> GGMLCompatibleTensor: ...
  567. def bf16_to_fp32(bf16_arr: np.ndarray[Any, np.dtype[np.uint16]]) -> NDArray:
  568. assert bf16_arr.dtype == np.uint16, f"Input array should be of dtype uint16, but got {bf16_arr.dtype}"
  569. fp32_arr = bf16_arr.astype(np.uint32) << 16
  570. return fp32_arr.view(np.float32)
  571. class UnquantizedTensor(Tensor):
  572. def __init__(self, ndarray: NDArray):
  573. assert isinstance(ndarray, np.ndarray)
  574. self.ndarray = ndarray
  575. self.data_type = NUMPY_TYPE_TO_DATA_TYPE[ndarray.dtype]
  576. def astype(self, data_type: DataType) -> UnquantizedTensor:
  577. dtype = data_type.dtype
  578. if self.data_type == DT_BF16:
  579. self.ndarray = bf16_to_fp32(self.ndarray)
  580. return UnquantizedTensor(self.ndarray.astype(dtype))
  581. def to_ggml(self) -> Self:
  582. return self
  583. def permute_part(self, n_part: int, n_head: int, n_head_kv: int) -> UnquantizedTensor:
  584. r = self.ndarray.shape[0] // 3
  585. return UnquantizedTensor(permute(self.ndarray[r * n_part : r * n_part + r, ...], n_head, n_head_kv))
  586. def part(self, n_part: int) -> UnquantizedTensor:
  587. r = self.ndarray.shape[0] // 3
  588. return UnquantizedTensor(self.ndarray[r * n_part : r * n_part + r, ...])
  589. def permute(self, n_head: int, n_head_kv: int) -> UnquantizedTensor:
  590. return UnquantizedTensor(permute(self.ndarray, n_head, n_head_kv))
  591. def load_unquantized(lazy_tensor: LazyTensor, expected_dtype: Any = None, convert: bool = False) -> NDArray:
  592. tensor = lazy_tensor.load()
  593. assert isinstance(tensor, UnquantizedTensor)
  594. # double-check:
  595. actual_shape = list(tensor.ndarray.shape)
  596. assert actual_shape == lazy_tensor.shape, (actual_shape, lazy_tensor.shape)
  597. if expected_dtype is not None and expected_dtype != tensor.ndarray.dtype:
  598. if convert:
  599. tensor.ndarray = tensor.ndarray.astype(expected_dtype)
  600. else:
  601. raise ValueError(f'expected this tensor to have dtype {expected_dtype}, got {tensor.ndarray.dtype}')
  602. return tensor.ndarray
  603. GGMLCompatibleTensor = UnquantizedTensor
  604. @dataclass
  605. class LazyTensor:
  606. _load: Callable[[], Tensor]
  607. shape: list[int]
  608. data_type: DataType
  609. description: str
  610. def load(self) -> Tensor:
  611. ret = self._load()
  612. # Should be okay if it maps to the same numpy type?
  613. assert ret.data_type == self.data_type or (self.data_type.dtype == ret.data_type.dtype), \
  614. (self.data_type, ret.data_type, self.description)
  615. return ret
  616. def astype(self, data_type: DataType) -> LazyTensor:
  617. self.validate_conversion_to(data_type)
  618. def load() -> Tensor:
  619. return self.load().astype(data_type)
  620. return LazyTensor(load, self.shape, data_type, f'convert({data_type}) {self.description}')
  621. def validate_conversion_to(self, data_type: DataType) -> None:
  622. if data_type != self.data_type and data_type.name not in self.data_type.valid_conversions:
  623. raise ValueError(f'Cannot validate conversion from {self.data_type} to {data_type}.')
  624. LazyModel: TypeAlias = 'dict[str, LazyTensor]'
  625. @dataclass
  626. class ModelPlus:
  627. model: LazyModel
  628. paths: list[Path] # Where this was read from.
  629. format: Literal['ggml', 'torch', 'safetensors', 'none']
  630. vocab: BaseVocab | None # For GGML models (which have vocab built in), the vocab.
  631. def merge_sharded(models: list[LazyModel]) -> LazyModel:
  632. # Original LLaMA models have each file contain one part of each tensor.
  633. # Use a dict instead of a set to preserve order.
  634. names = {name: None for model in models for name in model}
  635. def convert(name: str) -> LazyTensor:
  636. lazy_tensors = [model[name] for model in models]
  637. if len(lazy_tensors) == 1:
  638. # only one file; don't go through this procedure since there might
  639. # be quantized tensors
  640. return lazy_tensors[0]
  641. if len(lazy_tensors[0].shape) == 1:
  642. # the tensor is just duplicated in every file
  643. return lazy_tensors[0]
  644. if name.startswith('tok_embeddings.') or \
  645. name.endswith('.attention.wo.weight') or \
  646. name.endswith('.feed_forward.w2.weight'):
  647. # split by columns
  648. axis = 1
  649. else:
  650. # split by rows
  651. axis = 0
  652. concatenated_shape = list(lazy_tensors[0].shape)
  653. concatenated_shape[axis] = sum(tensor.shape[axis] for tensor in lazy_tensors)
  654. def load() -> UnquantizedTensor:
  655. ndarrays = [load_unquantized(tensor) for tensor in lazy_tensors]
  656. concatenated = np.concatenate(ndarrays, axis=axis)
  657. return UnquantizedTensor(concatenated)
  658. description = 'concatenated[[' + '] | ['.join(lt.description for lt in lazy_tensors) + ']]'
  659. return LazyTensor(load, concatenated_shape, lazy_tensors[0].data_type, description)
  660. return {name: convert(name) for name in names}
  661. def merge_multifile_models(models_plus: list[ModelPlus]) -> ModelPlus:
  662. formats = set(mp.format for mp in models_plus)
  663. assert len(formats) == 1, "different formats?"
  664. format = formats.pop()
  665. paths = [path for mp in models_plus for path in mp.paths]
  666. # Use the first non-None vocab, if any.
  667. try:
  668. vocab = next(mp.vocab for mp in models_plus if mp.vocab is not None)
  669. except StopIteration:
  670. vocab = None
  671. if any("model.embed_tokens.weight" in mp.model for mp in models_plus):
  672. # Transformers models put different tensors in different files, but
  673. # don't split individual tensors between files.
  674. model: LazyModel = {}
  675. for mp in models_plus:
  676. model.update(mp.model)
  677. else:
  678. model = merge_sharded([mp.model for mp in models_plus])
  679. return ModelPlus(model, paths, format, vocab) # pytype: disable=wrong-arg-types
  680. def permute_lazy(lazy_tensor: LazyTensor, n_head: int, n_head_kv: int) -> LazyTensor:
  681. def load() -> Tensor:
  682. return lazy_tensor.load().permute(n_head, n_head_kv)
  683. return LazyTensor(load, lazy_tensor.shape, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  684. def permute_part_lazy(lazy_tensor: LazyTensor, n_part: int, n_head: int, n_head_kv: int) -> LazyTensor:
  685. def load() -> Tensor:
  686. return lazy_tensor.load().permute_part(n_part, n_head, n_head_kv)
  687. s = lazy_tensor.shape.copy()
  688. s[0] = s[0] // 3
  689. return LazyTensor(load, s, lazy_tensor.data_type, f'permute({n_head}, {n_head_kv}) ' + lazy_tensor.description)
  690. def part_lazy(lazy_tensor: LazyTensor, n_part: int) -> LazyTensor:
  691. def load() -> Tensor:
  692. return lazy_tensor.load().part(n_part)
  693. s = lazy_tensor.shape.copy()
  694. s[0] = s[0] // 3
  695. return LazyTensor(load, s, lazy_tensor.data_type, 'part ' + lazy_tensor.description)
  696. def pack_experts_lazy(lazy_tensors: list[LazyTensor]) -> LazyTensor:
  697. def load() -> Tensor:
  698. tensors = [lazy_tensor.load() for lazy_tensor in lazy_tensors]
  699. return UnquantizedTensor(np.array([tensor.ndarray for tensor in tensors]))
  700. s = lazy_tensors[0].shape.copy()
  701. s.insert(0, len(lazy_tensors))
  702. return LazyTensor(load, s, lazy_tensors[0].data_type, 'pack_experts ' + ' | '.join(lt.description for lt in lazy_tensors))
  703. # Functionality that simulates `torch.load` but where individual tensors are
  704. # only loaded into memory on demand, not all at once.
  705. # PyTorch can't do this natively as of time of writing:
  706. # - https://github.com/pytorch/pytorch/issues/64327
  707. # This allows us to de-shard without multiplying RAM usage, and also
  708. # conveniently drops the PyTorch dependency (though we still need numpy).
  709. @dataclass
  710. class LazyStorageKind:
  711. data_type: DataType
  712. @dataclass
  713. class LazyStorage:
  714. load: Callable[[int, int], NDArray]
  715. kind: LazyStorageKind
  716. description: str
  717. class LazyUnpickler(pickle.Unpickler):
  718. def __init__(self, fp: IO[bytes], data_base_path: str, zip_file: zipfile.ZipFile):
  719. super().__init__(fp)
  720. self.data_base_path = data_base_path
  721. self.zip_file = zip_file
  722. def persistent_load(self, pid: Any) -> Any:
  723. assert pid[0] == 'storage'
  724. assert isinstance(pid[1], LazyStorageKind)
  725. data_type = pid[1].data_type
  726. filename_stem = pid[2]
  727. filename = f'{self.data_base_path}/{filename_stem}'
  728. info = self.zip_file.getinfo(filename)
  729. def load(offset: int, elm_count: int) -> NDArray:
  730. dtype = data_type.dtype
  731. with self.zip_file.open(info) as fp:
  732. fp.seek(offset * dtype.itemsize)
  733. size = elm_count * dtype.itemsize
  734. data = fp.read(size)
  735. assert len(data) == size
  736. return np.frombuffer(data, dtype)
  737. description = f'storage data_type={data_type} path-in-zip={filename} path={self.zip_file.filename}'
  738. return LazyStorage(load=load, kind=pid[1], description=description)
  739. @staticmethod
  740. def lazy_rebuild_tensor_v2(storage: Any, storage_offset: Any, size: Any, stride: Any,
  741. requires_grad: Any, backward_hooks: Any, metadata: Any = None) -> LazyTensor:
  742. assert isinstance(storage, LazyStorage)
  743. def load() -> UnquantizedTensor:
  744. elm_count = stride[0] * size[0]
  745. return UnquantizedTensor(storage.load(storage_offset, elm_count).reshape(size))
  746. description = f'pickled storage_offset={storage_offset} in {storage.description}'
  747. return LazyTensor(load, list(size), storage.kind.data_type, description)
  748. @staticmethod
  749. def rebuild_from_type_v2(func, new_type, args, state):
  750. return func(*args)
  751. CLASSES: dict[tuple[str, str], type[LazyTensor] | LazyStorageKind] = {
  752. # getattr used here as a workaround for mypy not being smart enough to determine
  753. # the staticmethods have a __func__ attribute.
  754. ('torch._tensor', '_rebuild_from_type_v2'): getattr(rebuild_from_type_v2, '__func__'),
  755. ('torch._utils', '_rebuild_tensor_v2'): getattr(lazy_rebuild_tensor_v2, '__func__'),
  756. ('torch', 'BFloat16Storage'): LazyStorageKind(DT_BF16),
  757. ('torch', 'HalfStorage'): LazyStorageKind(DT_F16),
  758. ('torch', 'FloatStorage'): LazyStorageKind(DT_F32),
  759. ('torch', 'IntStorage'): LazyStorageKind(DT_I32),
  760. ('torch', 'Tensor'): LazyTensor,
  761. }
  762. def find_class(self, module: str, name: str) -> Any:
  763. if not module.startswith('torch'):
  764. return super().find_class(module, name)
  765. return self.CLASSES[(module, name)]
  766. def lazy_load_torch_file(outer_fp: IO[bytes], path: Path) -> ModelPlus:
  767. zf = zipfile.ZipFile(outer_fp)
  768. pickle_paths = [name for name in zf.namelist() if name.endswith('.pkl')]
  769. assert len(pickle_paths) == 1, pickle_paths
  770. pickle_fp = zf.open(pickle_paths[0], 'r')
  771. unpickler = LazyUnpickler(pickle_fp,
  772. data_base_path=pickle_paths[0][:-4],
  773. zip_file=zf)
  774. model = unpickler.load()
  775. if 'model' in model: model = model['model']
  776. as_dict = dict(model.items())
  777. return ModelPlus(model=as_dict, paths=[path], format='torch', vocab=None)
  778. def lazy_load_safetensors_file(fp: IO[bytes], path: Path) -> ModelPlus:
  779. header_size, = struct.unpack('<Q', fp.read(8))
  780. header: dict[str, dict[str, Any]] = json.loads(fp.read(header_size))
  781. # Use mmap for the actual data to avoid race conditions with the file offset.
  782. mapped = memoryview(mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ))
  783. byte_buf = mapped[8 + header_size:]
  784. def convert(info: dict[str, Any]) -> LazyTensor:
  785. data_type = SAFETENSORS_DATA_TYPES[info['dtype']]
  786. numpy_dtype = data_type.dtype
  787. shape: list[int] = info['shape']
  788. begin, end = info['data_offsets']
  789. assert 0 <= begin <= end <= len(byte_buf)
  790. assert end - begin == math.prod(shape) * numpy_dtype.itemsize
  791. buf = byte_buf[begin:end]
  792. def load() -> UnquantizedTensor:
  793. return UnquantizedTensor(np.frombuffer(buf, dtype=numpy_dtype).reshape(shape))
  794. description = f'safetensors begin={begin} end={end} type={data_type} path={path}'
  795. return LazyTensor(load, shape, data_type, description)
  796. model = {name: convert(info) for (name, info) in header.items() if name != '__metadata__'}
  797. return ModelPlus(model=model, paths=[path], format='safetensors', vocab=None)
  798. def must_read(fp: IO[bytes], length: int) -> bytes:
  799. ret = fp.read(length)
  800. if len(ret) < length:
  801. raise EOFError("unexpectedly reached end of file")
  802. return ret
  803. @functools.lru_cache(maxsize=None)
  804. def lazy_load_file(path: Path) -> ModelPlus:
  805. fp = open(path, 'rb')
  806. first8 = fp.read(8)
  807. fp.seek(0)
  808. if first8[:2] == b'PK':
  809. # A zip file, i.e. PyTorch format
  810. return lazy_load_torch_file(fp, path)
  811. elif struct.unpack('<Q', first8)[0] < 16 * 1024 * 1024:
  812. # Probably safetensors
  813. return lazy_load_safetensors_file(fp, path)
  814. else:
  815. raise ValueError(f"unknown format: {path}")
  816. In = TypeVar('In')
  817. Out = TypeVar('Out')
  818. def bounded_parallel_map(func: Callable[[In], Out], iterable: Iterable[In], concurrency: int, max_workers: int | None = None, use_processpool_executor: bool = False) -> Iterable[Out]:
  819. '''Parallel map, but with backpressure. If the caller doesn't call `next`
  820. fast enough, this will stop calling `func` at some point rather than
  821. letting results pile up in memory. Specifically, there is a max of one
  822. output value buffered per thread.'''
  823. if concurrency < 2:
  824. yield from map(func, iterable)
  825. # Not reached.
  826. iterable = iter(iterable)
  827. executor_class: type[ThreadPoolExecutor] | type[ProcessPoolExecutor]
  828. if use_processpool_executor:
  829. executor_class = ProcessPoolExecutor
  830. else:
  831. executor_class = ThreadPoolExecutor
  832. with executor_class(max_workers=max_workers) as executor:
  833. futures: list[concurrent.futures.Future[Out]] = []
  834. done = False
  835. for _ in range(concurrency):
  836. try:
  837. futures.append(executor.submit(func, next(iterable)))
  838. except StopIteration:
  839. done = True
  840. break
  841. while futures:
  842. result = futures.pop(0).result()
  843. while not done and len(futures) < concurrency:
  844. try:
  845. futures.append(executor.submit(func, next(iterable)))
  846. except StopIteration:
  847. done = True
  848. break
  849. yield result
  850. def check_vocab_size(params: Params, vocab: BaseVocab, pad_vocab: bool = False) -> None:
  851. # Handle special case where the model's vocab size is not set
  852. if params.n_vocab == -1:
  853. raise ValueError(
  854. "The model's vocab size is set to -1 in params.json. Please update it manually."
  855. + (f" Maybe {vocab.vocab_size}?" if isinstance(vocab, Vocab) else ""),
  856. )
  857. if not isinstance(vocab, Vocab):
  858. return # model has no vocab
  859. # Check for a vocab size mismatch
  860. if params.n_vocab == vocab.vocab_size:
  861. logger.warning("Ignoring added_tokens.json since model matches vocab size without it.")
  862. return
  863. if pad_vocab and params.n_vocab > vocab.vocab_size:
  864. pad_count = params.n_vocab - vocab.vocab_size
  865. logger.debug(
  866. f"Padding vocab with {pad_count} token(s) - <dummy00001> through <dummy{pad_count:05}>"
  867. )
  868. for i in range(1, pad_count + 1):
  869. vocab.added_tokens_dict[f"<dummy{i:05}>"] = -1
  870. vocab.added_tokens_list.append(f"<dummy{i:05}>")
  871. vocab.vocab_size = params.n_vocab
  872. return
  873. msg = f"Vocab size mismatch (model has {params.n_vocab}, but {vocab.fname_tokenizer} has {vocab.vocab_size})."
  874. if vocab.vocab_size < params.n_vocab < vocab.vocab_size + 20:
  875. msg += f" Most likely you are missing added_tokens.json (should be in {vocab.fname_tokenizer.parent})."
  876. if vocab.vocab_size < params.n_vocab:
  877. msg += " Add the --pad-vocab option and try again."
  878. raise ValueError(msg)
  879. class OutputFile:
  880. def __init__(self, fname_out: Path, endianess:gguf.GGUFEndian = gguf.GGUFEndian.LITTLE):
  881. self.gguf = gguf.GGUFWriter(fname_out, gguf.MODEL_ARCH_NAMES[ARCH], endianess=endianess)
  882. def add_meta_model(self, params: Params, metadata: Metadata) -> None:
  883. # Metadata About The Model And Its Provenence
  884. name = "LLaMA"
  885. if metadata is not None and metadata.name is not None:
  886. name = metadata.name
  887. elif params.path_model is not None:
  888. name = str(params.path_model.parent).split("/")[-1]
  889. elif params.n_ctx == 4096:
  890. # Heuristic detection of LLaMA v2 model
  891. name = "LLaMA v2"
  892. self.gguf.add_name(name)
  893. if metadata is not None:
  894. if metadata.author is not None:
  895. self.gguf.add_author(metadata.author)
  896. if metadata.version is not None:
  897. self.gguf.add_version(metadata.version)
  898. if metadata.url is not None:
  899. self.gguf.add_url(metadata.url)
  900. if metadata.description is not None:
  901. self.gguf.add_description(metadata.description)
  902. if metadata.licence is not None:
  903. self.gguf.add_licence(metadata.licence)
  904. if metadata.source_url is not None:
  905. self.gguf.add_source_url(metadata.source_url)
  906. if metadata.source_hf_repo is not None:
  907. self.gguf.add_source_hf_repo(metadata.source_hf_repo)
  908. def add_meta_arch(self, params: Params) -> None:
  909. # Metadata About The Neural Architecture Itself
  910. self.gguf.add_vocab_size(params.n_vocab)
  911. self.gguf.add_context_length(params.n_ctx)
  912. self.gguf.add_embedding_length(params.n_embd)
  913. self.gguf.add_block_count(params.n_layer)
  914. self.gguf.add_feed_forward_length(params.n_ff)
  915. self.gguf.add_rope_dimension_count(params.n_embd // params.n_head)
  916. self.gguf.add_head_count (params.n_head)
  917. self.gguf.add_head_count_kv (params.n_head_kv)
  918. if params.n_experts:
  919. self.gguf.add_expert_count(params.n_experts)
  920. if params.n_experts_used:
  921. self.gguf.add_expert_used_count(params.n_experts_used)
  922. if params.f_norm_eps:
  923. self.gguf.add_layer_norm_rms_eps(params.f_norm_eps)
  924. else:
  925. raise ValueError('f_norm_eps is None')
  926. if params.f_rope_freq_base is not None:
  927. self.gguf.add_rope_freq_base(params.f_rope_freq_base)
  928. if params.rope_scaling_type:
  929. assert params.f_rope_scale is not None
  930. self.gguf.add_rope_scaling_type(params.rope_scaling_type)
  931. self.gguf.add_rope_scaling_factor(params.f_rope_scale)
  932. if params.n_orig_ctx is not None:
  933. self.gguf.add_rope_scaling_orig_ctx_len(params.n_orig_ctx)
  934. if params.rope_finetuned is not None:
  935. self.gguf.add_rope_scaling_finetuned(params.rope_finetuned)
  936. if params.ftype is not None:
  937. self.gguf.add_file_type(params.ftype)
  938. def extract_vocabulary_from_model(self, vocab: Vocab) -> tuple[list[bytes], list[float], list[gguf.TokenType]]:
  939. tokens = []
  940. scores = []
  941. toktypes = []
  942. # NOTE: `all_tokens` returns the base vocabulary and added tokens
  943. for text, score, toktype in vocab.all_tokens():
  944. tokens.append(text)
  945. scores.append(score)
  946. toktypes.append(toktype)
  947. assert len(tokens) == vocab.vocab_size
  948. return tokens, scores, toktypes
  949. def add_meta_vocab(self, vocab: Vocab) -> None:
  950. # Ensure that tokenizer_model is added to the GGUF model
  951. self.gguf.add_tokenizer_model(vocab.tokenizer_model)
  952. # Extract model vocabulary for model conversion
  953. tokens, scores, toktypes = self.extract_vocabulary_from_model(vocab)
  954. # Add extracted token information for model conversion
  955. self.gguf.add_token_list(tokens)
  956. self.gguf.add_token_scores(scores)
  957. self.gguf.add_token_types(toktypes)
  958. def add_meta_special_vocab(self, svocab: gguf.SpecialVocab) -> None:
  959. svocab.add_to_gguf(self.gguf)
  960. def add_tensor_info(self, name: str, tensor: LazyTensor) -> None:
  961. n_elements = int(np.prod(tensor.shape))
  962. raw_dtype = getattr(tensor.data_type, 'ggml_type', None)
  963. data_type = getattr(tensor.data_type, 'quantized_type', None) or tensor.data_type.dtype
  964. data_nbytes = tensor.data_type.elements_to_bytes(n_elements)
  965. self.gguf.add_tensor_info(name, tensor.shape, data_type, data_nbytes, raw_dtype=raw_dtype)
  966. def write_meta(self) -> None:
  967. self.gguf.write_header_to_file()
  968. self.gguf.write_kv_data_to_file()
  969. def write_tensor_info(self) -> None:
  970. self.gguf.write_ti_data_to_file()
  971. def write_tensor_data(self, ftype: GGMLFileType, model: LazyModel, concurrency: int) -> None:
  972. ndarrays_inner = bounded_parallel_map(OutputFile.do_item, model.items(), concurrency=concurrency)
  973. if ftype == GGMLFileType.MostlyQ8_0:
  974. ndarrays = bounded_parallel_map(
  975. OutputFile.maybe_do_quantize, ndarrays_inner, concurrency=concurrency, max_workers=concurrency,
  976. use_processpool_executor=True,
  977. )
  978. else:
  979. ndarrays = map(OutputFile.maybe_do_quantize, ndarrays_inner)
  980. start = time.time()
  981. for i, ((name, lazy_tensor), ndarray) in enumerate(zip(model.items(), ndarrays)):
  982. elapsed = time.time() - start
  983. size = ' x '.join(f"{dim:6d}" for dim in lazy_tensor.shape)
  984. padi = len(str(len(model)))
  985. logger.info(
  986. f"[{i + 1:{padi}d}/{len(model)}] Writing tensor {name:38s} | size {size:16} | type {lazy_tensor.data_type.name:4} | T+{int(elapsed):4}"
  987. )
  988. self.gguf.write_tensor_data(ndarray)
  989. def close(self) -> None:
  990. self.gguf.close()
  991. @staticmethod
  992. def write_vocab_only(
  993. fname_out: Path, params: Params, vocab: Vocab, svocab: gguf.SpecialVocab,
  994. endianess: gguf.GGUFEndian = gguf.GGUFEndian.LITTLE, pad_vocab: bool = False, metadata: Metadata = None,
  995. ) -> None:
  996. check_vocab_size(params, vocab, pad_vocab=pad_vocab)
  997. of = OutputFile(fname_out, endianess=endianess)
  998. # meta data
  999. of.add_meta_model(params, metadata)
  1000. of.add_meta_arch(params)
  1001. of.add_meta_vocab(vocab)
  1002. of.add_meta_special_vocab(svocab)
  1003. of.write_meta()
  1004. of.close()
  1005. @staticmethod
  1006. def do_item(item: tuple[str, LazyTensor]) -> tuple[DataType, NDArray]:
  1007. name, lazy_tensor = item
  1008. tensor = lazy_tensor.load().to_ggml()
  1009. return (lazy_tensor.data_type, tensor.ndarray)
  1010. @staticmethod
  1011. def maybe_do_quantize(item: tuple[DataType, NDArray]) -> NDArray:
  1012. dt, arr = item
  1013. if not isinstance(dt, QuantizedDataType):
  1014. return arr
  1015. return dt.quantize(arr)
  1016. @staticmethod
  1017. def write_all(
  1018. fname_out: Path, ftype: GGMLFileType, params: Params, model: LazyModel, vocab: BaseVocab, svocab: gguf.SpecialVocab,
  1019. concurrency: int = DEFAULT_CONCURRENCY, endianess: gguf.GGUFEndian = gguf.GGUFEndian.LITTLE,
  1020. pad_vocab: bool = False,
  1021. metadata: Metadata = None,
  1022. ) -> None:
  1023. check_vocab_size(params, vocab, pad_vocab=pad_vocab)
  1024. of = OutputFile(fname_out, endianess=endianess)
  1025. # meta data
  1026. of.add_meta_model(params, metadata)
  1027. of.add_meta_arch(params)
  1028. if isinstance(vocab, Vocab):
  1029. of.add_meta_vocab(vocab)
  1030. of.add_meta_special_vocab(svocab)
  1031. else: # NoVocab
  1032. of.gguf.add_tokenizer_model(vocab.tokenizer_model)
  1033. # tensor info
  1034. for name, lazy_tensor in model.items():
  1035. of.add_tensor_info(name, lazy_tensor)
  1036. of.write_meta()
  1037. of.write_tensor_info()
  1038. # tensor data
  1039. of.write_tensor_data(ftype, model, concurrency)
  1040. of.close()
  1041. def pick_output_type(model: LazyModel, output_type_str: str | None) -> GGMLFileType:
  1042. wq_type = model[gguf.TENSOR_NAMES[gguf.MODEL_TENSOR.ATTN_Q].format(bid=0) + ".weight"].data_type
  1043. if output_type_str == "f32" or (output_type_str is None and wq_type in (DT_F32, DT_BF16)):
  1044. return GGMLFileType.AllF32
  1045. if output_type_str == "f16" or (output_type_str is None and wq_type == DT_F16):
  1046. return GGMLFileType.MostlyF16
  1047. if output_type_str == "q8_0":
  1048. return GGMLFileType.MostlyQ8_0
  1049. name_to_type = {name: lazy_tensor.data_type for (name, lazy_tensor) in model.items()}
  1050. raise ValueError(f"Unexpected combination of types: {name_to_type}")
  1051. def model_parameter_count(model: LazyModel) -> int:
  1052. total_model_parameters = 0
  1053. for i, (name, lazy_tensor) in enumerate(model.items()):
  1054. sum_weights_in_tensor = 1
  1055. for dim in lazy_tensor.shape:
  1056. sum_weights_in_tensor *= dim
  1057. total_model_parameters += sum_weights_in_tensor
  1058. return total_model_parameters
  1059. def model_parameter_count_rounded_notation(model_params_count: int) -> str:
  1060. if model_params_count > 1e12 :
  1061. # Trillions Of Parameters
  1062. scaled_model_params = model_params_count * 1e-12
  1063. scale_suffix = "T"
  1064. elif model_params_count > 1e9 :
  1065. # Billions Of Parameters
  1066. scaled_model_params = model_params_count * 1e-9
  1067. scale_suffix = "B"
  1068. elif model_params_count > 1e6 :
  1069. # Millions Of Parameters
  1070. scaled_model_params = model_params_count * 1e-6
  1071. scale_suffix = "M"
  1072. else:
  1073. # Thousands Of Parameters
  1074. scaled_model_params = model_params_count * 1e-3
  1075. scale_suffix = "K"
  1076. return f"{round(scaled_model_params)}{scale_suffix}"
  1077. def convert_to_output_type(model: LazyModel, output_type: GGMLFileType) -> LazyModel:
  1078. return {name: tensor.astype(output_type.type_for_tensor(name, tensor))
  1079. for (name, tensor) in model.items()}
  1080. def convert_model_names(model: LazyModel, params: Params, skip_unknown: bool) -> LazyModel:
  1081. tmap = gguf.TensorNameMap(ARCH, params.n_layer)
  1082. should_skip = set(gguf.MODEL_TENSOR_SKIP.get(ARCH, []))
  1083. tmp = model
  1084. # merge experts into one tensor
  1085. if params.n_experts and params.n_experts > 0:
  1086. for i_l in range(params.n_layer):
  1087. for w in range(1, 4):
  1088. experts = []
  1089. for e in range(params.n_experts):
  1090. if f"layers.{i_l}.feed_forward.experts.{e}.w{w}.weight" in model:
  1091. experts.append(model[f"layers.{i_l}.feed_forward.experts.{e}.w{w}.weight"])
  1092. del tmp[f"layers.{i_l}.feed_forward.experts.{e}.w{w}.weight"]
  1093. elif f"model.layers.{i_l}.block_sparse_moe.experts.{e}.w{w}.weight" in model:
  1094. experts.append(model[f"model.layers.{i_l}.block_sparse_moe.experts.{e}.w{w}.weight"])
  1095. del tmp[f"model.layers.{i_l}.block_sparse_moe.experts.{e}.w{w}.weight"]
  1096. else:
  1097. raise ValueError(f"Expert tensor not found: layers.{i_l}.feed_forward.experts.{e}.w{w}.weight")
  1098. tmp[f"layers.{i_l}.feed_forward.experts.w{w}.weight"] = pack_experts_lazy(experts)
  1099. # HF models permut or pack some of the tensors, so we need to undo that
  1100. for i in itertools.count():
  1101. if f"model.layers.{i}.self_attn.q_proj.weight" in model:
  1102. logger.debug(f"Permuting layer {i}")
  1103. 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)
  1104. 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)
  1105. # tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = model[f"model.layers.{i}.self_attn.v_proj.weight"]
  1106. elif f"model.layers.{i}.self_attn.W_pack.weight" in model:
  1107. logger.debug(f"Unpacking and permuting layer {i}")
  1108. 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)
  1109. 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)
  1110. tmp[f"model.layers.{i}.self_attn.v_proj.weight"] = part_lazy (model[f"model.layers.{i}.self_attn.W_pack.weight"], 2)
  1111. del tmp[f"model.layers.{i}.self_attn.W_pack.weight"]
  1112. else:
  1113. break
  1114. out: LazyModel = {}
  1115. for name, lazy_tensor in model.items():
  1116. tensor_type, name_new = tmap.get_type_and_name(name, try_suffixes = (".weight", ".bias")) or (None, None)
  1117. if name_new is None:
  1118. if skip_unknown:
  1119. logger.warning(f"Unexpected tensor name: {name} - skipping")
  1120. continue
  1121. raise ValueError(f"Unexpected tensor name: {name}. Use --skip-unknown to ignore it (e.g. LLaVA)")
  1122. if tensor_type in should_skip:
  1123. logger.debug(f"skipping tensor {name_new}")
  1124. continue
  1125. logger.debug(f"{name:48s} -> {name_new:40s} | {lazy_tensor.data_type.name:6s} | {lazy_tensor.shape}")
  1126. out[name_new] = lazy_tensor
  1127. return out
  1128. def nth_multifile_path(path: Path, n: int) -> Path | None:
  1129. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  1130. the nth path in the model.
  1131. '''
  1132. # Support the following patterns:
  1133. patterns = [
  1134. # - x.00.pth, x.01.pth, etc.
  1135. (r'\.[0-9]{2}\.pth$', f'.{n:02}.pth'),
  1136. # - x-00001-of-00002.bin, x-00002-of-00002.bin, etc.
  1137. (r'-[0-9]{5}-of-(.*)$', fr'-{n:05}-of-\1'),
  1138. # x.bin, x.bin.1, etc.
  1139. (r'(\.[0-9]+)?$', r'\1' if n == 0 else fr'\1.{n}')
  1140. ]
  1141. for regex, replacement in patterns:
  1142. if re.search(regex, path.name):
  1143. new_path = path.with_name(re.sub(regex, replacement, path.name))
  1144. if new_path.exists():
  1145. return new_path
  1146. return None
  1147. def find_multifile_paths(path: Path) -> list[Path]:
  1148. '''Given any path belonging to a multi-file model (e.g. foo.bin.1), return
  1149. the whole list of paths in the model.
  1150. '''
  1151. ret: list[Path] = []
  1152. for i in itertools.count():
  1153. nth_path = nth_multifile_path(path, i)
  1154. if nth_path is None:
  1155. break
  1156. ret.append(nth_path)
  1157. if not ret:
  1158. # No matches. This should only happen if the file was named, e.g.,
  1159. # foo.0, and there was no file named foo. Oh well, try to process it
  1160. # as a single file.
  1161. return [path]
  1162. return ret
  1163. def load_some_model(path: Path) -> ModelPlus:
  1164. '''Load a model of any supported format.'''
  1165. # Be extra-friendly and accept either a file or a directory:
  1166. if path.is_dir():
  1167. # Check if it's a set of safetensors files first
  1168. globs = ["model-00001-of-*.safetensors", "model.safetensors", "consolidated.safetensors"]
  1169. files = [file for glob in globs for file in path.glob(glob)]
  1170. if not files:
  1171. # Try the PyTorch patterns too, with lower priority
  1172. globs = ["consolidated.00.pth", "pytorch_model-00001-of-*.bin", "*.pt", "pytorch_model.bin"]
  1173. files = [file for glob in globs for file in path.glob(glob)]
  1174. if not files:
  1175. raise FileNotFoundError(f"Can't find model in directory {path}")
  1176. if len(files) > 1:
  1177. raise ValueError(f"Found multiple models in {path}, not sure which to pick: {files}")
  1178. path = files[0]
  1179. paths = find_multifile_paths(path)
  1180. models_plus: list[ModelPlus] = []
  1181. for path in paths:
  1182. logger.info(f"Loading model file {path}")
  1183. models_plus.append(lazy_load_file(path))
  1184. model_plus = merge_multifile_models(models_plus)
  1185. return model_plus
  1186. class VocabFactory:
  1187. _VOCAB_CLASSES: list[type[Vocab]] = [SentencePieceVocab, BpeVocab, LlamaHfVocab]
  1188. def __init__(self, path: Path):
  1189. self.path = path
  1190. def _create_special_vocab(self, vocab: BaseVocab, model_parent_path: Path) -> gguf.SpecialVocab:
  1191. load_merges = vocab.name == "bpe"
  1192. n_vocab = vocab.vocab_size if isinstance(vocab, Vocab) else None
  1193. return gguf.SpecialVocab(
  1194. model_parent_path,
  1195. load_merges=load_merges,
  1196. special_token_types=None, # Predetermined or passed as a parameter
  1197. n_vocab=n_vocab,
  1198. )
  1199. def _create_vocab_by_path(self, vocab_types: list[str]) -> Vocab:
  1200. vocab_classes: dict[str, type[Vocab]] = {cls.name: cls for cls in self._VOCAB_CLASSES}
  1201. selected_vocabs: dict[str, type[Vocab]] = {}
  1202. for vtype in vocab_types:
  1203. try:
  1204. selected_vocabs[vtype] = vocab_classes[vtype]
  1205. except KeyError:
  1206. raise ValueError(f"Unsupported vocabulary type {vtype}") from None
  1207. for vtype, cls in selected_vocabs.items():
  1208. try:
  1209. vocab = cls(self.path)
  1210. break
  1211. except FileNotFoundError:
  1212. pass # ignore unavailable tokenizers
  1213. else:
  1214. raise FileNotFoundError(f"Could not find a tokenizer matching any of {vocab_types}")
  1215. logger.info(f"Loaded vocab file {vocab.fname_tokenizer!r}, type {vocab.name!r}")
  1216. return vocab
  1217. def load_vocab(self, vocab_types: list[str] | None, model_parent_path: Path) -> tuple[BaseVocab, gguf.SpecialVocab]:
  1218. vocab: BaseVocab
  1219. if vocab_types is None:
  1220. vocab = NoVocab()
  1221. else:
  1222. vocab = self._create_vocab_by_path(vocab_types)
  1223. # FIXME: Respect --vocab-dir?
  1224. special_vocab = self._create_special_vocab(
  1225. vocab,
  1226. model_parent_path,
  1227. )
  1228. return vocab, special_vocab
  1229. def default_convention_outfile(file_type: GGMLFileType, params: Params, model_params_count: int, metadata: Metadata) -> str:
  1230. quantization = {
  1231. GGMLFileType.AllF32: "F32",
  1232. GGMLFileType.MostlyF16: "F16",
  1233. GGMLFileType.MostlyQ8_0: "Q8_0",
  1234. }[file_type]
  1235. parameters = model_parameter_count_rounded_notation(model_params_count)
  1236. expert_count = ""
  1237. if params.n_experts is not None:
  1238. expert_count = f"{params.n_experts}x"
  1239. version = ""
  1240. if metadata is not None and metadata.version is not None:
  1241. version = f"-{metadata.version}"
  1242. name = "ggml-model"
  1243. if metadata is not None and metadata.name is not None:
  1244. name = metadata.name
  1245. elif params.path_model is not None:
  1246. name = params.path_model.name
  1247. return f"{name}{version}-{expert_count}{parameters}-{quantization}"
  1248. def default_outfile(model_paths: list[Path], file_type: GGMLFileType, params: Params, model_params_count: int, metadata: Metadata) -> Path:
  1249. default_filename = default_convention_outfile(file_type, params, model_params_count, metadata)
  1250. ret = model_paths[0].parent / f"{default_filename}.gguf"
  1251. if ret in model_paths:
  1252. logger.error(
  1253. f"Error: Default output path ({ret}) would overwrite the input. "
  1254. "Please explicitly specify a path using --outfile.")
  1255. sys.exit(1)
  1256. return ret
  1257. def do_dump_model(model_plus: ModelPlus) -> None:
  1258. print(f"model_plus.paths = {model_plus.paths!r}") # noqa: NP100
  1259. print(f"model_plus.format = {model_plus.format!r}") # noqa: NP100
  1260. print(f"model_plus.vocab = {model_plus.vocab!r}") # noqa: NP100
  1261. for name, lazy_tensor in model_plus.model.items():
  1262. print(f"{name}: shape={lazy_tensor.shape} type={lazy_tensor.data_type}; {lazy_tensor.description}") # noqa: NP100
  1263. def main(args_in: list[str] | None = None) -> None:
  1264. output_choices = ["f32", "f16"]
  1265. if np.uint32(1) == np.uint32(1).newbyteorder("<"):
  1266. # We currently only support Q8_0 output on little endian systems.
  1267. output_choices.append("q8_0")
  1268. parser = argparse.ArgumentParser(description="Convert a LLaMA model to a GGML compatible file")
  1269. parser.add_argument("--dump", action="store_true", help="don't convert, just show what's in the model")
  1270. parser.add_argument("--dump-single", action="store_true", help="don't convert, just show what's in a single model file")
  1271. parser.add_argument("--vocab-only", action="store_true", help="extract only the vocab")
  1272. parser.add_argument("--no-vocab", action="store_true", help="store model without the vocab")
  1273. parser.add_argument("--outtype", choices=output_choices, help="output format - note: q8_0 may be very slow (default: f16 or f32 based on input)")
  1274. parser.add_argument("--vocab-dir", type=Path, help="directory containing tokenizer.model, if separate from model file")
  1275. parser.add_argument("--vocab-type", help="vocab types to try in order, choose from 'spm', 'bpe', 'hfft' (default: spm,hfft)", default="spm,hfft")
  1276. parser.add_argument("--outfile", type=Path, help="path to write to; default: based on input")
  1277. parser.add_argument("model", type=Path, help="directory containing model file, or model file itself (*.pth, *.pt, *.bin)")
  1278. parser.add_argument("--ctx", type=int, help="model training context (default: based on input)")
  1279. parser.add_argument("--concurrency", type=int, help=f"concurrency used for conversion (default: {DEFAULT_CONCURRENCY})", default=DEFAULT_CONCURRENCY)
  1280. parser.add_argument("--big-endian", action="store_true", help="model is executed on big endian machine")
  1281. parser.add_argument("--pad-vocab", action="store_true", help="add pad tokens when model vocab expects more than tokenizer metadata provides")
  1282. parser.add_argument("--skip-unknown", action="store_true", help="skip unknown tensor names instead of failing")
  1283. parser.add_argument("--verbose", action="store_true", help="increase output verbosity")
  1284. parser.add_argument("--metadata", type=Path, help="Specify the path for a metadata file")
  1285. parser.add_argument("--get-outfile", action="store_true", help="get calculated default outfile name")
  1286. args = parser.parse_args(args_in)
  1287. if args.verbose:
  1288. logging.basicConfig(level=logging.DEBUG)
  1289. elif args.dump_single or args.dump or args.get_outfile:
  1290. # Avoid printing anything besides the dump output
  1291. logging.basicConfig(level=logging.WARNING)
  1292. else:
  1293. logging.basicConfig(level=logging.INFO)
  1294. metadata = Metadata.load(args.metadata)
  1295. if args.get_outfile:
  1296. model_plus = load_some_model(args.model)
  1297. params = Params.load(model_plus)
  1298. model = convert_model_names(model_plus.model, params, args.skip_unknown)
  1299. model_params_count = model_parameter_count(model_plus.model)
  1300. ftype = pick_output_type(model, args.outtype)
  1301. print(f"{default_convention_outfile(ftype, params, model_params_count, metadata)}") # noqa: NP100
  1302. return
  1303. if args.no_vocab and args.vocab_only:
  1304. raise ValueError("--vocab-only does not make sense with --no-vocab")
  1305. if args.dump_single:
  1306. model_plus = lazy_load_file(args.model)
  1307. do_dump_model(model_plus)
  1308. return
  1309. if not args.vocab_only:
  1310. model_plus = load_some_model(args.model)
  1311. else:
  1312. model_plus = ModelPlus(model = {}, paths = [args.model / 'dummy'], format = 'none', vocab = None)
  1313. model_params_count = model_parameter_count(model_plus.model)
  1314. logger.info(f"model parameters count : {model_params_count} ({model_parameter_count_rounded_notation(model_params_count)})")
  1315. if args.dump:
  1316. do_dump_model(model_plus)
  1317. return
  1318. endianess = gguf.GGUFEndian.LITTLE
  1319. if args.big_endian:
  1320. endianess = gguf.GGUFEndian.BIG
  1321. params = None
  1322. if args.pad_vocab or not args.vocab_only:
  1323. params = Params.load(model_plus)
  1324. if params.n_ctx == -1:
  1325. if args.ctx is None:
  1326. msg = """\
  1327. The model doesn't have a context size, and you didn't specify one with --ctx
  1328. Please specify one with --ctx:
  1329. - LLaMA v1: --ctx 2048
  1330. - LLaMA v2: --ctx 4096"""
  1331. parser.error(textwrap.dedent(msg))
  1332. params.n_ctx = args.ctx
  1333. if args.outtype:
  1334. params.ftype = {
  1335. "f32": GGMLFileType.AllF32,
  1336. "f16": GGMLFileType.MostlyF16,
  1337. "q8_0": GGMLFileType.MostlyQ8_0,
  1338. }[args.outtype]
  1339. logger.info(f"params = {params}")
  1340. model_parent_path = model_plus.paths[0].parent
  1341. vocab_path = Path(args.vocab_dir or args.model or model_parent_path)
  1342. vocab_factory = VocabFactory(vocab_path)
  1343. vocab_types = None if args.no_vocab else args.vocab_type.split(",")
  1344. vocab, special_vocab = vocab_factory.load_vocab(vocab_types, model_parent_path)
  1345. if args.vocab_only:
  1346. assert isinstance(vocab, Vocab)
  1347. if not args.outfile:
  1348. raise ValueError("need --outfile if using --vocab-only")
  1349. outfile = args.outfile
  1350. if params is None:
  1351. params = Params(
  1352. n_vocab = vocab.vocab_size,
  1353. n_embd = 1,
  1354. n_layer = 1,
  1355. n_ctx = 1,
  1356. n_ff = 1,
  1357. n_head = 1,
  1358. n_head_kv = 1,
  1359. f_norm_eps = 1e-5,
  1360. )
  1361. OutputFile.write_vocab_only(outfile, params, vocab, special_vocab,
  1362. endianess=endianess, pad_vocab=args.pad_vocab, metadata=metadata)
  1363. logger.info(f"Wrote {outfile}")
  1364. return
  1365. if model_plus.vocab is not None and args.vocab_dir is None and not args.no_vocab:
  1366. vocab = model_plus.vocab
  1367. logger.info(f"Vocab info: {vocab}")
  1368. logger.info(f"Special vocab info: {special_vocab}")
  1369. model = model_plus.model
  1370. model = convert_model_names(model, params, args.skip_unknown)
  1371. ftype = pick_output_type(model, args.outtype)
  1372. model = convert_to_output_type(model, ftype)
  1373. outfile = args.outfile or default_outfile(model_plus.paths, ftype, params, model_params_count, metadata)
  1374. params.ftype = ftype
  1375. logger.info(f"Writing {outfile}, format {ftype}")
  1376. OutputFile.write_all(outfile, ftype, params, model, vocab, special_vocab,
  1377. concurrency=args.concurrency, endianess=endianess, pad_vocab=args.pad_vocab, metadata=metadata)
  1378. logger.info(f"Wrote {outfile}")
  1379. if __name__ == '__main__':
  1380. main()