test_ggml_integration.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. import ggml
  2. import ctypes
  3. import torch
  4. import pytest
  5. import numpy as np
  6. import torch
  7. import fairseq2.nn
  8. import fairseq2.nn.transformer
  9. import logging
  10. import sys
  11. import functools
  12. from typing import Tuple
  13. from pathlib import Path
  14. from ctypes_utils import Ptr
  15. from ctypes import c_void_p
  16. from typing import Any
  17. from pathlib import Path
  18. from typing import Iterator
  19. from ggml import NativeObj
  20. from ggml_convert import convert_model
  21. from seamless_communication.models.inference.translator import Translator, Modality
  22. Ctx = ggml.ggml_context_p
  23. UNITY_MODELS = Path(__file__).parent / "examples/unity/models"
  24. CTX_PARAMS = ggml.ggml_init_params(mem_size=16 * 1024 * 1024, mem_buffer=None)
  25. @pytest.fixture(name="ctx")
  26. def _ctx() -> Iterator[Ctx]:
  27. """Allocate a new context with 16 MB of memory"""
  28. try:
  29. ctx = ggml.ggml_init(params=CTX_PARAMS)
  30. yield ctx
  31. finally:
  32. ggml.ggml_free(ctx)
  33. def test_ggml_bindings_work(ctx: Ctx) -> None:
  34. # Instantiate tensors
  35. x = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 1)
  36. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 1)
  37. b = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 1)
  38. # Use ggml operations to build a computational graph
  39. x2 = ggml.ggml_mul(ctx, x, x)
  40. f = ggml.ggml_add(ctx, ggml.ggml_mul(ctx, a, x2), b)
  41. gf = ggml.ggml_build_forward(f)
  42. # Set the input values
  43. ggml.ggml_set_f32(x, 2.0)
  44. ggml.ggml_set_f32(a, 3.0)
  45. ggml.ggml_set_f32(b, 4.0)
  46. # Compute the graph
  47. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  48. # Get the output value
  49. output = ggml.ggml_get_f32_1d(f, 0)
  50. assert output == 16.0
  51. def test_ggml_matmul(ctx: Ctx) -> None:
  52. # Instantiate tensors
  53. a = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 4, 2)
  54. x = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 4, 3)
  55. # Use ggml operations to build a computational graph
  56. y = ggml.ggml_mul_mat(ctx, a, x)
  57. assert ggml.shape(y) == (3, 2)
  58. gf = ggml.ggml_build_forward(y)
  59. # Set the input values
  60. ggml.ggml_set_f32(x, 0.0)
  61. for i in range(4 * 3):
  62. ggml.ggml_set_f32_1d(x, i, i)
  63. ggml.ggml_set_f32(a, 0.0)
  64. ggml.ggml_set_f32_1d(a, 1, 1.0)
  65. ggml.ggml_set_f32_1d(a, 7, 1.0)
  66. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  67. output = [[ggml.ggml_get_f32_1d(y, j * 2 + i) for j in range(3)] for i in range(2)]
  68. assert output == [[1, 5, 9], [3, 7, 11]]
  69. def test_shape_works(ctx: Ctx) -> None:
  70. """GGML shape order convention is the reverse from numpy"""
  71. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 10)
  72. assert ggml.shape(a) == (10,)
  73. b = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 11, 21)
  74. assert ggml.shape(b) == (21, 11)
  75. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, 12, 22, 32)
  76. assert ggml.shape(c) == (32, 22, 12)
  77. def test_nb_works(ctx: Ctx) -> None:
  78. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 10)
  79. assert ggml.nb(a) == (4, 40, 40, 40)
  80. b = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F16, 11, 21)
  81. assert ggml.nb(b) == (2, 22, 462, 462)
  82. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, 12, 22, 32)
  83. assert ggml.nb(c) == (4, 48, 1056, 33792)
  84. def test_strides_works(ctx: Ctx) -> None:
  85. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 10)
  86. assert ggml.strides(a) == np.ones((10,), dtype=np.float32).strides
  87. b = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 11, 21)
  88. assert ggml.strides(b) == np.ones((21, 11), dtype=np.float32).strides
  89. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, 12, 22, 32)
  90. assert ggml.strides(c) == np.ones((32, 22, 12), dtype=np.float32).strides
  91. def test_to_numpy_works_with_f32(ctx: Ctx) -> None:
  92. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 10)
  93. na = ggml.to_numpy(a)
  94. for i in range(10):
  95. ggml.ggml_set_f32_1d(a, i, i)
  96. assert na[5] == 5
  97. assert np.allclose(na, np.array(range(10), dtype=np.float32))
  98. ggml.ggml_set_f32_1d(a, 5, -1.5)
  99. assert na[5] == -1.5
  100. # Note: GGML order of dims is reversed wrt numpy shapes
  101. b = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 11, 21)
  102. for i in range(11 * 21):
  103. ggml.ggml_set_f32_1d(b, i, i)
  104. nb = ggml.to_numpy(b)
  105. # assert nb.shape == (21, 11)
  106. assert nb[0, 5] == 5
  107. assert nb[3, 5] == 11 * 3 + 5
  108. assert np.allclose(
  109. nb, np.array(range(11 * 21), dtype=np.float32).reshape(ggml.shape(b))
  110. )
  111. ggml.ggml_set_f32_1d(b, 11 * 3 + 5, -1.5)
  112. assert nb[3, 5] == -1.5
  113. sum_rows = ggml.ggml_sum_rows(ctx, b)
  114. gf = ggml.ggml_build_forward(sum_rows)
  115. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  116. np_sum_rows = np.sum(nb, axis=-1, keepdims=True)
  117. assert np_sum_rows.shape == ggml.shape(sum_rows)
  118. for i in range(11):
  119. assert np_sum_rows[i] == ggml.ggml_get_f32_1d(sum_rows, i)
  120. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, 12, 22, 32)
  121. for i in range(12 * 22 * 32):
  122. ggml.ggml_set_f32_1d(c, i, i)
  123. nc = ggml.to_numpy(c)
  124. assert ggml.shape(c) == (32, 22, 12)
  125. assert nc[3, 5, 11] == 22 * 12 * 3 + 12 * 5 + 11
  126. assert np.allclose(
  127. nc, np.array(range(12 * 22 * 32), dtype=np.float32).reshape(ggml.shape(c))
  128. )
  129. ggml.ggml_set_f32_1d(c, 22 * 12 * 3 + 12 * 5 + 11, -1.5)
  130. assert nc[3, 5, 11] == -1.5
  131. def test_from_numpy_works_with_f32(ctx: Ctx) -> None:
  132. a = np.random.normal(size=(10,)).astype(dtype=np.float32)
  133. ga = ggml.from_numpy(ctx, a)
  134. assert ggml.shape(ga) == (10,)
  135. assert ggml.nb(ga) == ggml.nb(ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 10))
  136. assert np.allclose(a, ggml.to_numpy(ga))
  137. a = np.random.normal(size=(11, 21)).astype(dtype=np.float32)
  138. ga = ggml.from_numpy(ctx, a)
  139. assert ggml.shape(ga) == (11, 21)
  140. assert ggml.nb(ga) == ggml.nb(
  141. ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, *a.shape[::-1])
  142. )
  143. assert np.allclose(a, ggml.to_numpy(ga))
  144. a = np.random.normal(size=(12, 22, 32)).astype(dtype=np.float32)
  145. ga = ggml.from_numpy(ctx, a)
  146. assert ggml.shape(ga) == (12, 22, 32)
  147. assert ggml.nb(ga) == ggml.nb(
  148. ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, *a.shape[::-1])
  149. )
  150. assert np.allclose(a, ggml.to_numpy(ga))
  151. def test_to_numpy_works_with_f16(ctx: Ctx) -> None:
  152. # We explicitly fill the tensor otherwise they might have non-zero values in them.
  153. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F16, 10)
  154. na = ggml.to_numpy(a)
  155. ggml.ggml_set_f32(a, 2.14)
  156. assert np.allclose(na, np.ones((10,), dtype=np.float16) * 2.14)
  157. ggml.ggml_set_f32(a, 4.28)
  158. assert np.allclose(na, np.ones((10,), dtype=np.float16) * 4.28)
  159. b = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F16, 11, 21)
  160. nb = ggml.to_numpy(b)
  161. ggml.ggml_set_f32(b, 4.18)
  162. assert np.allclose(nb, np.ones((21, 11), dtype=np.float16) * 4.18)
  163. ggml.ggml_set_f32(b, 5.12)
  164. assert np.allclose(nb, np.ones((21, 11), dtype=np.float16) * 5.12)
  165. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F16, 12, 22, 32)
  166. nc = ggml.to_numpy(c)
  167. ggml.ggml_set_f32(c, 3.16)
  168. assert np.allclose(nc, np.ones((32, 22, 12), dtype=np.float16) * 3.16)
  169. ggml.ggml_set_f32(c, 5.08)
  170. assert np.allclose(nc, np.ones((32, 22, 12), dtype=np.float16) * 5.08)
  171. def test_from_numpy_works_with_f16(ctx: Ctx) -> None:
  172. a = np.random.normal(size=(10,)).astype(dtype=np.float16)
  173. ga = ggml.from_numpy(ctx, a)
  174. assert np.allclose(a, ggml.to_numpy(ga))
  175. a = np.random.normal(size=(11, 21)).astype(dtype=np.float16)
  176. ga = ggml.from_numpy(ctx, a)
  177. assert np.allclose(a, ggml.to_numpy(ga))
  178. a = np.random.normal(size=(12, 22, 32)).astype(dtype=np.float16)
  179. ga = ggml.from_numpy(ctx, a)
  180. assert np.allclose(a, ggml.to_numpy(ga))
  181. def test_to_numpy_works_with_transposed(ctx: Ctx) -> None:
  182. ga = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 10, 5)
  183. a = ggml.to_numpy(ga)
  184. a[...] = np.arange(50).reshape(5, 10).astype(dtype=np.float32)
  185. gat = ggml.ggml_transpose(ctx, ga)
  186. at = ggml.to_numpy(gat)
  187. assert np.allclose(a.T, at)
  188. def test_ggml_slice(ctx: Ctx) -> None:
  189. ga = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 10, 5)
  190. a = ggml.to_numpy(ga)
  191. a[...] = np.arange(50).reshape(5, 10).astype(dtype=np.float32)
  192. gs0 = ggml.ggml_slice(ctx, ga, 0, 3, 7)
  193. s0 = ggml.to_numpy(gs0)
  194. assert np.allclose(a[:, 3:7], s0)
  195. gs1 = ggml.ggml_slice(ctx, ga, 1, 2, 5)
  196. s1 = ggml.to_numpy(gs1)
  197. assert np.allclose(a[2:5, :], s1)
  198. @pytest.mark.xfail(reason="to_numpy not implemented")
  199. def test_ggml_transpose_and_slice(ctx: Ctx) -> None:
  200. ga = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 10, 5)
  201. a = ggml.to_numpy(ga)
  202. a[...] = np.arange(50).reshape(5, 10).astype(dtype=np.float32)
  203. gat = ggml.ggml_transpose(ctx, ga)
  204. gs0 = ggml.ggml_slice(ctx, gat, 0, 2, 5)
  205. s0 = ggml.to_numpy(gs0)
  206. assert np.allclose(a.T[:, 2:5], s0)
  207. gs1 = ggml.ggml_slice(ctx, gat, 1, 3, 7)
  208. s1 = ggml.to_numpy(gs1)
  209. assert np.allclose(a.T[3:7, :], s1)
  210. def test_numpy_mul_mat(ctx: Ctx) -> None:
  211. slen, d_in, d_out = (5, 4, 2)
  212. # torch.nn and fairseq2.nn assumes (seq_len, dim) to represent inputs,
  213. x = np.zeros((slen, d_in), dtype=np.float32) # (seq_len, dim_in)
  214. x[0, :] = [1, 1 / 3, 0, 0]
  215. weight = np.eye(d_out, d_in, dtype=np.float32)
  216. weight[1, 1] = 1
  217. # assert weight.shape == (d_out, d_in) # (dim_out, dim_in)
  218. y_exp = x @ weight.T # (seq_len, dim_out)
  219. gx = ggml.from_numpy(ctx, x) # (dim_in, seq_len)
  220. gw = ggml.from_numpy(ctx, weight) # (dim_in, dim_out)
  221. # gb = ggml.from_numpy(ctx, linear.bias.numpy()) # (dim_out)
  222. # GGML linear impl
  223. assert ggml.ggml_can_mul_mat(gw, gx)
  224. # gy = ggml.ggml_add(ctx, ggml.ggml_mul_mat(ctx, gw, gx), gb) # (dim_out, seq_len)
  225. gy = ggml.ggml_mul_mat(ctx, gw, gx) # (dim_out, seq_len)
  226. ggml.build_and_compute(ctx, gy)
  227. y = ggml.to_numpy(gy)
  228. assert np.allclose(y_exp, y)
  229. @pytest.mark.parametrize("ndim", [2, 3, 4])
  230. def test_flatten(ctx: Ctx, ndim: int) -> None:
  231. shape = [11, 7, 5, 3][:ndim] # Prime numbers to avoid surprises
  232. numel = functools.reduce(lambda a, b: a * b, shape, 1)
  233. x = torch.arange(numel, dtype=torch.float32).reshape(shape)
  234. for torch_dim in range(ndim - 1):
  235. ggml_dim = ndim - 1 - torch_dim
  236. n = x.shape[torch_dim + 1]
  237. gx = ggml.from_numpy(ctx, x)
  238. gx1 = ggml.ggml_flatten_1d(ctx, gx, ggml_dim - 1)
  239. gy = ggml.ggml_unflatten_1d(ctx, gx1, ggml_dim - 1, n)
  240. x1 = x.flatten(torch_dim, torch_dim + 1)
  241. y = x1.unflatten(torch_dim, (-1, n))
  242. assert y.shape == x.shape
  243. assert np.allclose(y.numpy(), x.numpy())
  244. assert x1.shape == ggml.shape(gx1)
  245. assert np.allclose(x1.numpy(), ggml.to_numpy(gx1))
  246. assert y.shape == ggml.shape(gy)
  247. assert np.allclose(y.numpy(), ggml.to_numpy(gy))
  248. @torch.no_grad()
  249. def test_torch_spda_vs_ggml_flash_attn(ctx: Ctx) -> None:
  250. slen, d_in, num_heads = (5, 4, 2)
  251. torch.random.manual_seed(0)
  252. q = torch.zeros((num_heads, slen, d_in))
  253. torch.nn.init.uniform_(q, -1, 1)
  254. k = torch.zeros((num_heads, slen, d_in))
  255. torch.nn.init.uniform_(k, -1, 1)
  256. v = torch.zeros((num_heads, slen, d_in))
  257. torch.nn.init.uniform_(v, -1, 1)
  258. # Note: we are using x for both keys and queries, so every position
  259. # attends mostly to itself, hence y_exp looks a bit like arange(slen)
  260. y_exp = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)
  261. y_exp = y_exp.numpy()
  262. gq = ggml.from_numpy(ctx, q.numpy())
  263. gk = ggml.from_numpy(ctx, k.numpy())
  264. # ggml flash attention expect a different order of axis for v:
  265. # (H, slen, H_dim) -> (H, H_dim, slen)
  266. gv = ggml.from_numpy(ctx, v.transpose(1, 2).contiguous().numpy())
  267. assert ggml.shape(gv) == (num_heads, d_in, slen)
  268. gy = ggml.ggml_flash_attn(ctx, gq, gk, gv, True)
  269. gf = ggml.ggml_build_forward(gy)
  270. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  271. y = ggml.to_numpy(gy)
  272. assert np.allclose(y_exp, y)
  273. @pytest.mark.parametrize("shape", [(5, 8, 4), (2, 5, 8, 4)])
  274. def test_ggml_softmax_vs_torch(ctx: Ctx, shape: Tuple[int, ...]) -> None:
  275. x = torch.empty(shape)
  276. torch.nn.init.uniform_(x, -1, 1)
  277. y_exp = torch.softmax(x, dim=-1).numpy()
  278. gx = ggml.from_numpy(ctx, x.numpy())
  279. gy = ggml.ggml_soft_max(ctx, gx)
  280. ggml.build_and_compute(ctx, gy)
  281. y = ggml.to_numpy(gy)
  282. assert np.allclose(y_exp, y, rtol=1e-3)
  283. assert np.allclose(np.argmax(y_exp, axis=-1), np.argmax(y, axis=-1))
  284. def test_can_return_hypothesis_ptr(ctx: Ctx) -> None:
  285. hyp_ptr = ggml._testing_return_hypothesis_ptr(ctx)
  286. hyp0, hyp1 = hyp_ptr[0], hyp_ptr[1]
  287. assert ggml.to_numpy(hyp0.seq).tolist() == [314]
  288. assert hyp0.score == pytest.approx(3.14)
  289. assert ggml.to_numpy(hyp1.seq).tolist() == [421]
  290. assert hyp1.score == pytest.approx(4.21)
  291. @pytest.mark.parametrize("inplace", ["", "inplace"])
  292. def test_set_2d(ctx: Ctx, inplace: bool):
  293. a = torch.empty((5, 3, 2))
  294. torch.nn.init.uniform_(a, -1, 1)
  295. b = torch.empty((3, 2))
  296. torch.nn.init.uniform_(b, -1, 1)
  297. a_original = a.clone()
  298. # make a copy of `a` before we modify it
  299. ga = ggml.from_numpy(ctx, a.clone().numpy())
  300. gb = ggml.from_numpy(ctx, b.numpy())
  301. a[3, ...] = b
  302. set_2d = ggml.ggml_set_2d_inplace if inplace else ggml.ggml_set_2d
  303. ga_updated = set_2d(ctx, ga, gb, ggml.nb(ga)[1], ggml.nb(ga)[2] * 3)
  304. ggml.build_and_compute(ctx, ga_updated)
  305. a_updated = ggml.to_numpy(ga if inplace else ga_updated)
  306. assert np.allclose(a.numpy(), a_updated)
  307. if not inplace:
  308. # When not using set_2d_inplace, the original tensor is unmodified.
  309. assert np.allclose(ggml.to_numpy(ga), a_original.numpy())
  310. assert ga.contents.data != ga_updated.contents.data