test_unity_cpp.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 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. FAIRSEQ2_CPP = Path(__file__).parent / "examples/unity/fairseq2.cpp"
  25. UNITY_FLASH_ATTN = "\n# define UNITY_FLASH_ATTN 0\n" not in FAIRSEQ2_CPP.read_text()
  26. @pytest.fixture(name="ctx")
  27. def _ctx() -> Iterator[Ctx]:
  28. """Allocate a new context with 1024 MB of memory"""
  29. try:
  30. ctx = ggml.ggml_init(params=CTX_PARAMS)
  31. with torch.inference_mode():
  32. yield ctx
  33. finally:
  34. ggml.ggml_free(ctx)
  35. @functools.lru_cache()
  36. def _load_g_model_once() -> NativeObj:
  37. model_file = Path(__file__).parent / "seamlessM4T_medium.ggml"
  38. if not model_file.exists():
  39. convert_model("seamlessM4T_medium", model_file)
  40. return ggml.load_unity_ggml_file(model_file)
  41. @pytest.fixture()
  42. def g_model(ctx: Ctx) -> c_void_p:
  43. model = _load_g_model_once()
  44. ggml.lib.fairseq2_model_set_inference_ctx(model.ptr, ctx)
  45. return model.ptr
  46. @functools.lru_cache(maxsize=1)
  47. def load_translator() -> Translator:
  48. return Translator(
  49. "seamlessM4T_medium", "vocoder_36langs", torch.device("cpu"), torch.float32
  50. )
  51. def load_pt_model() -> Any:
  52. return load_translator().model
  53. @pytest.mark.xfail(reason="TODO")
  54. def test_hparams_code_is_up_to_date() -> None:
  55. model_file = Path(__file__).parent / "seamlessM4T_medium.ggml"
  56. hparams_header_file = model_file.with_suffix(".hparams.h")
  57. hparams_struct = hparams_header_file.read_text().strip()
  58. actual_code = (UNITY_MODELS.parent / "unity_model_loader.h").read_text()
  59. assert hparams_struct in actual_code
  60. def test_causal_attention_mask(ctx: Ctx):
  61. x = torch.zeros((1, 10, 32))
  62. generator = fairseq2.nn.transformer.CausalAttentionMaskGenerator()
  63. mask_exp = generator(x).numpy()
  64. gx = ggml.from_numpy(ctx, x)
  65. gmask = ggml.causal_attention_mask(ctx, gx)
  66. mask = ggml.to_numpy(gmask)
  67. gf = ggml.ggml_build_forward(gmask)
  68. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  69. assert mask_exp.shape == (10, 10)
  70. assert mask.shape == (10, 10)
  71. assert np.all(mask == mask_exp)
  72. x = x[:, :8, :]
  73. mask_exp = generator(x).numpy()
  74. gx = ggml.from_numpy(ctx, x)
  75. gmask = ggml.causal_attention_mask(ctx, gx)
  76. mask = ggml.to_numpy(gmask)
  77. gf = ggml.ggml_build_forward(gmask)
  78. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  79. assert mask_exp.shape == (8, 8)
  80. assert mask.shape == (8, 8)
  81. assert np.all(mask == mask_exp)
  82. def test_LayerNorm_forward(ctx: Ctx, g_model: c_void_p) -> None:
  83. x = torch.empty((2, 21, 1024))
  84. torch.nn.init.uniform_(x, -1, 1)
  85. pt_model = load_pt_model()
  86. y_exp = pt_model.text_encoder.layers[0].ffn_layer_norm(x).numpy()
  87. gx = ggml.from_numpy(ctx, x)
  88. gy = ggml.forward("LayerNorm", g_model, "text_encoder.layers.0.ffn_layer_norm", gx)
  89. ggml.build_and_compute(ctx, gy)
  90. y = ggml.to_numpy(gy)
  91. assert np.allclose(y_exp, y, atol=1e-5)
  92. def test_Linear_forward(ctx: Ctx, g_model: c_void_p) -> None:
  93. x = torch.empty((2, 21, 1024))
  94. torch.nn.init.uniform_(x, -1, 1)
  95. pt_model = load_pt_model()
  96. y_exp = pt_model.text_encoder.layers[0].ffn.inner_proj(x).numpy()
  97. gx = ggml.from_numpy(ctx, x)
  98. gy = ggml.forward("Linear", g_model, "text_encoder.layers.0.ffn.inner_proj", gx)
  99. ggml.build_and_compute(ctx, gy)
  100. y = ggml.to_numpy(gy)
  101. assert np.allclose(y_exp, y, atol=1e-5)
  102. def test_FeedForwardNetwork_forward(ctx: Ctx, g_model: c_void_p) -> None:
  103. x = torch.empty((2, 21, 1024)) # (bs, seq_len, model_dim)
  104. torch.nn.init.uniform_(x, -1 / 32, 1 / 32)
  105. # Test FFN without LayerNorm
  106. pt_model = load_pt_model()
  107. y_exp = pt_model.text_encoder.layers[0].ffn(x).numpy()
  108. gx = ggml.from_numpy(ctx, x)
  109. gy = ggml.forward(
  110. "StandardFeedForwardNetwork", g_model, "text_encoder.layers.0.ffn", gx
  111. )
  112. ggml.build_and_compute(ctx, gy)
  113. y = ggml.to_numpy(gy)
  114. assert np.allclose(y_exp, y, atol=1e-5)
  115. def _name(tensor: ggml.ggml_tensor_p) -> bytes:
  116. try:
  117. return tensor.contents.name # type: ignore[no-any-return]
  118. except ValueError:
  119. return b"???"
  120. def test_MultiheadAttention_forward(ctx: Ctx, g_model: c_void_p) -> None:
  121. x = torch.empty((2, 21, 1024))
  122. torch.random.manual_seed(0)
  123. torch.nn.init.uniform_(x, -1, 1)
  124. pt_model = load_pt_model()
  125. self_attn = pt_model.text_encoder.layers[0].self_attn
  126. # Note: we use different lengths for queries and keys,
  127. # this tests the implementation in decoding context too.
  128. # Note2: ggml_flash_attn requires that we have more keys than queries
  129. gxq = ggml.from_numpy(ctx, x[:, :11, :].contiguous())
  130. gx = ggml.from_numpy(ctx, x)
  131. ggml.ggml_set_name(gx, b"x")
  132. gy = ggml.forward(
  133. "MultiheadAttention",
  134. g_model,
  135. "text_encoder.layers.0.self_attn",
  136. gxq,
  137. gx,
  138. gx,
  139. None, # TODO: tests with causal attention masks
  140. )
  141. gf = ggml.ggml_build_forward(gy)
  142. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  143. q_exp = self_attn.q_proj(x[:, :11, :]).numpy()
  144. y = ggml.to_numpy(gy)
  145. nodes = {}
  146. for i in range(gf.n_nodes):
  147. name = _name(gf.nodes[i])
  148. children = [_name(gf.nodes[i].contents.src[j]) for j in range(2)]
  149. print(name, f"op({gf.nodes[i].contents.op})", children)
  150. nodes[name] = ggml.to_numpy(gf.nodes[i])
  151. attn_weights_hook = fairseq2.nn.transformer.StoreAttentionWeights([])
  152. self_attn.register_attn_weight_hook(attn_weights_hook)
  153. y_exp = self_attn(x[:, :11, :], None, x, x).numpy()
  154. q = nodes[b"q"]
  155. assert q.shape == q_exp.shape
  156. assert np.allclose(q_exp, q, atol=1e-5)
  157. # with flash_attn we don't have attn_weights
  158. if not UNITY_FLASH_ATTN:
  159. attn_weights = nodes[b"attn_weights"]
  160. [attn_weights_exp] = attn_weights_hook._storage
  161. attn_weights_exp = attn_weights_exp.numpy()
  162. assert attn_weights_exp.shape == attn_weights.shape
  163. # GGML is very agressively reducing small softmax weights to 0,
  164. # so the error isn't that small
  165. assert np.allclose(attn_weights_exp, attn_weights, atol=1e-3)
  166. # But the sums should be close to 1
  167. assert np.allclose(np.sum(attn_weights, axis=-1), np.ones((2 * 16, 11)))
  168. # And the maximum index should match the original ones.
  169. assert np.allclose(
  170. np.argmax(attn_weights_exp, axis=-1), np.argmax(attn_weights, axis=-1)
  171. )
  172. assert y.shape == y_exp.shape
  173. assert np.allclose(y_exp, y, atol=1e-4 if UNITY_FLASH_ATTN else 1e-2)
  174. def test_StandardTransformerEncoderLayer_forward(
  175. ctx: Ctx, g_model: c_void_p
  176. ) -> None:
  177. x = torch.empty((2, 21, 1024))
  178. padding_mask = torch.ones((2, 21))
  179. torch.random.manual_seed(0)
  180. torch.nn.init.uniform_(x, -1, 1)
  181. pt_model = load_pt_model()
  182. layer = pt_model.text_encoder.layers[0]
  183. gx = ggml.from_numpy(ctx, x)
  184. ggml.ggml_set_name(gx, b"x")
  185. gpad = ggml.from_numpy(ctx, padding_mask)
  186. ggml.ggml_set_name(gpad, b"padding_mask")
  187. gy = ggml.forward(
  188. "StandardTransformerEncoderLayer",
  189. g_model,
  190. "text_encoder.layers.0",
  191. gx,
  192. None, # TODO support padding mask
  193. )
  194. gf = ggml.ggml_build_forward(gy)
  195. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  196. y = ggml.to_numpy(gy)
  197. y_exp, _ = layer(x, padding_mask)
  198. y_exp = y_exp.numpy()
  199. assert y.shape == y_exp.shape
  200. assert np.allclose(y_exp, y, atol=1e-4 if UNITY_FLASH_ATTN else 1e-2)
  201. def test_StandardTransformerEncoder_forward(
  202. ctx: Ctx, g_model: c_void_p
  203. ) -> None:
  204. x = torch.empty((2, 21, 1024))
  205. padding_mask = torch.ones((2, 21))
  206. torch.random.manual_seed(0)
  207. torch.nn.init.uniform_(x, -1, 1)
  208. gx = ggml.from_numpy(ctx, x)
  209. ggml.ggml_set_name(gx, b"x")
  210. gpad = ggml.from_numpy(ctx, padding_mask)
  211. ggml.ggml_set_name(gpad, b"padding_mask")
  212. gy = ggml.forward(
  213. "StandardTransformerEncoder",
  214. g_model,
  215. "text_encoder",
  216. gx,
  217. None, # TODO support padding mask
  218. )
  219. gf = ggml.ggml_build_forward(gy)
  220. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  221. y = ggml.to_numpy(gy)
  222. pt_model = load_pt_model()
  223. y_exp, _ = pt_model.text_encoder(x, padding_mask)
  224. y_exp = y_exp.numpy()
  225. assert y.shape == y_exp.shape
  226. assert np.allclose(y_exp, y, atol=1e-4 if UNITY_FLASH_ATTN else 1e-2)
  227. def test_PositionalEmbedding_forward(ctx: Ctx, g_model: c_void_p) -> None:
  228. seq = torch.zeros((4, 20, 1024), dtype=torch.float32)
  229. # this _legacy_pad_idx is suspicious. Shouldn't the model use 1 ? But
  230. # this is consistent with pt_model.text_decoder_frontend.pos_encoder._sin_offset
  231. pos_encoder = fairseq2.nn.SinusoidalPositionEncoder(1024, 55, _legacy_pad_idx=0)
  232. y_exp = pos_encoder(seq, None)[0].numpy()
  233. gseq = ggml.from_numpy(ctx, seq[0].numpy())
  234. ggml.ggml_set_name(gseq, b"seq")
  235. gy = ggml.forward(
  236. "PositionalEmbedding", g_model, "text_decoder_frontend.pos_encoder", gseq
  237. )
  238. gf = ggml.ggml_build_forward(gy)
  239. ggml.ggml_graph_compute_with_ctx(ctx, ctypes.pointer(gf), 1)
  240. y = ggml.to_numpy(gy)
  241. assert y.shape == y_exp.shape
  242. assert np.allclose(y_exp, y, atol=1e-6)
  243. def test_TransformerEmbeddingFrontend_forward(
  244. ctx: Ctx, g_model: c_void_p
  245. ) -> None:
  246. seq = torch.arange(2 * 20).reshape(2, 20)
  247. seq[1, 15:] = 0 # padding for second sentence
  248. seq_len = torch.tensor([20, 15])
  249. gseq = ggml.from_numpy(ctx, seq.numpy().astype(np.int32))
  250. ggml.ggml_set_name(gseq, b"seq")
  251. gy = ggml.forward(
  252. "TransformerEmbeddingFrontend", g_model, "text_decoder_frontend", gseq
  253. )
  254. ggml.build_and_compute(ctx, gy)
  255. y = ggml.to_numpy(gy)
  256. pt_model = load_pt_model()
  257. y_exp, _ = pt_model.text_decoder_frontend(seq, seq_len)
  258. y_exp = y_exp.numpy()
  259. assert y.shape == y_exp.shape
  260. assert np.allclose(y_exp, y, atol=1e-6)
  261. def test_StandardTransformerDecoder_forward(
  262. ctx: Ctx, g_model: c_void_p
  263. ) -> None:
  264. x = torch.empty((2, 13, 1024))
  265. encoder_out = torch.empty((2, 21, 1024))
  266. padding_mask = torch.ones((2, 13))
  267. torch.random.manual_seed(0)
  268. torch.nn.init.uniform_(x, -1, 1)
  269. torch.nn.init.uniform_(encoder_out, -1, 1)
  270. gx = ggml.from_numpy(ctx, x)
  271. ggml.ggml_set_name(gx, b"x")
  272. gpad = ggml.from_numpy(ctx, padding_mask)
  273. ggml.ggml_set_name(gpad, b"padding_mask")
  274. genc = ggml.from_numpy(ctx, encoder_out)
  275. gy = ggml.forward(
  276. "StandardTransformerDecoder",
  277. g_model,
  278. "text_decoder",
  279. gx,
  280. None, # TODO support padding mask,
  281. genc,
  282. None,
  283. )
  284. ggml.build_and_compute(ctx, gy)
  285. y = ggml.to_numpy(gy)
  286. pt_model = load_pt_model()
  287. y_exp, _ = pt_model.text_decoder(x, padding_mask, encoder_out, None)
  288. y_exp = y_exp.numpy()
  289. assert y.shape == y_exp.shape
  290. assert np.allclose(y_exp, y, atol=1e-4 if UNITY_FLASH_ATTN else 1e-3)
  291. def test_t2tt(ctx: Ctx, g_model: c_void_p):
  292. src_lang = "eng"
  293. src_text = "We are all in a yellow submarine."
  294. tgt_lang = "fra"
  295. sample_file = Path(__file__).parent / "sample_input.npz"
  296. beam_size = 2
  297. if not sample_file.exists():
  298. translator = load_translator()
  299. device = translator.device
  300. token_encoder = translator.text_tokenizer.create_encoder(
  301. task="translation", lang=src_lang, mode="source", device=device
  302. )
  303. src = translator.collate(token_encoder(src_text))
  304. text_out, _ = translator.get_prediction(
  305. translator.model,
  306. translator.text_tokenizer,
  307. translator.unit_tokenizer,
  308. src,
  309. input_modality=Modality.TEXT,
  310. output_modality=Modality.TEXT,
  311. tgt_lang=tgt_lang,
  312. beam_size=beam_size,
  313. )
  314. tgt_text = str(text_out.sentences[0])
  315. assert tgt_text == "Nous sommes tous dans un sous-marin jaune."
  316. hypotheses = [
  317. {
  318. "seq": h.seq.tolist(),
  319. "score": h.score.item(),
  320. "step_scores": h.step_scores.numpy(),
  321. }
  322. for h in text_out.generator_output.results[0]
  323. ]
  324. np.savez(
  325. sample_file,
  326. encoder_output=text_out.encoder_output.numpy(),
  327. encoder_padding_mask=text_out.encoder_padding_mask.numpy(),
  328. hypotheses=hypotheses,
  329. )
  330. # allow_pickle to load the hyp dicts
  331. text_out = np.load(sample_file, allow_pickle=True)
  332. encoder_out = ggml.from_numpy(ctx, text_out["encoder_output"])
  333. encoder_padding_mask = ggml.from_numpy(ctx, text_out["encoder_padding_mask"])
  334. prefix_seq = np.array(text_out["hypotheses"][0]["seq"][:2]).astype(np.int32)
  335. max_seq_len = max(len(h["seq"]) for h in text_out["hypotheses"])
  336. job = ggml.SequenceGeneratorJob()
  337. job.opts.beam_size = beam_size
  338. job.opts.min_seq_len = 1
  339. job.opts.soft_max_seq_len_a = 1
  340. job.opts.soft_max_seq_len_b = 200
  341. job.opts.hard_max_seq_len = int(max_seq_len * 1.5)
  342. job.opts.len_penalty = 1.0
  343. job.opts.unk_penalty = 0.0
  344. job.opts.normalize_scores = True
  345. job.prefix_seq = ggml.from_numpy(ctx, prefix_seq)
  346. job.pad_idx = 0
  347. job.unk_idx = 1
  348. job.bos_idx = 2
  349. job.eos_idx = 3
  350. result_ptr = ggml.generate_sequence(
  351. g_model, job, encoder_out, encoder_padding_mask, ctx
  352. )
  353. results = [result_ptr[i] for i in range(beam_size)]
  354. assert len(results) == len(text_out["hypotheses"])
  355. for g_hyp, exp in zip(results, text_out["hypotheses"]):
  356. g_tokens = list(ggml.to_numpy(g_hyp.seq))
  357. g_step_scores = ggml.to_numpy(g_hyp.step_scores)
  358. assert g_tokens == exp["seq"]
  359. assert g_hyp.score == pytest.approx(exp["score"], rel=1e-2)
  360. # The score error is big, this may negatively impact the beam search.
  361. assert np.allclose(g_step_scores, exp["step_scores"], atol=0.1)