gguf_reader.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  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'] | Literal['S'] = 'I'
  53. alignment: int = GGUF_DEFAULT_ALIGNMENT
  54. # Note: Internal helper, API may change.
  55. gguf_scalar_to_np: dict[GGUFValueType, type[np.generic]] = {
  56. GGUFValueType.UINT8: np.uint8,
  57. GGUFValueType.INT8: np.int8,
  58. GGUFValueType.UINT16: np.uint16,
  59. GGUFValueType.INT16: np.int16,
  60. GGUFValueType.UINT32: np.uint32,
  61. GGUFValueType.INT32: np.int32,
  62. GGUFValueType.FLOAT32: np.float32,
  63. GGUFValueType.UINT64: np.uint64,
  64. GGUFValueType.INT64: np.int64,
  65. GGUFValueType.FLOAT64: np.float64,
  66. GGUFValueType.BOOL: np.bool_,
  67. }
  68. def __init__(self, path: os.PathLike[str] | str, mode: Literal['r'] | Literal['r+'] | Literal['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(f'Sorry, file appears to be version {version} which we cannot handle')
  83. self.fields: OrderedDict[str, ReaderField] = OrderedDict()
  84. self.tensors: list[ReaderTensor] = []
  85. offs += self._push_field(ReaderField(offs, 'GGUF.version', [temp_version], [0], [GGUFValueType.UINT32]))
  86. temp_counts = self._get(offs, np.uint64, 2)
  87. offs += self._push_field(ReaderField(offs, 'GGUF.tensor_count', [temp_counts[:1]], [0], [GGUFValueType.UINT64]))
  88. offs += self._push_field(ReaderField(offs, 'GGUF.kv_count', [temp_counts[1:]], [0], [GGUFValueType.UINT64]))
  89. tensor_count, kv_count = temp_counts
  90. offs = self._build_fields(offs, kv_count)
  91. offs, tensors_fields = self._build_tensors_fields(offs, tensor_count)
  92. new_align = self.fields.get('general.alignment')
  93. if new_align is not None:
  94. if new_align.types != [GGUFValueType.UINT32]:
  95. raise ValueError('Bad type for general.alignment field')
  96. self.alignment = new_align.parts[-1][0]
  97. padding = offs % self.alignment
  98. if padding != 0:
  99. offs += self.alignment - padding
  100. self._build_tensors(offs, tensors_fields)
  101. _DT = TypeVar('_DT', bound = npt.DTypeLike)
  102. # Fetch a key/value metadata field by key.
  103. def get_field(self, key: str) -> Union[ReaderField, None]:
  104. return self.fields.get(key, None)
  105. # Fetch a tensor from the list by index.
  106. def get_tensor(self, idx: int) -> ReaderTensor:
  107. return self.tensors[idx]
  108. def _get(
  109. self, offset: int, dtype: npt.DTypeLike, count: int = 1, override_order: None | Literal['I'] | Literal['S'] | Literal['<'] = None,
  110. ) -> npt.NDArray[Any]:
  111. count = int(count)
  112. itemsize = int(np.empty([], dtype = dtype).itemsize)
  113. end_offs = offset + itemsize * count
  114. return (
  115. self.data[offset:end_offs]
  116. .view(dtype = dtype)[:count]
  117. .newbyteorder(override_order or self.byte_order)
  118. )
  119. def _push_field(self, field: ReaderField, skip_sum: bool = False) -> int:
  120. if field.name in self.fields:
  121. # TODO: add option to generate error on duplicate keys
  122. # raise KeyError(f'Duplicate {field.name} already in list at offset {field.offset}')
  123. logger.warning(f'Duplicate key {field.name} at offset {field.offset}')
  124. self.fields[field.name + '_{}'.format(field.offset)] = field
  125. else:
  126. self.fields[field.name] = field
  127. return 0 if skip_sum else sum(int(part.nbytes) for part in field.parts)
  128. def _get_str(self, offset: int) -> tuple[npt.NDArray[np.uint64], npt.NDArray[np.uint8]]:
  129. slen = self._get(offset, np.uint64)
  130. return slen, self._get(offset + 8, np.uint8, slen[0])
  131. def _get_field_parts(
  132. self, orig_offs: int, raw_type: int,
  133. ) -> tuple[int, list[npt.NDArray[Any]], list[int], list[GGUFValueType]]:
  134. offs = orig_offs
  135. types: list[GGUFValueType] = []
  136. gtype = GGUFValueType(raw_type)
  137. types.append(gtype)
  138. # Handle strings.
  139. if gtype == GGUFValueType.STRING:
  140. sparts: list[npt.NDArray[Any]] = list(self._get_str(offs))
  141. size = sum(int(part.nbytes) for part in sparts)
  142. return size, sparts, [1], types
  143. # Check if it's a simple scalar type.
  144. nptype = self.gguf_scalar_to_np.get(gtype)
  145. if nptype is not None:
  146. val = self._get(offs, nptype)
  147. return int(val.nbytes), [val], [0], types
  148. # Handle arrays.
  149. if gtype == GGUFValueType.ARRAY:
  150. raw_itype = self._get(offs, np.uint32)
  151. offs += int(raw_itype.nbytes)
  152. alen = self._get(offs, np.uint64)
  153. offs += int(alen.nbytes)
  154. aparts: list[npt.NDArray[Any]] = [raw_itype, alen]
  155. data_idxs: list[int] = []
  156. for idx in range(alen[0]):
  157. curr_size, curr_parts, curr_idxs, curr_types = self._get_field_parts(offs, raw_itype[0])
  158. if idx == 0:
  159. types += curr_types
  160. idxs_offs = len(aparts)
  161. aparts += curr_parts
  162. data_idxs += (idx + idxs_offs for idx in curr_idxs)
  163. offs += curr_size
  164. return offs - orig_offs, aparts, data_idxs, types
  165. # We can't deal with this one.
  166. raise ValueError('Unknown/unhandled field type {gtype}')
  167. def _get_tensor(self, orig_offs: int) -> ReaderField:
  168. offs = orig_offs
  169. name_len, name_data = self._get_str(offs)
  170. offs += int(name_len.nbytes + name_data.nbytes)
  171. n_dims = self._get(offs, np.uint32)
  172. offs += int(n_dims.nbytes)
  173. dims = self._get(offs, np.uint64, n_dims[0])
  174. offs += int(dims.nbytes)
  175. raw_dtype = self._get(offs, np.uint32)
  176. offs += int(raw_dtype.nbytes)
  177. offset_tensor = self._get(offs, np.uint64)
  178. offs += int(offset_tensor.nbytes)
  179. return ReaderField(
  180. orig_offs,
  181. str(bytes(name_data), encoding = 'utf-8'),
  182. [name_len, name_data, n_dims, dims, raw_dtype, offset_tensor],
  183. [1, 3, 4, 5],
  184. )
  185. def _build_fields(self, offs: int, count: int) -> int:
  186. for _ in range(count):
  187. orig_offs = offs
  188. kv_klen, kv_kdata = self._get_str(offs)
  189. offs += int(kv_klen.nbytes + kv_kdata.nbytes)
  190. raw_kv_type = self._get(offs, np.uint32)
  191. offs += int(raw_kv_type.nbytes)
  192. parts: list[npt.NDArray[Any]] = [kv_klen, kv_kdata, raw_kv_type]
  193. idxs_offs = len(parts)
  194. field_size, field_parts, field_idxs, field_types = self._get_field_parts(offs, raw_kv_type[0])
  195. parts += field_parts
  196. self._push_field(ReaderField(
  197. orig_offs,
  198. str(bytes(kv_kdata), encoding = 'utf-8'),
  199. parts,
  200. [idx + idxs_offs for idx in field_idxs],
  201. field_types,
  202. ), skip_sum = True)
  203. offs += field_size
  204. return offs
  205. def _build_tensors_fields(self, offs: int, count: int) -> tuple[int, list[ReaderField]]:
  206. tensor_fields = []
  207. for _ in range(count):
  208. field = self._get_tensor(offs)
  209. offs += sum(int(part.nbytes) for part in field.parts)
  210. tensor_fields.append(field)
  211. return offs, tensor_fields
  212. def _build_tensors(self, start_offs: int, fields: list[ReaderField]) -> None:
  213. tensors = []
  214. tensor_names = set() # keep track of name to prevent duplicated tensors
  215. for field in fields:
  216. _name_len, name_data, _n_dims, dims, raw_dtype, offset_tensor = field.parts
  217. # check if there's any tensor having same name already in the list
  218. tensor_name = str(bytes(name_data), encoding = 'utf-8')
  219. if tensor_name in tensor_names:
  220. raise ValueError(f'Found duplicated tensor with name {tensor_name}')
  221. tensor_names.add(tensor_name)
  222. ggml_type = GGMLQuantizationType(raw_dtype[0])
  223. n_elems = int(np.prod(dims))
  224. np_dims = tuple(reversed(dims.tolist()))
  225. block_size, type_size = GGML_QUANT_SIZES[ggml_type]
  226. n_bytes = n_elems * type_size // block_size
  227. data_offs = int(start_offs + offset_tensor[0])
  228. item_type: npt.DTypeLike
  229. if ggml_type == GGMLQuantizationType.F16:
  230. item_count = n_elems
  231. item_type = np.float16
  232. elif ggml_type == GGMLQuantizationType.F32:
  233. item_count = n_elems
  234. item_type = np.float32
  235. elif ggml_type == GGMLQuantizationType.F64:
  236. item_count = n_elems
  237. item_type = np.float64
  238. elif ggml_type == GGMLQuantizationType.I8:
  239. item_count = n_elems
  240. item_type = np.int8
  241. elif ggml_type == GGMLQuantizationType.I16:
  242. item_count = n_elems
  243. item_type = np.int16
  244. elif ggml_type == GGMLQuantizationType.I32:
  245. item_count = n_elems
  246. item_type = np.int32
  247. elif ggml_type == GGMLQuantizationType.I64:
  248. item_count = n_elems
  249. item_type = np.int64
  250. else:
  251. item_count = n_bytes
  252. item_type = np.uint8
  253. np_dims = quant_shape_to_byte_shape(np_dims, ggml_type)
  254. tensors.append(ReaderTensor(
  255. name = tensor_name,
  256. tensor_type = ggml_type,
  257. shape = dims,
  258. n_elements = n_elems,
  259. n_bytes = n_bytes,
  260. data_offset = data_offs,
  261. data = self._get(data_offs, item_type, item_count).reshape(np_dims),
  262. field = field,
  263. ))
  264. self.tensors = tensors