test_unity_cpp.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357
  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. from typing import Any
  9. from pathlib import Path
  10. from typing import Iterator
  11. from ggml import NativeObj
  12. from ggml_convert import convert_model
  13. from seamless_communication.models.unity import load_unity_model
  14. Ctx = ggml.ggml_context_p
  15. UNITY_MODELS = Path(__file__).parent / "examples/unity/models"
  16. PARAMS_16MB = ggml.ggml_init_params(mem_size=16 * 1024 * 1024, mem_buffer=None)
  17. @pytest.fixture(name="ctx")
  18. def _ctx() -> Iterator[Ctx]:
  19. """Allocate a new context with 16 MB of memory"""
  20. try:
  21. ctx = ggml.ggml_init(params=PARAMS_16MB)
  22. yield ctx
  23. finally:
  24. ggml.ggml_free(ctx)
  25. def test_ggml_bindings_work(ctx: Ctx) -> None:
  26. # Instantiate tensors
  27. x = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 1)
  28. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 1)
  29. b = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 1)
  30. # Use ggml operations to build a computational graph
  31. x2 = ggml.ggml_mul(ctx, x, x)
  32. f = ggml.ggml_add(ctx, ggml.ggml_mul(ctx, a, x2), b)
  33. gf = ggml.ggml_build_forward(f)
  34. # Set the input values
  35. ggml.ggml_set_f32(x, 2.0)
  36. ggml.ggml_set_f32(a, 3.0)
  37. ggml.ggml_set_f32(b, 4.0)
  38. # Compute the graph
  39. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  40. # Get the output value
  41. output = ggml.ggml_get_f32_1d(f, 0)
  42. assert output == 16.0
  43. def test_ggml_matmul(ctx: Ctx) -> None:
  44. # Instantiate tensors
  45. a = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 4, 2)
  46. x = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 4, 3)
  47. # Use ggml operations to build a computational graph
  48. y = ggml.ggml_mul_mat(ctx, a, x)
  49. assert ggml.shape(y) == (3, 2)
  50. gf = ggml.ggml_build_forward(y)
  51. # Set the input values
  52. ggml.ggml_set_f32(x, 0.0)
  53. for i in range(4 * 3):
  54. ggml.ggml_set_f32_1d(x, i, i)
  55. ggml.ggml_set_f32(a, 0.0)
  56. ggml.ggml_set_f32_1d(a, 1, 1.0)
  57. ggml.ggml_set_f32_1d(a, 7, 1.0)
  58. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  59. output = [[ggml.ggml_get_f32_1d(y, j * 2 + i) for j in range(3)] for i in range(2)]
  60. assert output == [[1, 5, 9], [3, 7, 11]]
  61. def test_shape_works(ctx: Ctx) -> None:
  62. """GGML shape order convention is the reverse from numpy"""
  63. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 10)
  64. assert ggml.shape(a) == (10,)
  65. b = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 11, 21)
  66. assert ggml.shape(b) == (21, 11)
  67. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, 12, 22, 32)
  68. assert ggml.shape(c) == (32, 22, 12)
  69. def test_nb_works(ctx: Ctx) -> None:
  70. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 10)
  71. assert ggml.nb(a) == (4, 40, 40, 40)
  72. b = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F16, 11, 21)
  73. assert ggml.nb(b) == (2, 22, 462, 462)
  74. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, 12, 22, 32)
  75. assert ggml.nb(c) == (4, 48, 1056, 33792)
  76. @pytest.mark.xfail(reason="TODO: fix strides")
  77. def test_strides_works(ctx: Ctx) -> None:
  78. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 10)
  79. assert ggml.strides(a) == np.ones((10,), dtype=np.float32).strides
  80. b = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 11, 21)
  81. assert ggml.strides(b) == np.ones((11, 21), dtype=np.float32).strides
  82. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, 12, 22, 32)
  83. assert ggml.strides(c) == np.ones((12, 22, 32), dtype=np.float32).strides
  84. def test_to_numpy_works_with_f32(ctx: Ctx) -> None:
  85. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 10)
  86. na = ggml.to_numpy(a)
  87. for i in range(10):
  88. ggml.ggml_set_f32_1d(a, i, i)
  89. assert na[5] == 5
  90. assert np.allclose(na, np.array(range(10), dtype=np.float32))
  91. ggml.ggml_set_f32_1d(a, 5, -1.5)
  92. assert na[5] == -1.5
  93. # Note: GGML order of dims is reversed wrt numpy shapes
  94. b = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, 11, 21)
  95. for i in range(11 * 21):
  96. ggml.ggml_set_f32_1d(b, i, i)
  97. nb = ggml.to_numpy(b)
  98. # assert nb.shape == (21, 11)
  99. assert nb[0, 5] == 5
  100. assert nb[3, 5] == 11 * 3 + 5
  101. assert np.allclose(nb, np.array(range(11 * 21), dtype=np.float32).reshape(ggml.shape(b)))
  102. ggml.ggml_set_f32_1d(b, 11 * 3 + 5, -1.5)
  103. assert nb[3, 5] == -1.5
  104. sum_rows = ggml.ggml_sum_rows(ctx, b);
  105. gf = ggml.ggml_build_forward(sum_rows)
  106. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  107. np_sum_rows = np.sum(nb, axis=-1, keepdims=True)
  108. assert np_sum_rows.shape == ggml.shape(sum_rows)
  109. for i in range(11):
  110. assert np_sum_rows[i] == ggml.ggml_get_f32_1d(sum_rows, i)
  111. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, 12, 22, 32)
  112. for i in range(12 * 22 * 32):
  113. ggml.ggml_set_f32_1d(c, i, i)
  114. nc = ggml.to_numpy(c)
  115. assert ggml.shape(c) == (32, 22, 12)
  116. assert nc[3, 5, 11] == 22 * 12 * 3 + 12 * 5 + 11
  117. assert np.allclose(nc, np.array(range(12 * 22 * 32), dtype=np.float32).reshape(ggml.shape(c)))
  118. ggml.ggml_set_f32_1d(c, 22 * 12 * 3 + 12 * 5 + 11, -1.5)
  119. assert nc[3, 5, 11] == -1.5
  120. def test_from_numpy_works_with_f32(ctx: Ctx) -> None:
  121. a = np.random.normal(size=(10,)).astype(dtype=np.float32)
  122. ga = ggml.from_numpy(ctx, a)
  123. assert ggml.shape(ga) == (10,)
  124. assert ggml.nb(ga) == ggml.nb(ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 10))
  125. assert np.allclose(a, ggml.to_numpy(ga))
  126. a = np.random.normal(size=(11, 21)).astype(dtype=np.float32)
  127. ga = ggml.from_numpy(ctx, a)
  128. assert ggml.shape(ga) == (11, 21)
  129. assert ggml.nb(ga) == ggml.nb(
  130. ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, *a.shape[::-1])
  131. )
  132. assert np.allclose(a, ggml.to_numpy(ga))
  133. a = np.random.normal(size=(12, 22, 32)).astype(dtype=np.float32)
  134. ga = ggml.from_numpy(ctx, a)
  135. assert ggml.shape(ga) == (12, 22, 32)
  136. assert ggml.nb(ga) == ggml.nb(
  137. ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, *a.shape[::-1])
  138. )
  139. assert np.allclose(a, ggml.to_numpy(ga))
  140. def test_to_numpy_works_with_f16(ctx: Ctx) -> None:
  141. # We explicitly fill the tensor otherwise they might have non-zero values in them.
  142. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F16, 10)
  143. na = ggml.to_numpy(a)
  144. ggml.ggml_set_f32(a, 2.14)
  145. assert np.allclose(na, np.ones((10,), dtype=np.float16) * 2.14)
  146. ggml.ggml_set_f32(a, 4.28)
  147. assert np.allclose(na, np.ones((10,), dtype=np.float16) * 4.28)
  148. b = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F16, 11, 21)
  149. nb = ggml.to_numpy(b)
  150. ggml.ggml_set_f32(b, 4.18)
  151. assert np.allclose(nb, np.ones((21, 11), dtype=np.float16) * 4.18)
  152. ggml.ggml_set_f32(b, 5.12)
  153. assert np.allclose(nb, np.ones((21, 11), dtype=np.float16) * 5.12)
  154. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F16, 12, 22, 32)
  155. nc = ggml.to_numpy(c)
  156. ggml.ggml_set_f32(c, 3.16)
  157. assert np.allclose(nc, np.ones((32, 22, 12), dtype=np.float16) * 3.16)
  158. ggml.ggml_set_f32(c, 5.08)
  159. assert np.allclose(nc, np.ones((32, 22, 12), dtype=np.float16) * 5.08)
  160. def test_from_numpy_works_with_f16(ctx: Ctx) -> None:
  161. a = np.random.normal(size=(10,)).astype(dtype=np.float16)
  162. ga = ggml.from_numpy(ctx, a)
  163. assert np.allclose(a, ggml.to_numpy(ga))
  164. a = np.random.normal(size=(11, 21)).astype(dtype=np.float16)
  165. ga = ggml.from_numpy(ctx, a)
  166. assert np.allclose(a, ggml.to_numpy(ga))
  167. a = np.random.normal(size=(12, 22, 32)).astype(dtype=np.float16)
  168. ga = ggml.from_numpy(ctx, a)
  169. assert np.allclose(a, ggml.to_numpy(ga))
  170. def test_ning_model_load(ctx: Ctx) -> None:
  171. pytest.skip("borken")
  172. model, vocab = ggml.unity_model_load(UNITY_MODELS / "unity-large/ggml-model.bin")
  173. print(model, vocab)
  174. example = ggml.from_file(
  175. ctx, UNITY_MODELS / "unity-large/seqs_before_conformer_block.bin", (1024, 137)
  176. )
  177. with ggml.MeasureArena() as arena:
  178. graph = ggml.unity_audio_encoder_graph(model, example)
  179. # TODO: why the extra memory ?
  180. mem_size = ggml.ggml_allocr_alloc_graph(arena, graph) + ggml.GGML_MEM_ALIGN
  181. with ggml.FixedSizeArena(mem_size) as allocr:
  182. print(
  183. f"unity_audio_encoder_graph: compute buffer size: {mem_size/1024/1024} MB"
  184. )
  185. eval_res_ptr = ggml.unity_eval(allocr, model, example, 1)
  186. eval_res = eval_res_ptr.contents
  187. inpL = ggml.to_numpy(eval_res.nodes[eval_res.n_nodes - 1])
  188. expected_raw = "-0.1308,0.0346,-0.2656,0.2873,-0.0104,0.0574,0.4033,-0.1125,-0.0460,-0.0496"
  189. expected = map(float, expected_raw.split(","))
  190. assert np.allclose(inpL[0, :10], list(expected), atol=1e-4)
  191. @pytest.fixture(scope="module")
  192. def g_model() -> NativeObj:
  193. model_file = Path(__file__).parent / "seamlessM4T_medium.ggml"
  194. if not model_file.exists():
  195. convert_model("seamlessM4T_medium", model_file)
  196. return ggml.load_unity_ggml_file(model_file)
  197. @pytest.fixture(scope="module")
  198. def pt_model() -> Iterator[Any]:
  199. model = load_unity_model("seamlessM4T_medium")
  200. print(model)
  201. model.eval()
  202. with torch.inference_mode():
  203. yield model
  204. @pytest.mark.xfail(reason="TODO")
  205. def test_hparams_code_is_up_to_date() -> None:
  206. model_file = Path(__file__).parent / "seamlessM4T_medium.ggml"
  207. hparams_header_file = model_file.with_suffix(".hparams.h")
  208. hparams_struct = hparams_header_file.read_text().strip()
  209. actual_code = (UNITY_MODELS.parent / "unity_model_loader.h").read_text()
  210. assert hparams_struct in actual_code
  211. def test_forward_linear(ctx: Ctx) -> None:
  212. slen, d_in, d_out = (5, 4, 2)
  213. # torch.nn and fairseq2.nn assumes (seq_len, dim) to represent inputs,
  214. x = np.zeros((slen, d_in), dtype=np.float32) # (seq_len, dim_in)
  215. # torch.nn.init.uniform_(x, -1, 1)
  216. x[0, :] = [1, 1/3, 0, 0]
  217. # linear = fairseq2.nn.Linear(d_in, d_out, bias=False)
  218. weight = np.eye(d_out, d_in, dtype=np.float32)
  219. weight[1, 1] = 1
  220. # assert weight.shape == (d_out, d_in) # (dim_out, dim_in)
  221. y_exp = (x @ weight.T) # (seq_len, dim_out)
  222. gx = ggml.from_numpy(ctx, x) # (dim_in, seq_len)
  223. gw = ggml.from_numpy(ctx, weight) # (dim_in, dim_out)
  224. # gb = ggml.from_numpy(ctx, linear.bias.numpy()) # (dim_out)
  225. # GGML linear impl
  226. assert ggml.ggml_can_mul_mat(gw, gx)
  227. # gy = ggml.ggml_add(ctx, ggml.ggml_mul_mat(ctx, gw, gx), gb) # (dim_out, seq_len)
  228. gy = ggml.ggml_mul_mat(ctx, gw, gx) # (dim_out, seq_len)
  229. gf = ggml.ggml_build_forward(gy)
  230. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  231. y = ggml.to_numpy(gf.nodes[gf.n_nodes - 1])
  232. assert np.allclose(y_exp, y)
  233. def test_forward_ffn(ctx: Ctx, g_model: NativeObj, pt_model: Any) -> None:
  234. x = torch.empty((1024))
  235. torch.nn.init.uniform_(x, -1, 1)
  236. # Test FFN without LayerNorm
  237. y_exp = pt_model.text_encoder.layers[0].ffn(x).numpy()
  238. gx = ggml.from_numpy(ctx, x)
  239. gy = ggml.forward(
  240. "StandardFeedForwardNetwork", g_model, "text_encoder.layers.0.ffn", gx
  241. )
  242. gf = ggml.ggml_build_forward(gy)
  243. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  244. y = ggml.to_numpy(gf.nodes[gf.n_nodes - 1]).reshape(-1)
  245. abs_diff = np.max(np.abs(y - y_exp))
  246. assert abs_diff < 1e-2
  247. assert np.allclose(y_exp, y, rtol=1e-3)
  248. def test_forward_layer_norm(ctx: Ctx, g_model: NativeObj, pt_model: Any) -> None:
  249. x = torch.empty((1024,))
  250. torch.nn.init.uniform_(x, -1, 1)
  251. y_exp = pt_model.text_encoder.layers[0].ffn_layer_norm(x).numpy()
  252. gx = ggml.from_numpy(ctx, x)
  253. gy = ggml.forward("LayerNorm", g_model, "text_encoder.layers.0.ffn_layer_norm", gx)
  254. gf = ggml.ggml_build_forward(gy)
  255. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  256. y = ggml.to_numpy(gf.nodes[gf.n_nodes - 1]).reshape(-1)
  257. abs_diff = np.max(np.abs(y - y_exp))
  258. assert np.allclose(y_exp, y)
  259. def test_forward_self_attn(ctx: Ctx, g_model: NativeObj, pt_model: Any) -> None:
  260. x = torch.empty((1, 25, 1024))
  261. torch.nn.init.uniform_(x, -1, 1)
  262. self_attn = pt_model.text_encoder.layers[0].self_attn
  263. # Replace spda by just returning queries
  264. # TODO: implement spda
  265. self_attn.spda = lambda *qkv, **kwargs: qkv[0]
  266. y_exp = self_attn(x, None, x, x).numpy()
  267. gx = ggml.from_numpy(ctx, x)
  268. gy = ggml.forward(
  269. "MultiheadAttention",
  270. g_model,
  271. "text_encoder.layers.0.self_attn",
  272. gx,
  273. gx,
  274. gx,
  275. None,
  276. )
  277. gf = ggml.ggml_build_forward(gy)
  278. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  279. y = ggml.to_numpy(gf.nodes[gf.n_nodes - 1]).reshape(-1)
  280. abs_diff = np.max(np.abs(y - y_exp))
  281. assert np.allclose(y_exp, y)