ggml.py 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. """
  2. We are vendoring https://github.com/abetlen/ggml-python (MIT License)
  3. adding a few utilities to convert between ggml and numpy tensors for testing.
  4. """
  5. import numpy as np
  6. import ctypes
  7. import torch
  8. import functools
  9. from pathlib import Path
  10. from typing import Dict
  11. from typing import Callable
  12. from typing import Any
  13. from typing import Tuple
  14. from typing import Union
  15. from typing import Type
  16. from third_party_ggml import *
  17. ### Helpers
  18. def numpy_dtype(ggml_type: ctypes.c_int) -> type:
  19. if ggml_type == 0:
  20. # GGML_TYPE_F32 = 0,
  21. return np.float32
  22. if ggml_type == 1:
  23. # GGML_TYPE_F16 = 1,
  24. return np.float16
  25. raise NotImplementedError(f"Can't convert GGML_TYPE({ggml_type}) to a numpy.dtype")
  26. def from_numpy_dtype(dtype: np.dtype) -> ctypes.c_int:
  27. if dtype == np.float32:
  28. return ctypes.c_int(0)
  29. elif dtype == np.float16:
  30. return ctypes.c_int(1)
  31. raise NotImplementedError(f"Can't convert {dtype} to a GGML_TYPE")
  32. def shape(tensor: Union[ggml_tensor, ggml_tensor_p]) -> Tuple[int, ...]:
  33. if isinstance(tensor, ctypes._Pointer):
  34. tensor = tensor.contents
  35. ndims = tensor.n_dims
  36. return tuple([tensor.ne[i] for i in range(ndims)[::-1]])
  37. def nb(tensor: Union[ggml_tensor, ggml_tensor_p]) -> Tuple[int, ...]:
  38. if isinstance(tensor, ctypes._Pointer):
  39. tensor = tensor.contents
  40. return tuple([tensor.nb[i] for i in range(4)])
  41. def strides(tensor: Union[ggml_tensor, ggml_tensor_p]) -> Tuple[int, ...]:
  42. raise NotImplementedError()
  43. if isinstance(tensor, ctypes._Pointer):
  44. tensor = tensor.contents
  45. ndims = tensor.n_dims
  46. num_bytes = tuple([tensor.nb[i] for i in range(ndims)])
  47. # TODO: convert to numpy strides
  48. return num_bytes
  49. def to_numpy(tensor: Union[ggml_tensor, ggml_tensor_p]) -> np.ndarray:
  50. if isinstance(tensor, ctypes._Pointer):
  51. tensor = tensor.contents
  52. t_shape = shape(tensor)
  53. # Convert the ggml data pointer to a pointer to ints with the same size (float16 -> uint16)
  54. # This is needed because Python ctypes doesn't have "float16", and `as_array` only works with ctypes
  55. type_size = ggml_type_size(tensor.type)
  56. int_width: type = getattr(ctypes, f"c_uint{8 * type_size}")
  57. ptr = ctypes.cast(tensor.data, ctypes.POINTER(int_width))
  58. # Create a numpy array with the wrong dtype
  59. int_arr = np.ctypeslib.as_array(ptr, shape=t_shape)
  60. # Reinterpret it to the right dtype
  61. res = np.frombuffer(int_arr, dtype=numpy_dtype(tensor.type)).reshape(t_shape)
  62. # TODO: assert strides / check contiguous
  63. # assert strides(tensor) == res.strides, "TODO: support strided tensor"
  64. return res
  65. GgmlNElem = ctypes.c_int64 * GGML_MAX_DIMS
  66. GgmlNBytes = ctypes.c_uint64 * GGML_MAX_DIMS
  67. def from_file(
  68. ctx: ggml_context_p, file: Path, shape: Tuple[int, ...], dtype: type = np.float32
  69. ) -> ggml_tensor_p:
  70. data = np.fromfile(str(file), dtype=dtype).reshape(shape) # type: ignore
  71. return from_numpy(ctx, data)
  72. def _shape_to_ne(shape: Tuple[int, ...]) -> Tuple[int, int, int, int]:
  73. # in GGML ne[0] indicates the contiguous dimension, ie the last one in numpy and torch
  74. ne = shape[::-1]
  75. if len(ne) >= GGML_MAX_DIMS:
  76. return # type: ignore
  77. # ne is always of the same length
  78. padding = (1,) * (GGML_MAX_DIMS - len(ne))
  79. return ne + padding # type: ignore
  80. def _compute_nbytes(
  81. ne: Tuple[int, int, int, int], type: ctypes.c_int
  82. ) -> Tuple[int, int, int, int]:
  83. nb0 = ggml_type_size(type)
  84. nb1 = nb0 * (ne[0] // ggml_blck_size(type))
  85. nb2 = nb1 * ne[1]
  86. nb3 = nb2 * ne[2]
  87. return (nb0, nb1, nb2, nb3)
  88. def from_numpy(
  89. ctx: ggml_context_p, array: Union[np.ndarray, "torch.Tensor"]
  90. ) -> ggml_tensor_p:
  91. if type(array).__name__ == "Tensor":
  92. array = array.numpy()
  93. # Create an empty tensor so we don't allocate memory for the data pointer
  94. gtype = from_numpy_dtype(array.dtype)
  95. tensor_p = ggml_new_tensor_1d(ctx, gtype, 0)
  96. # Fill out the correct dimensions and shape.
  97. tensor_p.contents.n_dims = array.ndim
  98. ne = _shape_to_ne(array.shape)
  99. tensor_p.contents.ne = GgmlNElem(*ne)
  100. tensor_p.contents.nb = GgmlNBytes(*_compute_nbytes(ne, gtype))
  101. # point the tensor data to the content of the numpy array.
  102. tensor_p.contents.data = array.ctypes.data_as(ctypes.c_void_p)
  103. # print(f"array: {array.shape} @0x{array.ctypes.data_as(ctypes.c_void_p)}")
  104. # print(f"tensor_p: {shape(tensor_p)} @0x{tensor_p.contents.data:x}")
  105. # prevent the underlying numpy array to be freed
  106. setattr(tensor_p, "__data", array)
  107. return tensor_p
  108. def ggml_can_mul_mat(t0: ggml_tensor_p, t1: ggml_tensor_p) -> bool:
  109. assert GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function"
  110. return (
  111. (t0.contents.ne[0] == t1.contents.ne[0])
  112. and (t1.contents.ne[2] % t0.contents.ne[2] == 0)
  113. and (t1.contents.ne[3] % t0.contents.ne[3] == 0)
  114. )
  115. class NativeObj:
  116. AllocFn = Callable[[], ctypes.c_void_p]
  117. FreeFn = Callable[[ctypes.c_void_p], None]
  118. _cache: Dict[str, Tuple[AllocFn, FreeFn]] = {}
  119. @classmethod
  120. def _init_c_func(cls, kind: str) -> Tuple[AllocFn, FreeFn]:
  121. if kind in cls._cache:
  122. return cls._cache[kind]
  123. alloc_fn = getattr(lib, f"{kind}_alloc")
  124. alloc_fn.argtypes = []
  125. alloc_fn.restype = ctypes.c_void_p
  126. free_fn = getattr(lib, f"{kind}_free")
  127. free_fn.argtypes = [ctypes.c_void_p]
  128. free_fn.restype = None
  129. cls._cache[kind] = (alloc_fn, free_fn)
  130. return (alloc_fn, free_fn)
  131. def __init__(self, kind: str, ptr: ctypes.c_void_p = NULL):
  132. self.kind = kind
  133. alloc_fn, self._free_fn = self._init_c_func(kind)
  134. self.ptr = alloc_fn() if ptr is None else ptr
  135. # print(self)
  136. def free(self) -> None:
  137. if self.ptr is not None:
  138. self._free_fn(self.ptr)
  139. # print(f"freeing {self}")
  140. self.ptr = NULL
  141. def __enter__(self) -> ctypes.c_void_p:
  142. return self.ptr
  143. def __exit__(self, *args: Any) -> None:
  144. self.free()
  145. def __del__(self) -> None:
  146. self.free()
  147. def __repr__(self) -> str:
  148. return f"<{self.kind} native object at 0x{self.ptr:x}>"
  149. def MeasureArena() -> NativeObj:
  150. return NativeObj("ggml_allocr", ggml_allocr_new_measure(GGML_MEM_ALIGN))
  151. def FixedSizeArena(mem_size: int) -> NativeObj:
  152. memory = torch.zeros(mem_size, dtype=torch.uint8)
  153. allocr = ggml_allocr_new(
  154. ctypes.c_void_p(memory.data_ptr()), mem_size, GGML_MEM_ALIGN
  155. )
  156. arena = NativeObj("ggml_allocr", allocr)
  157. # Add a reference from the arena object to the underlying tensor, otherwise it will be freed to early.
  158. setattr(arena, "__memory", memory)
  159. return arena
  160. def UnityModel() -> NativeObj:
  161. return NativeObj("unity_model")
  162. def GptVocab() -> NativeObj:
  163. return NativeObj("gpt_vocab")
  164. lib.fairseq2_model_set_inference_ctx.argtypes = [ctypes.c_void_p, ggml_context_p]
  165. def Fairseq2Model() -> NativeObj:
  166. return NativeObj("fairseq2_model")
  167. lib.std_string_alloc.argtypes = [ctypes.c_char_p]
  168. lib.std_string_alloc.restype = ctypes.c_void_p
  169. lib.std_string_free.argtypes = [ctypes.c_void_p]
  170. lib.std_string_free.restype = None
  171. NativeObj._cache["std_string"] = (lib.std_string_alloc, lib.std_string_free)
  172. @functools.lru_cache(1024)
  173. def CppStr(content: str) -> NativeObj:
  174. c_str = ctypes.create_string_buffer(content.encode("utf-8"))
  175. cpp_str = lib.std_string_alloc(c_str)
  176. return NativeObj("std_string", cpp_str)
  177. lib.unity_model_load.argtypes = [ctypes.c_char_p, ctypes.c_void_p, ctypes.c_void_p]
  178. def unity_model_load(model_file: Path) -> Tuple[NativeObj, NativeObj]:
  179. model = UnityModel()
  180. vocab = GptVocab()
  181. lib.unity_model_load(
  182. ctypes.create_string_buffer(str(model_file).encode("utf-8")),
  183. model.ptr,
  184. vocab.ptr,
  185. )
  186. return model, vocab
  187. lib.load_unity_ggml_file.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
  188. lib.load_unity_ggml_file.restype = ctypes.c_int
  189. def load_unity_ggml_file(model_file: Path) -> NativeObj:
  190. model = Fairseq2Model()
  191. bytes_file = ctypes.create_string_buffer(str(model_file).encode("utf-8"))
  192. err = lib.load_unity_ggml_file(model.ptr, bytes_file)
  193. if err:
  194. raise Exception("Failed to load model")
  195. return model
  196. lib.unity_audio_encoder_graph.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
  197. lib.unity_audio_encoder_graph.restype = ctypes.POINTER(ggml_cgraph)
  198. def unity_audio_encoder_graph(model: NativeObj, tensor: ggml_tensor_p) -> ggml_cgraph_p:
  199. return lib.unity_audio_encoder_graph(model.ptr, tensor) # type: ignore
  200. lib.unity_eval.argtypes = [
  201. ctypes.c_void_p,
  202. ctypes.c_void_p,
  203. ctypes.POINTER(ggml_tensor),
  204. ctypes.c_int,
  205. ]
  206. lib.unity_eval.restype = ctypes.POINTER(ggml_cgraph)
  207. def unity_eval(
  208. allocr: ctypes.c_void_p, model: NativeObj, tensor: ggml_tensor_p, n_threads: int
  209. ) -> ggml_cgraph_p:
  210. return lib.unity_eval(allocr, model.ptr, tensor, n_threads)
  211. _FORWARD_CACHE: Dict[str, Callable[..., ggml_tensor_p]] = {}
  212. def forward(
  213. layer_name: str, model: ctypes.c_void_p, prefix: str, *inputs: ggml_tensor_p
  214. ) -> ggml_tensor_p:
  215. fwd: Any = _FORWARD_CACHE.get(layer_name)
  216. if fwd is None:
  217. fwd = getattr(lib, layer_name + "_forward")
  218. num_inputs = len(inputs)
  219. fwd.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + [
  220. ctypes.POINTER(ggml_tensor)
  221. ] * num_inputs
  222. fwd.restype = ctypes.POINTER(ggml_tensor)
  223. _FORWARD_CACHE[layer_name] = fwd
  224. with CppStr(prefix) as std_prefix:
  225. return fwd(model, std_prefix, *inputs) # ignore: type[no-any-return]