gguf_reader.py 12 KB

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