gguf_reader.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303
  1. # ruff: noqa
  2. #
  3. # GGUF file reading/modification support. For API usage information,
  4. # please see the files scripts/ for some fairly simple examples.
  5. #
  6. from __future__ import annotations
  7. import os
  8. from collections import OrderedDict
  9. from typing import Any, Literal, NamedTuple, TypeVar, Union
  10. import numpy as np
  11. import numpy.typing as npt
  12. if __name__ == "__main__":
  13. import sys
  14. from pathlib import Path
  15. # Allow running file in package as a script.
  16. sys.path.insert(0, str(Path(__file__).parent.parent))
  17. from .constants import (
  18. GGML_QUANT_SIZES,
  19. GGUF_DEFAULT_ALIGNMENT,
  20. GGUF_MAGIC,
  21. GGUF_VERSION,
  22. GGMLQuantizationType,
  23. GGUFValueType,
  24. )
  25. READER_SUPPORTED_VERSIONS = [2, GGUF_VERSION]
  26. class ReaderField(NamedTuple):
  27. # Offset to start of this field.
  28. offset: int
  29. # Name of the field (not necessarily from file data).
  30. name: str
  31. # Data parts. Some types have multiple components, such as strings
  32. # that consist of a length followed by the string data.
  33. parts: list[npt.NDArray[Any]] = []
  34. # Indexes into parts that we can call the actual data. For example
  35. # an array of strings will be populated with indexes to the actual
  36. # string data.
  37. data: list[int] = [-1]
  38. types: list[GGUFValueType] = []
  39. class ReaderTensor(NamedTuple):
  40. name: str
  41. tensor_type: GGMLQuantizationType
  42. shape: npt.NDArray[np.uint32]
  43. n_elements: int
  44. n_bytes: int
  45. data_offset: int
  46. data: npt.NDArray[Any]
  47. field: ReaderField
  48. class GGUFReader:
  49. # I - same as host, S - swapped
  50. byte_order: Literal['I' | 'S'] = 'I'
  51. alignment: int = GGUF_DEFAULT_ALIGNMENT
  52. # Note: Internal helper, API may change.
  53. gguf_scalar_to_np: dict[GGUFValueType, type[np.generic]] = {
  54. GGUFValueType.UINT8: np.uint8,
  55. GGUFValueType.INT8: np.int8,
  56. GGUFValueType.UINT16: np.uint16,
  57. GGUFValueType.INT16: np.int16,
  58. GGUFValueType.UINT32: np.uint32,
  59. GGUFValueType.INT32: np.int32,
  60. GGUFValueType.FLOAT32: np.float32,
  61. GGUFValueType.UINT64: np.uint64,
  62. GGUFValueType.INT64: np.int64,
  63. GGUFValueType.FLOAT64: np.float64,
  64. GGUFValueType.BOOL: np.bool_,
  65. }
  66. def __init__(self,
  67. path: os.PathLike[str] | str,
  68. mode: Literal['r' | 'r+' | 'c'] = 'r'):
  69. self.data = np.memmap(path, mode=mode)
  70. offs = 0
  71. if self._get(offs, np.uint32, override_order='<')[0] != GGUF_MAGIC:
  72. raise ValueError('GGUF magic invalid')
  73. offs += 4
  74. temp_version = self._get(offs, np.uint32)
  75. if temp_version[0] & 65535 == 0:
  76. # If we get 0 here that means it's (probably) a GGUF file created for
  77. # the opposite byte order of the machine this script is running on.
  78. self.byte_order = 'S'
  79. temp_version = temp_version.newbyteorder(self.byte_order)
  80. version = temp_version[0]
  81. if version not in READER_SUPPORTED_VERSIONS:
  82. raise ValueError(
  83. f'Sorry, file appears to be version {version} which we cannot handle'
  84. )
  85. self.fields: OrderedDict[str, ReaderField] = OrderedDict()
  86. self.tensors: list[ReaderTensor] = []
  87. offs += self._push_field(
  88. ReaderField(offs, 'GGUF.version', [temp_version], [0],
  89. [GGUFValueType.UINT32]))
  90. temp_counts = self._get(offs, np.uint64, 2)
  91. offs += self._push_field(
  92. ReaderField(offs, 'GGUF.tensor_count', [temp_counts[:1]], [0],
  93. [GGUFValueType.UINT64]))
  94. offs += self._push_field(
  95. ReaderField(offs, 'GGUF.kv_count', [temp_counts[1:]], [0],
  96. [GGUFValueType.UINT64]))
  97. tensor_count, kv_count = temp_counts
  98. offs = self._build_fields(offs, kv_count)
  99. offs, tensors_fields = self._build_tensors_fields(offs, tensor_count)
  100. new_align = self.fields.get('general.alignment')
  101. if new_align is not None:
  102. if new_align.types != [GGUFValueType.UINT32]:
  103. raise ValueError('Bad type for general.alignment field')
  104. self.alignment = new_align.parts[-1][0]
  105. padding = offs % self.alignment
  106. if padding != 0:
  107. offs += self.alignment - padding
  108. self._build_tensors(offs, tensors_fields)
  109. _DT = TypeVar('_DT', bound=npt.DTypeLike)
  110. # Fetch a key/value metadata field by key.
  111. def get_field(self, key: str) -> Union[ReaderField, None]:
  112. return self.fields.get(key, None)
  113. # Fetch a tensor from the list by index.
  114. def get_tensor(self, idx: int) -> ReaderTensor:
  115. return self.tensors[idx]
  116. def _get(
  117. self,
  118. offset: int,
  119. dtype: npt.DTypeLike,
  120. count: int = 1,
  121. override_order: None | Literal['I' | 'S' | '<'] = None,
  122. ) -> npt.NDArray[Any]:
  123. count = int(count)
  124. itemsize = int(np.empty([], dtype=dtype).itemsize)
  125. end_offs = offset + itemsize * count
  126. return (self.data[offset:end_offs].view(
  127. dtype=dtype)[:count].newbyteorder(override_order
  128. or self.byte_order))
  129. def _push_field(self, field: ReaderField, skip_sum: bool = False) -> int:
  130. if field.name in self.fields:
  131. raise KeyError(
  132. f'Duplicate {field.name} already in list at offset {field.offset}'
  133. )
  134. self.fields[field.name] = field
  135. return 0 if skip_sum else sum(int(part.nbytes) for part in field.parts)
  136. def _get_str(
  137. self, offset: int
  138. ) -> tuple[npt.NDArray[np.uint64], npt.NDArray[np.uint8]]:
  139. slen = self._get(offset, np.uint64)
  140. return slen, self._get(offset + 8, np.uint8, slen[0])
  141. def _get_field_parts(
  142. self,
  143. orig_offs: int,
  144. raw_type: int,
  145. ) -> tuple[int, list[npt.NDArray[Any]], list[int], list[GGUFValueType]]:
  146. offs = orig_offs
  147. types: list[GGUFValueType] = []
  148. gtype = GGUFValueType(raw_type)
  149. types.append(gtype)
  150. # Handle strings.
  151. if gtype == GGUFValueType.STRING:
  152. sparts: list[npt.NDArray[Any]] = list(self._get_str(offs))
  153. size = sum(int(part.nbytes) for part in sparts)
  154. return size, sparts, [1], types
  155. # Check if it's a simple scalar type.
  156. nptype = self.gguf_scalar_to_np.get(gtype)
  157. if nptype is not None:
  158. val = self._get(offs, nptype)
  159. return int(val.nbytes), [val], [0], types
  160. # Handle arrays.
  161. if gtype == GGUFValueType.ARRAY:
  162. raw_itype = self._get(offs, np.uint32)
  163. offs += int(raw_itype.nbytes)
  164. alen = self._get(offs, np.uint64)
  165. offs += int(alen.nbytes)
  166. aparts: list[npt.NDArray[Any]] = [raw_itype, alen]
  167. data_idxs: list[int] = []
  168. for idx in range(alen[0]):
  169. curr_size, curr_parts, curr_idxs, curr_types = self._get_field_parts(
  170. offs, raw_itype[0])
  171. if idx == 0:
  172. types += curr_types
  173. idxs_offs = len(aparts)
  174. aparts += curr_parts
  175. data_idxs += (idx + idxs_offs for idx in curr_idxs)
  176. offs += curr_size
  177. return offs - orig_offs, aparts, data_idxs, types
  178. # We can't deal with this one.
  179. raise ValueError('Unknown/unhandled field type {gtype}')
  180. def _get_tensor(self, orig_offs: int) -> ReaderField:
  181. offs = orig_offs
  182. name_len, name_data = self._get_str(offs)
  183. offs += int(name_len.nbytes + name_data.nbytes)
  184. n_dims = self._get(offs, np.uint32)
  185. offs += int(n_dims.nbytes)
  186. dims = self._get(offs, np.uint64, n_dims[0])
  187. offs += int(dims.nbytes)
  188. raw_dtype = self._get(offs, np.uint32)
  189. offs += int(raw_dtype.nbytes)
  190. offset_tensor = self._get(offs, np.uint64)
  191. offs += int(offset_tensor.nbytes)
  192. return ReaderField(
  193. orig_offs,
  194. str(bytes(name_data), encoding='utf-8'),
  195. [name_len, name_data, n_dims, dims, raw_dtype, offset_tensor],
  196. [1, 3, 4, 5],
  197. )
  198. def _build_fields(self, offs: int, count: int) -> int:
  199. for _ in range(count):
  200. orig_offs = offs
  201. kv_klen, kv_kdata = self._get_str(offs)
  202. offs += int(kv_klen.nbytes + kv_kdata.nbytes)
  203. raw_kv_type = self._get(offs, np.uint32)
  204. offs += int(raw_kv_type.nbytes)
  205. parts: list[npt.NDArray[Any]] = [kv_klen, kv_kdata, raw_kv_type]
  206. idxs_offs = len(parts)
  207. field_size, field_parts, field_idxs, field_types = self._get_field_parts(
  208. offs, raw_kv_type[0])
  209. parts += field_parts
  210. self._push_field(ReaderField(
  211. orig_offs,
  212. str(bytes(kv_kdata), encoding='utf-8'),
  213. parts,
  214. [idx + idxs_offs for idx in field_idxs],
  215. field_types,
  216. ),
  217. skip_sum=True)
  218. offs += field_size
  219. return offs
  220. def _build_tensors_fields(self, offs: int,
  221. count: int) -> tuple[int, list[ReaderField]]:
  222. tensor_fields = []
  223. for _ in range(count):
  224. field = self._get_tensor(offs)
  225. offs += sum(int(part.nbytes) for part in field.parts)
  226. tensor_fields.append(field)
  227. return offs, tensor_fields
  228. def _build_tensors(self, start_offs: int,
  229. fields: list[ReaderField]) -> None:
  230. tensors = []
  231. for field in fields:
  232. _name_len, name_data, _n_dims, dims, raw_dtype, offset_tensor = field.parts
  233. ggml_type = GGMLQuantizationType(raw_dtype[0])
  234. n_elems = np.prod(dims)
  235. block_size, type_size = GGML_QUANT_SIZES[ggml_type]
  236. n_bytes = n_elems * type_size // block_size
  237. data_offs = int(start_offs + offset_tensor[0])
  238. item_type: npt.DTypeLike
  239. if ggml_type == GGMLQuantizationType.F16:
  240. item_count = n_elems
  241. item_type = np.float16
  242. elif ggml_type == GGMLQuantizationType.F32:
  243. item_count = n_elems
  244. item_type = np.float32
  245. elif ggml_type == GGMLQuantizationType.F64:
  246. item_count = n_elems
  247. item_type = np.float64
  248. elif ggml_type == GGMLQuantizationType.I8:
  249. item_count = n_elems
  250. item_type = np.int8
  251. elif ggml_type == GGMLQuantizationType.I16:
  252. item_count = n_elems
  253. item_type = np.int16
  254. elif ggml_type == GGMLQuantizationType.I32:
  255. item_count = n_elems
  256. item_type = np.int32
  257. elif ggml_type == GGMLQuantizationType.I64:
  258. item_count = n_elems
  259. item_type = np.int64
  260. else:
  261. item_count = n_bytes
  262. item_type = np.uint8
  263. tensors.append(
  264. ReaderTensor(
  265. name=str(bytes(name_data), encoding='utf-8'),
  266. tensor_type=ggml_type,
  267. shape=dims,
  268. n_elements=n_elems,
  269. n_bytes=n_bytes,
  270. data_offset=data_offs,
  271. data=self._get(data_offs, item_type, item_count),
  272. field=field,
  273. ))
  274. self.tensors = tensors