ggml.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553
  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 contextlib
  6. import ctypes
  7. import dataclasses
  8. import functools
  9. import logging
  10. from pathlib import Path
  11. from typing import Any, Callable, Dict, Iterator, NamedTuple, Tuple, Type, Union
  12. import numpy as np
  13. import torch
  14. import subprocess
  15. import sys
  16. from ctypes_utils import NULLPTR, Ptr, c_fn, c_struct
  17. from third_party_ggml import *
  18. ### Helpers
  19. @functools.lru_cache(4)
  20. def numpy_dtype(ggml_type: ctypes.c_int) -> np.dtype:
  21. if ggml_type == 0:
  22. # GGML_TYPE_F32 = 0,
  23. return np.dtype(np.float32)
  24. if ggml_type == 1:
  25. # GGML_TYPE_F16 = 1,
  26. return np.dtype(np.float16)
  27. if ggml_type == 18:
  28. return np.dtype(np.int32)
  29. raise NotImplementedError(f"Can't convert GGML_TYPE({ggml_type}) to a numpy.dtype")
  30. @functools.lru_cache()
  31. def from_numpy_dtype(dtype: np.dtype) -> ctypes.c_int:
  32. def _ggml_type(name: bytes, value: int) -> ctypes.c_int:
  33. t = ctypes.c_int(value)
  34. type_name = ggml_type_name(t)
  35. if name != type_name:
  36. raise RuntimeError(
  37. f"Type {name!r} doesn't have value {value}. ggml.h was probably updated but not ggml.py"
  38. )
  39. return t
  40. if dtype == np.float32:
  41. return _ggml_type(b"f32", 0)
  42. elif dtype == np.float16:
  43. return _ggml_type(b"f16", 1)
  44. elif dtype == np.dtype("bool"):
  45. return _ggml_type(b"i8", 16)
  46. elif dtype == np.int32:
  47. return _ggml_type(b"i32", 18)
  48. raise NotImplementedError(f"Can't convert {dtype} to a GGML_TYPE")
  49. def shape(tensor: Union[ggml_tensor, ggml_tensor_p]) -> Tuple[int, ...]:
  50. if isinstance(tensor, ctypes._Pointer):
  51. tensor = tensor.contents
  52. ndims = tensor.n_dims
  53. return tuple([tensor.ne[i] for i in range(ndims)[::-1]])
  54. def nb(tensor: Union[ggml_tensor, ggml_tensor_p]) -> Tuple[int, ...]:
  55. if isinstance(tensor, ctypes._Pointer):
  56. tensor = tensor.contents
  57. return tuple([tensor.nb[i] for i in range(4)])
  58. def ne(tensor: Union[ggml_tensor, ggml_tensor_p]) -> Tuple[int, ...]:
  59. if isinstance(tensor, ctypes._Pointer):
  60. tensor = tensor.contents
  61. return tuple([tensor.ne[i] for i in range(4)])
  62. def strides(tensor: Union[ggml_tensor, ggml_tensor_p]) -> Tuple[int, ...]:
  63. if isinstance(tensor, ctypes._Pointer):
  64. tensor = tensor.contents
  65. ndims = tensor.n_dims
  66. num_bytes = tuple([tensor.nb[i] for i in range(ndims)])
  67. strides = num_bytes[::-1]
  68. return strides
  69. def to_numpy(tensor_p: ggml_tensor_p) -> np.ndarray:
  70. if not ggml_is_contiguous(tensor_p):
  71. if not _almost_contiguous(tensor_p):
  72. return _strided_to_numpy(tensor_p)
  73. tensor = tensor_p.contents
  74. res = _void_p_to_np_array(tensor.data, shape(tensor), numpy_dtype(tensor.type))
  75. if ggml_is_transposed(tensor_p):
  76. # Patch up strides to work with transposed ggml_tensor
  77. res.strides = strides(tensor) # type: ignore[assignment]
  78. return res
  79. def _almost_contiguous(tensor_p: ggml_tensor_p) -> bool:
  80. """Distinguishes between fully strided and just transposed."""
  81. tensor = tensor_p.contents
  82. num_bytes = nb(tensor)
  83. num_elem = ne(tensor)
  84. # Sort the axis according to 'num_bytes'
  85. nbe = sorted(zip(num_bytes, num_elem))
  86. itemsize = ggml_type_size(tensor.type)
  87. stride_exp = itemsize
  88. for stride, e in nbe:
  89. if stride != stride_exp:
  90. return False
  91. stride_exp *= e
  92. return True
  93. def _strided_to_numpy(tensor_p: ggml_tensor_p) -> np.ndarray:
  94. if ggml_is_transposed(tensor_p):
  95. raise NotImplementedError(
  96. "to_numpy doesn't support tensors both transposed and strided."
  97. )
  98. tensor = tensor_p.contents
  99. n_dim = tensor.n_dims
  100. t_shape = shape(tensor)
  101. t_strides = strides(tensor)
  102. type_size = ggml_type_size(tensor.type)
  103. full_shape = []
  104. num_bytes = nb(tensor)
  105. # Determine the full backing slice of bytes to read.
  106. # TODO make this work for transposed array
  107. n = 1
  108. total_elements = 1
  109. try:
  110. for d in range(n_dim - 1):
  111. n = num_bytes[d + 1] // type_size // n
  112. full_shape.append(n)
  113. total_elements *= n
  114. except ZeroDivisionError:
  115. logging.warning("Can't convert permuted GGML tensor back to numpy")
  116. return None
  117. # We don't need to guess for the first dimension, since this doesn't impact striding.
  118. full_shape.append(t_shape[0])
  119. total_elements *= t_shape[0]
  120. full_shape = full_shape[::-1]
  121. res = _void_p_to_np_array(tensor.data, tuple(full_shape), numpy_dtype(tensor.type))
  122. # Extract the correct slice
  123. res = res.__getitem__(tuple(slice(0, n) for n in t_shape))
  124. # TODO: we could handle transposition here
  125. return res
  126. def _void_p_to_np_array(
  127. data: ctypes.c_void_p, shape: Tuple[int, ...], dtype: np.dtype
  128. ) -> np.ndarray:
  129. # Convert the ggml data pointer to a pointer of bytes
  130. # This is needed because Python ctypes doesn't have "float16", and `as_array` only works with ctypes
  131. int_width: type = getattr(ctypes, f"c_uint{8 * dtype.itemsize}")
  132. ptr = ctypes.cast(data, ctypes.POINTER(int_width))
  133. # Create a numpy array with the wrong dtype
  134. int_arr = np.ctypeslib.as_array(ptr, shape=shape)
  135. # Reinterpret it to the right dtype
  136. return np.frombuffer(int_arr, dtype=dtype).reshape(shape)
  137. GgmlNElem = ctypes.c_int64 * GGML_MAX_DIMS
  138. GgmlNBytes = ctypes.c_uint64 * GGML_MAX_DIMS
  139. def from_file(
  140. ctx: ggml_context_p, file: Path, shape: Tuple[int, ...], dtype: type = np.float32
  141. ) -> ggml_tensor_p:
  142. data = np.fromfile(str(file), dtype=dtype).reshape(shape) # type: ignore
  143. return from_numpy(ctx, data)
  144. def _shape_to_ne(shape: Tuple[int, ...]) -> Tuple[int, int, int, int]:
  145. # in GGML ne[0] indicates the contiguous dimension, ie the last one in numpy and torch
  146. ne = shape[::-1]
  147. if len(ne) >= GGML_MAX_DIMS:
  148. return ne # type: ignore
  149. # ne is always of the same length
  150. padding = (1,) * (GGML_MAX_DIMS - len(ne))
  151. return ne + padding # type: ignore
  152. def _compute_nbytes(
  153. ne: Tuple[int, int, int, int], type: ctypes.c_int
  154. ) -> Tuple[int, int, int, int]:
  155. nb0 = ggml_type_size(type)
  156. nb1 = nb0 * (ne[0] // ggml_blck_size(type))
  157. nb2 = nb1 * ne[1]
  158. nb3 = nb2 * ne[2]
  159. return (nb0, nb1, nb2, nb3)
  160. def from_numpy(
  161. ctx: ggml_context_p, array: Union[np.ndarray, "torch.Tensor"], name: bytes = b""
  162. ) -> Ptr[ggml_tensor]:
  163. if type(array).__name__ == "Tensor":
  164. array = array.numpy()
  165. # Create an empty tensor so we don't allocate memory for the data pointer
  166. gtype = from_numpy_dtype(array.dtype)
  167. tensor_p = ggml_new_tensor_1d(ctx, gtype, 0)
  168. # Fill out the correct dimensions and shape.
  169. tensor_p.contents.n_dims = array.ndim
  170. ne = _shape_to_ne(array.shape)
  171. tensor_p.contents.ne = GgmlNElem(*ne)
  172. tensor_p.contents.nb = GgmlNBytes(*_compute_nbytes(ne, gtype))
  173. # point the tensor data to the content of the numpy array.
  174. tensor_p.contents.data = array.ctypes.data_as(ctypes.c_void_p)
  175. # print(f"array: {array.shape} @0x{array.ctypes.data_as(ctypes.c_void_p)}")
  176. # print(f"tensor_p: {shape(tensor_p)} @0x{tensor_p.contents.data:x}")
  177. # prevent the underlying numpy array to be freed
  178. setattr(tensor_p, "__data", array)
  179. if name:
  180. ggml_set_name(tensor_p, name)
  181. return tensor_p # type: ignore
  182. def ggml_can_mul_mat(t0: ggml_tensor_p, t1: ggml_tensor_p) -> bool:
  183. assert GGML_MAX_DIMS == 4, "GGML_MAX_DIMS is not 4 - update this function"
  184. return (
  185. (t0.contents.ne[0] == t1.contents.ne[0])
  186. and (t1.contents.ne[2] % t0.contents.ne[2] == 0)
  187. and (t1.contents.ne[3] % t0.contents.ne[3] == 0)
  188. )
  189. def nodes(gf: ggml_cgraph) -> Dict[bytes, ggml_tensor_p]:
  190. res = {}
  191. for i in range(gf.n_nodes):
  192. name = gf.nodes[i].contents.name
  193. res[name] = gf.nodes[i]
  194. return res
  195. def leafs(gf: ggml_cgraph) -> Dict[bytes, ggml_tensor_p]:
  196. res = {}
  197. for i in range(gf.n_leafs):
  198. name = gf.leafs[i].contents.name
  199. res[name] = gf.leafs[i]
  200. return res
  201. class NativeObj:
  202. AllocFn = Callable[[], ctypes.c_void_p]
  203. FreeFn = Callable[[ctypes.c_void_p], None]
  204. _cache: Dict[str, Tuple[AllocFn, FreeFn]] = {}
  205. @classmethod
  206. def _init_c_func(cls, kind: str) -> Tuple[AllocFn, FreeFn]:
  207. if kind in cls._cache:
  208. return cls._cache[kind]
  209. alloc_fn = getattr(lib, f"{kind}_alloc")
  210. alloc_fn.argtypes = []
  211. alloc_fn.restype = ctypes.c_void_p
  212. free_fn = getattr(lib, f"{kind}_free")
  213. free_fn.argtypes = [ctypes.c_void_p]
  214. free_fn.restype = None
  215. cls._cache[kind] = (alloc_fn, free_fn)
  216. return (alloc_fn, free_fn)
  217. def __init__(self, kind: str, ptr: ctypes.c_void_p = NULLPTR):
  218. self.kind = kind
  219. alloc_fn, self._free_fn = self._init_c_func(kind)
  220. self.ptr = alloc_fn() if ptr is None else ptr
  221. # print(self)
  222. def free(self) -> None:
  223. if self.ptr is not None:
  224. self._free_fn(self.ptr)
  225. # print(f"freeing {self}")
  226. self.ptr = NULLPTR
  227. def __enter__(self) -> ctypes.c_void_p:
  228. return self.ptr
  229. def __exit__(self, *args: Any) -> None:
  230. self.free()
  231. def __del__(self) -> None:
  232. self.free()
  233. def __repr__(self) -> str:
  234. return f"<{self.kind} native object at 0x{self.ptr:x}>"
  235. def MeasureArena() -> NativeObj:
  236. return NativeObj("ggml_allocr", ggml_allocr_new_measure(GGML_MEM_ALIGN))
  237. def FixedSizeArena(mem_size: int) -> NativeObj:
  238. memory = torch.zeros(mem_size, dtype=torch.uint8)
  239. allocr = ggml_allocr_new(
  240. ctypes.c_void_p(memory.data_ptr()), mem_size, GGML_MEM_ALIGN
  241. )
  242. arena = NativeObj("ggml_allocr", allocr)
  243. # Add a reference from the arena object to the underlying tensor, otherwise it will be freed to early.
  244. setattr(arena, "__memory", memory)
  245. return arena
  246. lib.fairseq2_model_set_inference_ctx.argtypes = [ctypes.c_void_p, ggml_context_p]
  247. def Fairseq2Model() -> NativeObj:
  248. return NativeObj("fairseq2_model")
  249. lib.std_string_alloc.argtypes = [ctypes.c_char_p]
  250. lib.std_string_alloc.restype = ctypes.c_void_p
  251. lib.std_string_free.argtypes = [ctypes.c_void_p]
  252. lib.std_string_free.restype = None
  253. NativeObj._cache["std_string"] = (lib.std_string_alloc, lib.std_string_free)
  254. def CppStr(content: str) -> NativeObj:
  255. c_str = ctypes.create_string_buffer(content.encode("utf-8"))
  256. cpp_str = lib.std_string_alloc(c_str)
  257. return NativeObj("std_string", cpp_str)
  258. lib.load_fairseq2_ggml_file.argtypes = [ctypes.c_void_p, ctypes.c_char_p]
  259. lib.load_fairseq2_ggml_file.restype = ctypes.c_int
  260. def load_fairseq2_ggml_file(model_file: Path) -> NativeObj:
  261. model = Fairseq2Model()
  262. bytes_file = ctypes.create_string_buffer(str(model_file).encode("utf-8"))
  263. err = lib.load_fairseq2_ggml_file(model.ptr, bytes_file)
  264. if err:
  265. raise Exception("Failed to load model")
  266. return model
  267. # lib.unity_audio_encoder_graph.argtypes = [ctypes.c_void_p, ctypes.c_void_p]
  268. # lib.unity_audio_encoder_graph.restype = ctypes.POINTER(ggml_cgraph)
  269. # def unity_audio_encoder_graph(model: NativeObj, tensor: ggml_tensor_p) -> ggml_cgraph_p:
  270. # return lib.unity_audio_encoder_graph(model.ptr, tensor) # type: ignore
  271. # lib.unity_eval.argtypes = [
  272. # ctypes.c_void_p,
  273. # ctypes.c_void_p,
  274. # ctypes.POINTER(ggml_tensor),
  275. # ctypes.c_int,
  276. # ]
  277. # lib.unity_eval.restype = ctypes.POINTER(ggml_cgraph)
  278. # def unity_eval(
  279. # allocr: ctypes.c_void_p, model: NativeObj, tensor: ggml_tensor_p, n_threads: int
  280. # ) -> ggml_cgraph_p:
  281. # return lib.unity_eval(allocr, model.ptr, tensor, n_threads)
  282. _FORWARD_CACHE: Dict[str, Callable[..., ggml_tensor_p]] = {}
  283. def forward(
  284. layer_name: str, model: ctypes.c_void_p, prefix: str, *inputs: ggml_tensor_p
  285. ) -> ggml_tensor_p:
  286. fwd: Any = _FORWARD_CACHE.get(layer_name)
  287. if fwd is None:
  288. fwd = getattr(lib, layer_name + "_forward")
  289. num_inputs = len(inputs)
  290. fwd.argtypes = [ctypes.c_void_p, ctypes.c_void_p] + [
  291. ctypes.POINTER(ggml_tensor)
  292. ] * num_inputs
  293. fwd.restype = ctypes.POINTER(ggml_tensor)
  294. _FORWARD_CACHE[layer_name] = fwd
  295. with CppStr(prefix) as std_prefix:
  296. return fwd(model, std_prefix, *inputs) # ignore: type[no-any-return]
  297. def build_and_compute(
  298. ctx: ggml_context_p, tensor: ggml_tensor_p, num_threads: int = 1, dump: Union[bool, str] = False
  299. ) -> ggml_cgraph:
  300. gf = ggml_build_forward(tensor)
  301. need_alloc = tensor.contents.data == NULLPTR
  302. if need_alloc:
  303. alloc = FixedSizeArena(1024 * 1024 * 1024 * 2)
  304. ggml_allocr_alloc_graph(alloc.ptr, ctypes.pointer(gf))
  305. setattr(tensor, "__data", alloc)
  306. if dump:
  307. if dump == True:
  308. dump = f"dot/{sys._getframe(1).f_code.co_name}"
  309. ggml_graph_dump_dot(ctypes.pointer(gf), NULLPTR, dump.encode("ascii"))
  310. # subprocess.run(["dot", "-Tsvg", "-O", dump])
  311. ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), num_threads)
  312. return gf
  313. @c_fn(lib)
  314. def causal_attention_mask(
  315. ctx: ggml_context_p, seqs: Ptr[ggml_tensor]
  316. ) -> Ptr[ggml_tensor]:
  317. ...
  318. @c_fn(lib)
  319. def ggml_slice(
  320. ctx: ggml_context_p,
  321. a: Ptr[ggml_tensor],
  322. axis: int,
  323. start: ctypes.c_int64,
  324. end: ctypes.c_int64,
  325. ) -> Ptr[ggml_tensor]:
  326. ...
  327. @c_fn(lib)
  328. def ggml_flatten_1d(
  329. ctx: ggml_context_p, a: Ptr[ggml_tensor], dim: int
  330. ) -> Ptr[ggml_tensor]:
  331. return a
  332. @c_fn(lib)
  333. def ggml_unflatten_1d(
  334. ctx: ggml_context_p, a: Ptr[ggml_tensor], dim: int, num_el: int
  335. ) -> Ptr[ggml_tensor]:
  336. return a
  337. @c_struct
  338. @dataclasses.dataclass
  339. class SequenceGeneratorOptions:
  340. beam_size: int
  341. min_seq_len: int = 5
  342. soft_max_seq_len_a: float = 1.0
  343. soft_max_seq_len_b: int = 200
  344. hard_max_seq_len: int = 1024
  345. len_penalty: float = 1.0
  346. unk_penalty: float = 0.0
  347. normalize_scores: bool = True
  348. mem_mb: int = 256
  349. @c_struct
  350. @dataclasses.dataclass
  351. class SequenceGeneratorJob:
  352. opts: SequenceGeneratorOptions
  353. prefix_seq: Ptr[ggml_tensor]
  354. pad_idx: int
  355. unk_idx: int
  356. bos_idx: int
  357. eos_idx: int
  358. num_threads: int = 1
  359. @c_struct
  360. class Hypothesis:
  361. seq: Ptr[ggml_tensor]
  362. """The generated sequence."""
  363. score: float
  364. """The score of the hypothesis."""
  365. step_scores: Ptr[ggml_tensor]
  366. """The score of each individual sequence step."""
  367. @c_fn(lib)
  368. def generate_sequence(
  369. model: ctypes.c_void_p,
  370. job: Ptr[SequenceGeneratorJob],
  371. encoder_output: Ptr[ggml_tensor],
  372. encoder_padding_mask: Ptr[ggml_tensor],
  373. result_ctx: ggml_context_p,
  374. ) -> Ptr[Hypothesis]:
  375. ...
  376. @c_fn(lib)
  377. def _testing_return_hypothesis_ptr(ctx: ggml_context_p) -> Ptr[Hypothesis]:
  378. return Ptr()
  379. @c_fn(lib)
  380. def fairseq2_model_layer_config_int(model: ctypes.c_void_p, name: bytes) -> int:
  381. return -1
  382. @c_fn(lib.fairseq2_kv_cache_alloc)
  383. def _fairseq2_kv_cache_alloc(
  384. model: ctypes.c_void_p, ctx: ctypes.c_void_p, beam_size: int, max_seq_len: int
  385. ) -> None:
  386. pass
  387. @c_fn(lib.fairseq2_kv_cache_reset)
  388. def _fairseq2_kv_cache_reset(model: ctypes.c_void_p) -> None:
  389. pass
  390. @contextlib.contextmanager
  391. def fairseq2_kv_cache_alloc(
  392. model: ctypes.c_void_p, kv_cache_size: int, beam_size: int, max_seq_len: int
  393. ) -> Iterator[None]:
  394. memory = torch.zeros(kv_cache_size, dtype=torch.uint8)
  395. ctx = ggml_init(
  396. params=ggml_init_params(
  397. mem_size=kv_cache_size,
  398. mem_buffer=ctypes.c_void_p(memory.data_ptr()),
  399. no_alloc=False,
  400. )
  401. )
  402. _fairseq2_kv_cache_alloc(model, ctx, beam_size, max_seq_len)
  403. try:
  404. yield
  405. finally:
  406. _fairseq2_kv_cache_reset(model)
  407. ggml_free(ctx)
  408. @c_fn(lib)
  409. def fairseq2_spm_tokenize(
  410. model: ctypes.c_void_p, text: bytes, out: Ptr[ggml_tensor]
  411. ) -> None:
  412. pass
  413. @c_fn(lib)
  414. def fairseq2_spm_detokenize(
  415. model: ctypes.c_void_p, tensor: Ptr[ggml_tensor], out: ctypes.Array[ctypes.c_char]
  416. ) -> ctypes.c_size_t:
  417. return 0