1
0

gguf_reader.py 12 KB

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