ggml.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  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. n_dim = tensor.n_dims
  53. t_shape = shape(tensor)
  54. strides = nb(tensor)[:n_dim][::-1]
  55. # Convert the ggml data pointer to a pointer to ints with the same size (float16 -> uint16)
  56. # This is needed because Python ctypes doesn't have "float16", and `as_array` only works with ctypes
  57. type_size = ggml_type_size(tensor.type)
  58. int_width: type = getattr(ctypes, f"c_uint{8 * type_size}")
  59. ptr = ctypes.cast(tensor.data, ctypes.POINTER(int_width))
  60. # Create a numpy array with the wrong dtype
  61. int_arr = np.ctypeslib.as_array(ptr, shape=t_shape)
  62. # Reinterpret it to the right dtype
  63. res = np.frombuffer(int_arr, dtype=numpy_dtype(tensor.type)).reshape(t_shape)
  64. # Patch up strides to work with transposed ggml_tensor
  65. res.strides = strides
  66. return res
  67. GgmlNElem = ctypes.c_int64 * GGML_MAX_DIMS
  68. GgmlNBytes = ctypes.c_uint64 * GGML_MAX_DIMS
  69. def from_file(
  70. ctx: ggml_context_p, file: Path, shape: Tuple[int, ...], dtype: type = np.float32
  71. ) -> ggml_tensor_p:
  72. data = np.fromfile(str(file), dtype=dtype).reshape(shape) # type: ignore
  73. return from_numpy(ctx, data)
  74. def _shape_to_ne(shape: Tuple[int, ...]) -> Tuple[int, int, int, int]:
  75. # in GGML ne[0] indicates the contiguous dimension, ie the last one in numpy and torch
  76. ne = shape[::-1]
  77. if len(ne) >= GGML_MAX_DIMS:
  78. return # type: ignore
  79. # ne is always of the same length
  80. padding = (1,) * (GGML_MAX_DIMS - len(ne))
  81. return ne + padding # type: ignore
  82. def _compute_nbytes(
  83. ne: Tuple[int, int, int, int], type: ctypes.c_int
  84. ) -> Tuple[int, int, int, int]:
  85. nb0 = ggml_type_size(type)
  86. nb1 = nb0 * (ne[0] // ggml_blck_size(type))
  87. nb2 = nb1 * ne[1]
  88. nb3 = nb2 * ne[2]
  89. return (nb0, nb1, nb2, nb3)
  90. def from_numpy(
  91. ctx: ggml_context_p, array: Union[np.ndarray, "torch.Tensor"]
  92. ) -> ggml_tensor_p:
  93. if type(array).__name__ == "Tensor":
  94. array = array.numpy()
  95. # Create an empty tensor so we don't allocate memory for the data pointer
  96. gtype = from_numpy_dtype(array.dtype)
  97. tensor_p = ggml_new_tensor_1d(ctx, gtype, 0)
  98. # Fill out the correct dimensions and shape.
  99. tensor_p.contents.n_dims = array.ndim
  100. ne = _shape_to_ne(array.shape)
  101. tensor_p.contents.ne = GgmlNElem(*ne)
  102. tensor_p.contents.nb = GgmlNBytes(*_compute_nbytes(ne, gtype))
  103. # point the tensor data to the content of the numpy array.
  104. tensor_p.contents.data = array.ctypes.data_as(ctypes.c_void_p)
  105. # print(f"array: {array.shape} @0x{array.ctypes.data_as(ctypes.c_void_p)}")
  106. # print(f"tensor_p: {shape(tensor_p)} @0x{tensor_p.contents.data:x}")
  107. # prevent the underlying numpy array to be freed
  108. setattr(tensor_p, "__data", array)
  109. return tensor_p
  110. def ggml_can_mul_mat(t0: ggml_tensor_p, t1: ggml_tensor_p) -> bool:
  111. assert GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function"
  112. return (
  113. (t0.contents.ne[0] == t1.contents.ne[0])
  114. and (t1.contents.ne[2] % t0.contents.ne[2] == 0)
  115. and (t1.contents.ne[3] % t0.contents.ne[3] == 0)
  116. )
  117. class NativeObj:
  118. AllocFn = Callable[[], ctypes.c_void_p]
  119. FreeFn = Callable[[ctypes.c_void_p], None]
  120. _cache: Dict[str, Tuple[AllocFn, FreeFn]] = {}
  121. @classmethod
  122. def _init_c_func(cls, kind: str) -> Tuple[AllocFn, FreeFn]:
  123. if kind in cls._cache:
  124. return cls._cache[kind]
  125. alloc_fn = getattr(lib, f"{kind}_alloc")
  126. alloc_fn.argtypes = []
  127. alloc_fn.restype = ctypes.c_void_p
  128. free_fn = getattr(lib, f"{kind}_free")
  129. free_fn.argtypes = [ctypes.c_void_p]
  130. free_fn.restype = None
  131. cls._cache[kind] = (alloc_fn, free_fn)
  132. return (alloc_fn, free_fn)
  133. def __init__(self, kind: str, ptr: ctypes.c_void_p = NULL):
  134. self.kind = kind
  135. alloc_fn, self._free_fn = self._init_c_func(kind)
  136. self.ptr = alloc_fn() if ptr is None else ptr
  137. # print(self)
  138. def free(self) -> None:
  139. if self.ptr is not None:
  140. self._free_fn(self.ptr)
  141. # print(f"freeing {self}")
  142. self.ptr = NULL
  143. def __enter__(self) -> ctypes.c_void_p:
  144. return self.ptr
  145. def __exit__(self, *args: Any) -> None:
  146. self.free()
  147. def __del__(self) -> None:
  148. self.free()
  149. def __repr__(self) -> str:
  150. return f"<{self.kind} native object at 0x{self.ptr:x}>"
  151. def MeasureArena() -> NativeObj:
  152. return NativeObj("ggml_allocr", ggml_allocr_new_measure(GGML_MEM_ALIGN))
  153. def FixedSizeArena(mem_size: int) -> NativeObj:
  154. memory = torch.zeros(mem_size, dtype=torch.uint8)
  155. allocr = ggml_allocr_new(
  156. ctypes.c_void_p(memory.data_ptr()), mem_size, GGML_MEM_ALIGN
  157. )
  158. arena = NativeObj("ggml_allocr", allocr)
  159. # Add a reference from the arena object to the underlying tensor, otherwise it will be freed to early.
  160. setattr(arena, "__memory", memory)
  161. return arena
  162. lib.fairseq2_model_set_inference_ctx.argtypes = [ctypes.c_void_p, ggml_context_p]
  163. def Fairseq2Model() -> NativeObj:
  164. return NativeObj("fairseq2_model")
  165. lib.std_string_alloc.argtypes = [ctypes.c_char_p]
  166. lib.std_string_alloc.restype = ctypes.c_void_p
  167. lib.std_string_free.argtypes = [ctypes.c_void_p]
  168. lib.std_string_free.restype = None
  169. NativeObj._cache["std_string"] = (lib.std_string_alloc, lib.std_string_free)
  170. @functools.lru_cache(1024)
  171. def CppStr(content: str) -> NativeObj:
  172. c_str = ctypes.create_string_buffer(content.encode("utf-8"))
  173. cpp_str = lib.std_string_alloc(c_str)
  174. return NativeObj("std_string", cpp_str)
  175. lib.load_unity_ggml_file.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
  176. lib.load_unity_ggml_file.restype = ctypes.c_int
  177. def load_unity_ggml_file(model_file: Path) -> NativeObj:
  178. model = Fairseq2Model()
  179. bytes_file = ctypes.create_string_buffer(str(model_file).encode("utf-8"))
  180. err = lib.load_unity_ggml_file(model.ptr, bytes_file)
  181. if err:
  182. raise Exception("Failed to load model")
  183. return model
  184. # lib.unity_audio_encoder_graph.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
  185. # lib.unity_audio_encoder_graph.restype = ctypes.POINTER(ggml_cgraph)
  186. # def unity_audio_encoder_graph(model: NativeObj, tensor: ggml_tensor_p) -> ggml_cgraph_p:
  187. # return lib.unity_audio_encoder_graph(model.ptr, tensor) # type: ignore
  188. # lib.unity_eval.argtypes = [
  189. # ctypes.c_void_p,
  190. # ctypes.c_void_p,
  191. # ctypes.POINTER(ggml_tensor),
  192. # ctypes.c_int,
  193. # ]
  194. # lib.unity_eval.restype = ctypes.POINTER(ggml_cgraph)
  195. # def unity_eval(
  196. # allocr: ctypes.c_void_p, model: NativeObj, tensor: ggml_tensor_p, n_threads: int
  197. # ) -> ggml_cgraph_p:
  198. # return lib.unity_eval(allocr, model.ptr, tensor, n_threads)
  199. _FORWARD_CACHE: Dict[str, Callable[..., ggml_tensor_p]] = {}
  200. def forward(
  201. layer_name: str, model: ctypes.c_void_p, prefix: str, *inputs: ggml_tensor_p
  202. ) -> ggml_tensor_p:
  203. fwd: Any = _FORWARD_CACHE.get(layer_name)
  204. if fwd is None:
  205. fwd = getattr(lib, layer_name + "_forward")
  206. num_inputs = len(inputs)
  207. fwd.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + [
  208. ctypes.POINTER(ggml_tensor)
  209. ] * num_inputs
  210. fwd.restype = ctypes.POINTER(ggml_tensor)
  211. _FORWARD_CACHE[layer_name] = fwd
  212. with CppStr(prefix) as std_prefix:
  213. return fwd(model, std_prefix, *inputs) # ignore: type[no-any-return]
  214. lib.causal_attention_mask.argtypes = [ggml_context_p, ctypes.POINTER(ggml_tensor)]
  215. lib.causal_attention_mask.restype = ctypes.POINTER(ggml_tensor)
  216. def causal_attention_mask(ctx: ggml_context_p, seqs: ggml_tensor_p) -> ggml_tensor_p:
  217. return lib.causal_attention_mask(ctx, seqs) # type: ignore[no-any-return]