test_ggml_integration.py 11 KB

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