test_ggml_integration.py 11 KB

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