test_unity_cpp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403
  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(
  102. nb, np.array(range(11 * 21), dtype=np.float32).reshape(ggml.shape(b))
  103. )
  104. ggml.ggml_set_f32_1d(b, 11 * 3 + 5, -1.5)
  105. assert nb[3, 5] == -1.5
  106. sum_rows = ggml.ggml_sum_rows(ctx, b)
  107. gf = ggml.ggml_build_forward(sum_rows)
  108. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  109. np_sum_rows = np.sum(nb, axis=-1, keepdims=True)
  110. assert np_sum_rows.shape == ggml.shape(sum_rows)
  111. for i in range(11):
  112. assert np_sum_rows[i] == ggml.ggml_get_f32_1d(sum_rows, i)
  113. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, 12, 22, 32)
  114. for i in range(12 * 22 * 32):
  115. ggml.ggml_set_f32_1d(c, i, i)
  116. nc = ggml.to_numpy(c)
  117. assert ggml.shape(c) == (32, 22, 12)
  118. assert nc[3, 5, 11] == 22 * 12 * 3 + 12 * 5 + 11
  119. assert np.allclose(
  120. nc, np.array(range(12 * 22 * 32), dtype=np.float32).reshape(ggml.shape(c))
  121. )
  122. ggml.ggml_set_f32_1d(c, 22 * 12 * 3 + 12 * 5 + 11, -1.5)
  123. assert nc[3, 5, 11] == -1.5
  124. def test_from_numpy_works_with_f32(ctx: Ctx) -> None:
  125. a = np.random.normal(size=(10,)).astype(dtype=np.float32)
  126. ga = ggml.from_numpy(ctx, a)
  127. assert ggml.shape(ga) == (10,)
  128. assert ggml.nb(ga) == ggml.nb(ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F32, 10))
  129. assert np.allclose(a, ggml.to_numpy(ga))
  130. a = np.random.normal(size=(11, 21)).astype(dtype=np.float32)
  131. ga = ggml.from_numpy(ctx, a)
  132. assert ggml.shape(ga) == (11, 21)
  133. assert ggml.nb(ga) == ggml.nb(
  134. ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F32, *a.shape[::-1])
  135. )
  136. assert np.allclose(a, ggml.to_numpy(ga))
  137. a = np.random.normal(size=(12, 22, 32)).astype(dtype=np.float32)
  138. ga = ggml.from_numpy(ctx, a)
  139. assert ggml.shape(ga) == (12, 22, 32)
  140. assert ggml.nb(ga) == ggml.nb(
  141. ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F32, *a.shape[::-1])
  142. )
  143. assert np.allclose(a, ggml.to_numpy(ga))
  144. def test_to_numpy_works_with_f16(ctx: Ctx) -> None:
  145. # We explicitly fill the tensor otherwise they might have non-zero values in them.
  146. a = ggml.ggml_new_tensor_1d(ctx, ggml.GGML_TYPE_F16, 10)
  147. na = ggml.to_numpy(a)
  148. ggml.ggml_set_f32(a, 2.14)
  149. assert np.allclose(na, np.ones((10,), dtype=np.float16) * 2.14)
  150. ggml.ggml_set_f32(a, 4.28)
  151. assert np.allclose(na, np.ones((10,), dtype=np.float16) * 4.28)
  152. b = ggml.ggml_new_tensor_2d(ctx, ggml.GGML_TYPE_F16, 11, 21)
  153. nb = ggml.to_numpy(b)
  154. ggml.ggml_set_f32(b, 4.18)
  155. assert np.allclose(nb, np.ones((21, 11), dtype=np.float16) * 4.18)
  156. ggml.ggml_set_f32(b, 5.12)
  157. assert np.allclose(nb, np.ones((21, 11), dtype=np.float16) * 5.12)
  158. c = ggml.ggml_new_tensor_3d(ctx, ggml.GGML_TYPE_F16, 12, 22, 32)
  159. nc = ggml.to_numpy(c)
  160. ggml.ggml_set_f32(c, 3.16)
  161. assert np.allclose(nc, np.ones((32, 22, 12), dtype=np.float16) * 3.16)
  162. ggml.ggml_set_f32(c, 5.08)
  163. assert np.allclose(nc, np.ones((32, 22, 12), dtype=np.float16) * 5.08)
  164. def test_from_numpy_works_with_f16(ctx: Ctx) -> None:
  165. a = np.random.normal(size=(10,)).astype(dtype=np.float16)
  166. ga = ggml.from_numpy(ctx, a)
  167. assert np.allclose(a, ggml.to_numpy(ga))
  168. a = np.random.normal(size=(11, 21)).astype(dtype=np.float16)
  169. ga = ggml.from_numpy(ctx, a)
  170. assert np.allclose(a, ggml.to_numpy(ga))
  171. a = np.random.normal(size=(12, 22, 32)).astype(dtype=np.float16)
  172. ga = ggml.from_numpy(ctx, a)
  173. assert np.allclose(a, ggml.to_numpy(ga))
  174. def test_ning_model_load(ctx: Ctx) -> None:
  175. pytest.skip("borken")
  176. model, vocab = ggml.unity_model_load(UNITY_MODELS / "unity-large/ggml-model.bin")
  177. print(model, vocab)
  178. example = ggml.from_file(
  179. ctx, UNITY_MODELS / "unity-large/seqs_before_conformer_block.bin", (1024, 137)
  180. )
  181. with ggml.MeasureArena() as arena:
  182. graph = ggml.unity_audio_encoder_graph(model, example)
  183. # TODO: why the extra memory ?
  184. mem_size = ggml.ggml_allocr_alloc_graph(arena, graph) + ggml.GGML_MEM_ALIGN
  185. with ggml.FixedSizeArena(mem_size) as allocr:
  186. print(
  187. f"unity_audio_encoder_graph: compute buffer size: {mem_size/1024/1024} MB"
  188. )
  189. eval_res_ptr = ggml.unity_eval(allocr, model, example, 1)
  190. eval_res = eval_res_ptr.contents
  191. inpL = ggml.to_numpy(eval_res.nodes[eval_res.n_nodes - 1])
  192. expected_raw = "-0.1308,0.0346,-0.2656,0.2873,-0.0104,0.0574,0.4033,-0.1125,-0.0460,-0.0496"
  193. expected = map(float, expected_raw.split(","))
  194. assert np.allclose(inpL[0, :10], list(expected), atol=1e-4)
  195. @pytest.fixture(scope="module")
  196. def g_model_once() -> Iterator[ctypes.c_void_p]:
  197. model_file = Path(__file__).parent / "seamlessM4T_medium.ggml"
  198. if not model_file.exists():
  199. convert_model("seamlessM4T_medium", model_file)
  200. with ggml.load_unity_ggml_file(model_file) as model:
  201. yield model
  202. @pytest.fixture()
  203. def g_model(ctx: Ctx, g_model_once: ctypes.c_void_p) -> ctypes.c_void_p:
  204. ggml.lib.fairseq2_model_set_inference_ctx(g_model_once, ctx)
  205. return g_model_once
  206. @pytest.fixture(scope="module")
  207. def pt_model() -> Iterator[Any]:
  208. model = load_unity_model("seamlessM4T_medium")
  209. print(model)
  210. model.eval()
  211. with torch.inference_mode():
  212. yield model
  213. @pytest.mark.xfail(reason="TODO")
  214. def test_hparams_code_is_up_to_date() -> None:
  215. model_file = Path(__file__).parent / "seamlessM4T_medium.ggml"
  216. hparams_header_file = model_file.with_suffix(".hparams.h")
  217. hparams_struct = hparams_header_file.read_text().strip()
  218. actual_code = (UNITY_MODELS.parent / "unity_model_loader.h").read_text()
  219. assert hparams_struct in actual_code
  220. def test_numpy_mul_mat(ctx: Ctx) -> None:
  221. slen, d_in, d_out = (5, 4, 2)
  222. # torch.nn and fairseq2.nn assumes (seq_len, dim) to represent inputs,
  223. x = np.zeros((slen, d_in), dtype=np.float32) # (seq_len, dim_in)
  224. x[0, :] = [1, 1 / 3, 0, 0]
  225. weight = np.eye(d_out, d_in, dtype=np.float32)
  226. weight[1, 1] = 1
  227. # assert weight.shape == (d_out, d_in) # (dim_out, dim_in)
  228. y_exp = x @ weight.T # (seq_len, dim_out)
  229. gx = ggml.from_numpy(ctx, x) # (dim_in, seq_len)
  230. gw = ggml.from_numpy(ctx, weight) # (dim_in, dim_out)
  231. # gb = ggml.from_numpy(ctx, linear.bias.numpy()) # (dim_out)
  232. # GGML linear impl
  233. assert ggml.ggml_can_mul_mat(gw, gx)
  234. # gy = ggml.ggml_add(ctx, ggml.ggml_mul_mat(ctx, gw, gx), gb) # (dim_out, seq_len)
  235. gy = ggml.ggml_mul_mat(ctx, gw, gx) # (dim_out, seq_len)
  236. gf = ggml.ggml_build_forward(gy)
  237. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  238. y = ggml.to_numpy(gf.nodes[gf.n_nodes - 1])
  239. assert np.allclose(y_exp, y)
  240. @torch.no_grad()
  241. def test_torch_spda_vs_ggml_flash_attn(ctx: Ctx) -> None:
  242. slen, d_in, num_heads = (5, 4, 2)
  243. torch.random.manual_seed(0)
  244. q = torch.zeros((num_heads, slen, d_in))
  245. torch.nn.init.uniform_(q, -1, 1)
  246. k = torch.zeros((num_heads, slen, d_in))
  247. torch.nn.init.uniform_(k, -1, 1)
  248. v = torch.zeros((num_heads, slen, d_in))
  249. torch.nn.init.uniform_(v, -1, 1)
  250. # Note: we are using x for both keys and queries, so every position
  251. # attends mostly to itself, hence y_exp looks a bit like arange(slen)
  252. y_exp = torch.nn.functional.scaled_dot_product_attention(q, k, v, is_causal=True)
  253. y_exp = y_exp.numpy()
  254. gq = ggml.from_numpy(ctx, q.numpy())
  255. gk = ggml.from_numpy(ctx, k.numpy())
  256. # ggml flash attention expect a different order of axis for v:
  257. gv = ggml.from_numpy(ctx, v.transpose(1, 2).contiguous().numpy())
  258. assert ggml.shape(gv) == (num_heads, d_in, slen)
  259. gy = ggml.ggml_flash_attn(ctx, gq, gk, gv, True)
  260. gf = ggml.ggml_build_forward(gy)
  261. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  262. y = ggml.to_numpy(gy)
  263. assert np.allclose(y_exp, y)
  264. def test_forward_ffn(ctx: Ctx, g_model: NativeObj, pt_model: Any) -> None:
  265. x = torch.empty((21, 1024)) # (seq_len, model_dim)
  266. torch.nn.init.uniform_(x, -1 / 32, 1 / 32)
  267. # Test FFN without LayerNorm
  268. y_exp = pt_model.text_encoder.layers[0].ffn(x).numpy()
  269. gx = ggml.from_numpy(ctx, x)
  270. gy = ggml.forward(
  271. "StandardFeedForwardNetwork", g_model, "text_encoder.layers.0.ffn", gx
  272. )
  273. gf = ggml.ggml_build_forward(gy)
  274. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  275. y = ggml.to_numpy(gf.nodes[gf.n_nodes - 1])
  276. assert np.allclose(y_exp, y, rtol=2e-2, atol=1e-4)
  277. def test_forward_layer_norm(ctx: Ctx, g_model: NativeObj, pt_model: Any) -> None:
  278. x = torch.empty((21, 1024))
  279. torch.nn.init.uniform_(x, -1, 1)
  280. y_exp = pt_model.text_encoder.layers[0].ffn_layer_norm(x).numpy()
  281. gx = ggml.from_numpy(ctx, x)
  282. gy = ggml.forward("LayerNorm", g_model, "text_encoder.layers.0.ffn_layer_norm", gx)
  283. gf = ggml.ggml_build_forward(gy)
  284. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  285. y = ggml.to_numpy(gf.nodes[gf.n_nodes - 1])
  286. assert np.allclose(y_exp, y, rtol=1e-3, atol=1e-4)
  287. def test_forward_self_attn(ctx: Ctx, g_model: NativeObj, pt_model: Any) -> None:
  288. x = torch.empty((1, 21, 1024))
  289. torch.random.manual_seed(0)
  290. torch.nn.init.uniform_(x, -1, 1)
  291. self_attn = pt_model.text_encoder.layers[0].self_attn
  292. # Replace spda by just returning queries
  293. # TODO: implement spda
  294. # self_attn.spda = lambda *qkv, **kwargs: qkv[0]
  295. gx = ggml.from_numpy(ctx, x)
  296. gy = ggml.forward(
  297. "MultiheadAttention",
  298. g_model,
  299. "text_encoder.layers.0.self_attn",
  300. gx,
  301. gx,
  302. gx,
  303. None,
  304. )
  305. gf = ggml.ggml_build_forward(gy)
  306. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  307. y = ggml.to_numpy(gy)
  308. names = "ql,q,qt,qp,kl,k,kt,kp,vl,v,vt,vp,v_cont,attn,attn_p,attn_cont,attn_reshape,outl,out"
  309. assert gf.n_nodes == len(names.split(","))
  310. gf_nodes = {}
  311. for i, name in enumerate(names.split(",")):
  312. mid = ggml.to_numpy(gf.nodes[i])
  313. # print(name, mid.shape, mid)
  314. gf_nodes[name] = mid
  315. breakpoint()
  316. y_exp = self_attn(x, None, x, x).numpy()
  317. y_exp = y_exp.squeeze(0) # remove batch dimension
  318. assert y.shape == y_exp.shape
  319. abs_diff = np.max(np.abs(y - y_exp))
  320. assert np.allclose(y_exp, y)