unity.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. #include "ggml/ggml.h"
  2. #include "ggml/ggml-alloc.h"
  3. #include "common.h"
  4. #include "common-ggml.h"
  5. #include "fairseq2.h"
  6. #include <cassert>
  7. #include <cmath>
  8. #include <cstdio>
  9. #include <cstring>
  10. #include <fstream>
  11. #include <map>
  12. #include <string>
  13. #include <vector>
  14. #include <iostream>
  15. // default hparams
  16. struct unity_hparams {
  17. int32_t n_text_vocab = 256206;
  18. int32_t n_unit_vocab = 10084;
  19. int32_t n_audio_enc_dim = 1024;
  20. int32_t n_audio_enc_ffn_dim = 4096;
  21. int32_t n_audio_enc_feat_dim = 160;
  22. int32_t n_audio_enc_layer = 24;
  23. int32_t n_audio_enc_head = 16;
  24. int32_t ftype = 1;
  25. float eps = 1e-5f;
  26. };
  27. struct audio_enc_layer {
  28. struct LayerNorm self_attn_layer_norm;
  29. struct ggml_tensor * self_attn_linear_k_w;
  30. struct ggml_tensor * self_attn_linear_k_b;
  31. struct ggml_tensor * self_attn_linear_q_w;
  32. struct ggml_tensor * self_attn_linear_q_b;
  33. struct ggml_tensor * self_attn_linear_v_w;
  34. struct ggml_tensor * self_attn_linear_v_b;
  35. struct ggml_tensor * self_attn_linear_out_w;
  36. struct ggml_tensor * self_attn_linear_out_b;
  37. struct ggml_tensor * self_attn_linear_pos_w;
  38. struct ggml_tensor * self_attn_pos_bias_u;
  39. struct ggml_tensor * self_attn_pos_bias_v;
  40. struct LayerNorm conv_layer_norm;
  41. struct ggml_tensor * conv_pointwise_conv1_w;
  42. struct ggml_tensor * conv_depthwise_conv_w;
  43. struct ggml_tensor * conv_batch_norm_w;
  44. struct ggml_tensor * conv_batch_norm_b;
  45. struct ggml_tensor * conv_batch_norm_running_mean;
  46. struct ggml_tensor * conv_batch_norm_running_var;
  47. struct ggml_tensor * conv_batch_norm_num_batches_tracked;
  48. struct ggml_tensor * conv_pointwise_conv2_w;
  49. struct LayerNorm ffn1_layer_norm;
  50. struct ggml_tensor * ffn1_w1;
  51. struct ggml_tensor * ffn1_b1;
  52. struct ggml_tensor * ffn1_w2;
  53. struct ggml_tensor * ffn1_b2;
  54. struct LayerNorm ffn2_layer_norm;
  55. struct ggml_tensor * ffn2_w1;
  56. struct ggml_tensor * ffn2_b1;
  57. struct ggml_tensor * ffn2_w2;
  58. struct ggml_tensor * ffn2_b2;
  59. struct LayerNorm final_layer_norm;
  60. };
  61. // struct ggml_tensor * conv_ln;
  62. // struct ggml_tensor * conv_pool_1d;
  63. // model def
  64. struct unity_model {
  65. unity_hparams hparams;
  66. // audio encoder
  67. struct ggml_tensor * post_extract_proj_w;
  68. struct ggml_tensor * post_extract_proj_b;
  69. struct ggml_tensor * audio_enc_pos_conv_wg;
  70. struct ggml_tensor * audio_enc_pos_conv_wv;
  71. struct ggml_tensor * audio_enc_pos_conv_b;
  72. struct LayerNorm audio_enc_layer_norm;
  73. struct ggml_tensor * audio_enc_pos_enc_w;
  74. struct LayerNorm layer_norm;
  75. struct ggml_tensor * memory_k;
  76. struct ggml_tensor * memory_v;
  77. std::vector<audio_enc_layer> audio_enc_layers;
  78. // text encoder
  79. // std::vector<text_enc_layer> text_enc_layers;
  80. // adaptor
  81. // std::vector<adapter_layer> adapter_layers;
  82. // text decoder
  83. std::vector<TransformerDecoderLayer> text_dec_layers;
  84. // unit decoder
  85. // std::vector<unit_dec_layer> unit_dec_layers;
  86. //
  87. struct ggml_context * ctx;
  88. std::map<std::string, struct ggml_tensor *> tensors;
  89. };
  90. extern "C" unity_model* unity_model_alloc() {
  91. return new unity_model;
  92. }
  93. extern "C" void unity_model_free(unity_model* model) {
  94. delete model;
  95. }
  96. extern "C" gpt_vocab* gpt_vocab_alloc() {
  97. return new gpt_vocab;
  98. }
  99. extern "C" void gpt_vocab_free(gpt_vocab* vocab) {
  100. delete vocab;
  101. }
  102. // model load
  103. extern "C" bool unity_model_load(const char* fname, unity_model& model, gpt_vocab& raw_vocab) {
  104. // unity_model& model = *raw_model;
  105. printf("%s: loading model from '%s'\n", __func__, fname);
  106. auto fin = std::ifstream(std::string(fname), std::ios::binary);
  107. if (!fin) {
  108. fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname);
  109. return false;
  110. }
  111. // verify magic
  112. {
  113. uint32_t magic;
  114. fin.read((char *) &magic, sizeof(magic));
  115. if (magic != GGML_FILE_MAGIC) {
  116. fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname);
  117. return false;
  118. }
  119. }
  120. // load hparams
  121. {
  122. auto & hparams = model.hparams;
  123. fin.read((char *) &hparams.n_text_vocab, sizeof(hparams.n_text_vocab));
  124. fin.read((char *) &hparams.n_audio_enc_dim, sizeof(hparams.n_audio_enc_dim));
  125. fin.read((char *) &hparams.n_audio_enc_ffn_dim, sizeof(hparams.n_audio_enc_ffn_dim));
  126. fin.read((char *) &hparams.n_audio_enc_feat_dim, sizeof(hparams.n_audio_enc_feat_dim));
  127. fin.read((char *) &hparams.n_audio_enc_layer, sizeof(hparams.n_audio_enc_layer));
  128. fin.read((char *) &hparams.n_audio_enc_head, sizeof(hparams.n_audio_enc_head));
  129. fin.read((char *) &hparams.ftype, sizeof(hparams.ftype));
  130. const int32_t qntvr = hparams.ftype / GGML_QNT_VERSION_FACTOR;
  131. printf("%s: n_text_vocab = %d\n", __func__, hparams.n_text_vocab);
  132. printf("%s: n_audio_enc_dim = %d\n", __func__, hparams.n_audio_enc_dim);
  133. printf("%s: n_audio_enc_ffn_dim = %d\n", __func__, hparams.n_audio_enc_ffn_dim);
  134. printf("%s: n_audio_enc_feat_dim = %d\n", __func__, hparams.n_audio_enc_feat_dim);
  135. printf("%s: n_audio_enc_layer = %d\n", __func__, hparams.n_audio_enc_layer);
  136. printf("%s: n_audio_enc_head = %d\n", __func__, hparams.n_audio_enc_head);
  137. printf("%s: ftype = %d\n", __func__, hparams.ftype);
  138. printf("%s: qntvr = %d\n", __func__, qntvr);
  139. hparams.ftype %= GGML_QNT_VERSION_FACTOR;
  140. }
  141. // for the big tensors, we have the option to store the data in 16-bit floats or quantized
  142. // in order to save memory and also to speed up the computation
  143. ggml_type wtype = ggml_ftype_to_ggml_type((ggml_ftype) (model.hparams.ftype));
  144. if (wtype == GGML_TYPE_COUNT) {
  145. fprintf(stderr, "%s: invalid model file '%s' (bad ftype value %d)\n",
  146. __func__, fname, model.hparams.ftype);
  147. return false;
  148. }
  149. auto & ctx = model.ctx;
  150. size_t ctx_size = 0;
  151. {
  152. const auto & hparams = model.hparams;
  153. const int n_audio_enc_dim = hparams.n_audio_enc_dim;
  154. const int n_audio_enc_ffn_dim = hparams.n_audio_enc_ffn_dim;
  155. const int n_audio_enc_layer = hparams.n_audio_enc_layer;
  156. const int n_ctx = 4096; // 20ms * 4096 = 80s
  157. // const int n_text_vocab = hparams.n_text_vocab;
  158. const int kernel_size = 31;
  159. ctx_size += n_audio_enc_layer*n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32); // self_attn_layer_norm.weight
  160. ctx_size += n_audio_enc_layer*n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32); // self_attn_layer_norm.bias
  161. ctx_size += n_audio_enc_layer*(5*n_audio_enc_dim*n_audio_enc_dim*ggml_type_sizef(wtype)); // self_attn_w
  162. ctx_size += n_audio_enc_layer*(4*n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32)); // self_attn_b
  163. ctx_size += n_audio_enc_layer*n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32); // conv_layer_norm.weight
  164. ctx_size += n_audio_enc_layer*n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32); // conv_layer_norm.bias
  165. ctx_size += n_audio_enc_layer*(n_audio_enc_dim*n_audio_enc_dim*2*ggml_type_sizef(wtype)); // conv_pointwise_conv1_w
  166. ctx_size += n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32); // conv_batch_norm_w
  167. ctx_size += n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32); // conv_batch_norm_b
  168. ctx_size += n_audio_enc_layer*(n_audio_enc_dim*n_audio_enc_dim*kernel_size*ggml_type_sizef(wtype)); // conv_depthwise_conv_w
  169. ctx_size += n_audio_enc_layer*(n_audio_enc_dim*n_audio_enc_dim*ggml_type_sizef(wtype)); // conv_pointwise_conv2_w
  170. ctx_size += 2 * n_audio_enc_layer * (n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32)); // ffn{1,2}_layer_norm.w
  171. ctx_size += 2 * n_audio_enc_layer * (n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32)); // ffn{1,2}_layer_norm.bias
  172. ctx_size += 2 * n_audio_enc_layer * (2 * n_audio_enc_dim * n_audio_enc_ffn_dim * ggml_type_sizef(wtype)); // ffn{1,2}_w{1,2}
  173. ctx_size += 2 * n_audio_enc_layer * (2 * n_audio_enc_dim * ggml_type_sizef(GGML_TYPE_F32)); // ffn{1,2}_b{1,2}
  174. ctx_size += n_audio_enc_layer*(n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32)); // final_layer_norm.w
  175. ctx_size += n_audio_enc_layer*(n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32)); // final_layer_norm.bias
  176. ctx_size += n_ctx*n_audio_enc_layer*n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32); // memory_k
  177. ctx_size += n_ctx*n_audio_enc_layer*n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32); // memory_v
  178. // Adaptor
  179. // ctx_size += n_audio_enc_layer*(n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32)); // conv_ln
  180. // ctx_size += n_audio_enc_layer*(n_audio_enc_dim*ggml_type_sizef(GGML_TYPE_F32)); // conv_pool_1d
  181. // object overhead might differ depending on the structure and other miscellaneous factors
  182. ctx_size += (6 + 12*n_audio_enc_layer)*512; // updated object overhead
  183. printf("%s: ggml tensor size = %d bytes\n", __func__, (int) sizeof(ggml_tensor));
  184. printf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
  185. }
  186. // create the ggml context
  187. {
  188. struct ggml_init_params params = {
  189. /*.mem_size =*/ ctx_size,
  190. /*.mem_buffer =*/ NULL,
  191. /*.no_alloc =*/ false,
  192. };
  193. model.ctx = ggml_init(params);
  194. if (!model.ctx) {
  195. fprintf(stderr, "%s: ggml_init() failed\n", __func__);
  196. return false;
  197. }
  198. }
  199. // prepare memory for the weights
  200. {
  201. const auto & hparams = model.hparams;
  202. const int n_audio_enc_dim = hparams.n_audio_enc_dim;
  203. const int n_audio_enc_ffn_dim = hparams.n_audio_enc_ffn_dim;
  204. const int n_audio_enc_feat_dim = hparams.n_audio_enc_feat_dim;
  205. const int n_audio_enc_layer = hparams.n_audio_enc_layer;
  206. const int n_audio_enc_head = hparams.n_audio_enc_head;
  207. const int n_ctx = 4096; // 20ms * 4096 = 80s
  208. const int pos_conv_kernel_size = 128;
  209. // const int n_text_vocab = hparams.n_text_vocab;
  210. model.audio_enc_layers.resize(n_audio_enc_layer);
  211. model.audio_enc_pos_enc_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim, n_ctx * 2 - 1);
  212. model.tensors["model/enc/pos_enc/w"] = model.audio_enc_pos_enc_w;
  213. model.post_extract_proj_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_feat_dim, n_audio_enc_dim);
  214. model.post_extract_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  215. model.tensors["model/post_extract_proj/w"] = model.post_extract_proj_w;
  216. model.tensors["model/post_extract_proj/b"] = model.post_extract_proj_b;
  217. model.audio_enc_pos_conv_wg = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, pos_conv_kernel_size);
  218. model.audio_enc_pos_conv_wv = ggml_new_tensor_3d(ctx, GGML_TYPE_F32, pos_conv_kernel_size, 64, n_audio_enc_dim);
  219. model.audio_enc_pos_conv_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  220. model.tensors["model/enc/pos_conv/w_g"] = model.audio_enc_pos_conv_wg;
  221. model.tensors["model/enc/pos_conv/w_v"] = model.audio_enc_pos_conv_wv;
  222. model.tensors["model/enc/pos_conv/b"] = model.audio_enc_pos_conv_b;
  223. model.audio_enc_layer_norm.weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  224. model.audio_enc_layer_norm.bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  225. model.tensors["model/enc/layer_norm/w"] = model.audio_enc_layer_norm.weight;
  226. model.tensors["model/enc/layer_norm/b"] = model.audio_enc_layer_norm.bias;
  227. model.layer_norm.weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_feat_dim);
  228. model.layer_norm.bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_feat_dim);
  229. model.tensors["model/layer_norm/w"] = model.layer_norm.weight;
  230. model.tensors["model/layer_norm/b"] = model.layer_norm.bias;
  231. for (int i = 0; i < n_audio_enc_layer; ++i) {
  232. auto & layer = model.audio_enc_layers[i];
  233. layer.self_attn_layer_norm.weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  234. layer.self_attn_layer_norm.bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  235. layer.self_attn_linear_k_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim, n_audio_enc_dim);
  236. layer.self_attn_linear_k_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  237. layer.self_attn_linear_q_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim, n_audio_enc_dim);
  238. layer.self_attn_linear_q_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  239. layer.self_attn_linear_v_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim, n_audio_enc_dim);
  240. layer.self_attn_linear_v_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  241. layer.self_attn_linear_out_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim, n_audio_enc_dim);
  242. layer.self_attn_linear_out_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  243. layer.self_attn_linear_pos_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim, n_audio_enc_dim);
  244. layer.self_attn_pos_bias_u = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim / n_audio_enc_head, n_audio_enc_head);
  245. layer.self_attn_pos_bias_v = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim / n_audio_enc_head, n_audio_enc_head);
  246. layer.conv_layer_norm.weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  247. layer.conv_layer_norm.bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  248. layer.conv_pointwise_conv1_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim, 2*n_audio_enc_dim);
  249. layer.conv_depthwise_conv_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 31, n_audio_enc_dim);
  250. layer.conv_batch_norm_w = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  251. layer.conv_batch_norm_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  252. layer.conv_batch_norm_running_mean = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  253. layer.conv_batch_norm_running_var = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  254. layer.conv_batch_norm_num_batches_tracked = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 1);
  255. layer.conv_pointwise_conv2_w = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim, n_audio_enc_dim);
  256. layer.ffn1_layer_norm.weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  257. layer.ffn1_layer_norm.bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  258. layer.ffn1_w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim, n_audio_enc_ffn_dim);
  259. layer.ffn1_b1 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_ffn_dim);
  260. layer.ffn1_w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_ffn_dim, n_audio_enc_dim);
  261. layer.ffn1_b2 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  262. layer.ffn2_layer_norm.weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  263. layer.ffn2_layer_norm.bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  264. layer.ffn2_w1 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_dim, n_audio_enc_ffn_dim);
  265. layer.ffn2_b1 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_ffn_dim);
  266. layer.ffn2_w2 = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_audio_enc_ffn_dim, n_audio_enc_dim);
  267. layer.ffn2_b2 = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  268. layer.final_layer_norm.weight = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  269. layer.final_layer_norm.bias = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_audio_enc_dim);
  270. // map by name
  271. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_layer_norm/w"] = layer.self_attn_layer_norm.weight;
  272. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_layer_norm/b"] = layer.self_attn_layer_norm.bias;
  273. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_linear_k/w"] = layer.self_attn_linear_k_w;
  274. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_linear_k/b"] = layer.self_attn_linear_k_b;
  275. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_linear_q/w"] = layer.self_attn_linear_q_w;
  276. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_linear_q/b"] = layer.self_attn_linear_q_b;
  277. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_linear_v/w"] = layer.self_attn_linear_v_w;
  278. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_linear_v/b"] = layer.self_attn_linear_v_b;
  279. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_linear_out/w"] = layer.self_attn_linear_out_w;
  280. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_linear_out/b"] = layer.self_attn_linear_out_b;
  281. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_linear_pos/w"] = layer.self_attn_linear_pos_w;
  282. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_pos_bias/u"] = layer.self_attn_pos_bias_u;
  283. model.tensors["model/enc/h" + std::to_string(i) + "/self_attn_pos_bias/v"] = layer.self_attn_pos_bias_v;
  284. model.tensors["model/enc/h" + std::to_string(i) + "/conv_layer_norm/w"] = layer.conv_layer_norm.weight;
  285. model.tensors["model/enc/h" + std::to_string(i) + "/conv_layer_norm/b"] = layer.conv_layer_norm.bias;
  286. model.tensors["model/enc/h" + std::to_string(i) + "/conv_pointwise_conv1/w"] = layer.conv_pointwise_conv1_w;
  287. model.tensors["model/enc/h" + std::to_string(i) + "/conv_depthwise_conv/w"] = layer.conv_depthwise_conv_w;
  288. model.tensors["model/enc/h" + std::to_string(i) + "/conv_batch_norm/w"] = layer.conv_batch_norm_w;
  289. model.tensors["model/enc/h" + std::to_string(i) + "/conv_batch_norm/b"] = layer.conv_batch_norm_b;
  290. model.tensors["model/enc/h" + std::to_string(i) + "/conv_batch_norm/m"] = layer.conv_batch_norm_running_mean;
  291. model.tensors["model/enc/h" + std::to_string(i) + "/conv_batch_norm/v"] = layer.conv_batch_norm_running_var;
  292. model.tensors["model/enc/h" + std::to_string(i) + "/conv_batch_norm/n"] = layer.conv_batch_norm_num_batches_tracked;
  293. model.tensors["model/enc/h" + std::to_string(i) + "/conv_pointwise_conv2/w"] = layer.conv_pointwise_conv2_w;
  294. model.tensors["model/enc/h" + std::to_string(i) + "/ffn1_layer_norm/w"] = layer.ffn1_layer_norm.weight;
  295. model.tensors["model/enc/h" + std::to_string(i) + "/ffn1_layer_norm/b"] = layer.ffn1_layer_norm.bias;
  296. model.tensors["model/enc/h" + std::to_string(i) + "/ffn1_w_1/w"] = layer.ffn1_w1;
  297. model.tensors["model/enc/h" + std::to_string(i) + "/ffn1_w_1/b"] = layer.ffn1_b1;
  298. model.tensors["model/enc/h" + std::to_string(i) + "/ffn1_w_2/w"] = layer.ffn1_w2;
  299. model.tensors["model/enc/h" + std::to_string(i) + "/ffn1_w_2/b"] = layer.ffn1_b2;
  300. model.tensors["model/enc/h" + std::to_string(i) + "/ffn2_layer_norm/w"] = layer.ffn2_layer_norm.weight;
  301. model.tensors["model/enc/h" + std::to_string(i) + "/ffn2_layer_norm/b"] = layer.ffn2_layer_norm.bias;
  302. model.tensors["model/enc/h" + std::to_string(i) + "/ffn2_w_1/w"] = layer.ffn2_w1;
  303. model.tensors["model/enc/h" + std::to_string(i) + "/ffn2_w_1/b"] = layer.ffn2_b1;
  304. model.tensors["model/enc/h" + std::to_string(i) + "/ffn2_w_2/w"] = layer.ffn2_w2;
  305. model.tensors["model/enc/h" + std::to_string(i) + "/ffn2_w_2/b"] = layer.ffn2_b2;
  306. model.tensors["model/enc/h" + std::to_string(i) + "/final_layer_norm/w"] = layer.final_layer_norm.weight;
  307. model.tensors["model/enc/h" + std::to_string(i) + "/final_layer_norm/b"] = layer.final_layer_norm.bias;
  308. }
  309. }
  310. // load weights
  311. {
  312. size_t total_size = 0;
  313. while (true) {
  314. int32_t n_dims;
  315. int32_t length;
  316. int32_t ttype;
  317. fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
  318. fin.read(reinterpret_cast<char *>(&length), sizeof(length));
  319. fin.read(reinterpret_cast<char *>(&ttype), sizeof(ttype));
  320. if (fin.eof()) {
  321. break;
  322. }
  323. int32_t nelements = 1;
  324. int32_t ne[3] = { 1, 1, 1};
  325. for (int i = 0; i < n_dims; ++i) {
  326. fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
  327. nelements *= ne[i];
  328. }
  329. std::string name(length, 0);
  330. fin.read(&name[0], length);
  331. std::cout << "loading " << name << " " << n_dims << std::endl;
  332. if (model.tensors.find(name) == model.tensors.end()) {
  333. fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.c_str());
  334. return false;
  335. }
  336. auto tensor = model.tensors[name];
  337. if (ggml_nelements(tensor) != nelements) {
  338. std::cout << ggml_nelements(tensor) << std::endl;
  339. std::cout << nelements << std::endl;
  340. fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.c_str());
  341. return false;
  342. }
  343. if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
  344. fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
  345. __func__, name.c_str(), (int) tensor->ne[0], (int) tensor->ne[1], ne[0], ne[1]);
  346. // return false;
  347. }
  348. // for debugging
  349. if (0) {
  350. printf("%24s - [%5d, %5d], type = %6s, %6.2f MB, %9zu bytes\n", name.c_str(), ne[0], ne[1], ggml_type_name(ggml_type(ttype)), ggml_nbytes(tensor)/1024.0/1024.0, ggml_nbytes(tensor));
  351. }
  352. const size_t bpe = ggml_type_size(ggml_type(ttype));
  353. if ((nelements*bpe)/ggml_blck_size(tensor->type) != ggml_nbytes(tensor)) {
  354. fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
  355. __func__, name.c_str(), ggml_nbytes(tensor), nelements*bpe);
  356. return false;
  357. }
  358. fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
  359. // for (int i = 0; i < 10; ++i) {
  360. // std::cout << ((float *)(tensor->data))[i] << std::endl;
  361. // } // debug
  362. total_size += ggml_nbytes(tensor);
  363. }
  364. printf("%s: model size = %8.2f MB\n", __func__, total_size/1024.0/1024.0);
  365. }
  366. fin.close();
  367. return true;
  368. }
  369. extern "C" ggml_tensor* LayerNorm_forward(
  370. const LayerNorm& layer,
  371. ggml_context* ctx,
  372. ggml_tensor* cur,
  373. float eps
  374. ) {
  375. cur = ggml_norm(ctx, cur, eps);
  376. return ggml_add(
  377. ctx,
  378. ggml_mul(ctx, ggml_repeat(ctx, layer.weight, cur), cur),
  379. ggml_repeat(ctx, layer.bias, cur)
  380. );
  381. }
  382. // build the computation graph
  383. extern "C" ggml_cgraph* unity_audio_encoder_graph(
  384. const unity_model & model,
  385. ggml_tensor* input
  386. ) {
  387. const auto & hparams = model.hparams;
  388. const int n_audio_enc_dim = hparams.n_audio_enc_dim;
  389. const int n_audio_enc_ffn_dim = hparams.n_audio_enc_ffn_dim;
  390. const int n_audio_enc_layer = hparams.n_audio_enc_layer;
  391. // const int n_text_vocab = hparams.n_text_vocab;
  392. const int kernel_size = 31;
  393. // since we are using ggml-alloc, this buffer only needs enough space to hold the ggml_tensor and ggml_cgraph structs, but not the tensor data
  394. static size_t buf_size = ggml_tensor_overhead()*GGML_MAX_NODES + ggml_graph_overhead();
  395. static std::vector<uint8_t> buf(buf_size);
  396. struct ggml_init_params params = {
  397. /*.mem_size =*/ buf_size,
  398. /*.mem_buffer =*/ buf.data(),
  399. /*.no_alloc =*/ true, // the tensors will be allocated later by ggml_allocr_alloc_graph()
  400. };
  401. struct ggml_context * ctx0 = ggml_init(params);
  402. struct ggml_cgraph * gf = ggml_new_graph(ctx0);
  403. struct ggml_tensor * ffn_scale = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, 1, 1);
  404. ffn_scale->data = malloc(ggml_nbytes(ffn_scale));
  405. ggml_set_f32(ffn_scale, 0.5f);
  406. ggml_tensor* inpL = input;
  407. for (int il = 0; il < n_audio_enc_layer; ++il) {
  408. struct ggml_tensor * cur = inpL;
  409. struct ggml_tensor * residual = cur;
  410. const audio_enc_layer layer = model.audio_enc_layers[il];
  411. // FFN1: layernorm
  412. cur = LayerNorm_forward(layer.ffn1_layer_norm, ctx0, cur, hparams.eps);
  413. // FFN1: proj
  414. cur = ggml_mul_mat(ctx0, layer.ffn1_w1, cur);
  415. cur = ggml_add(ctx0, ggml_repeat(ctx0, layer.ffn1_b1, cur), cur);
  416. cur = ggml_silu(ctx0, cur);
  417. cur = ggml_mul_mat(ctx0, layer.ffn1_w2, cur);
  418. cur = ggml_add(ctx0, ggml_repeat(ctx0, layer.ffn1_b2, cur), cur);
  419. // FFN1: * 0.5
  420. cur = ggml_mul(ctx0, ggml_repeat(ctx0, ffn_scale, cur), cur);
  421. // FFN1: + residual
  422. cur = ggml_add(ctx0, cur, residual);
  423. // TODO: Opportunity to optimize attn calculation (1) For num_threads > 1 (2) Flash attn. See https://github.com/ggerganov/ggml/blob/main/examples/gpt-2/main.cpp
  424. // self_attn: layernorm
  425. // unity_layer_norm
  426. cur = ggml_norm(ctx0, cur, hparams.eps);
  427. cur = ggml_add(ctx0,
  428. ggml_mul(ctx0,
  429. ggml_repeat(ctx0, layer.self_attn_layer_norm.weight, cur),
  430. cur),
  431. ggml_repeat(ctx0, layer.self_attn_layer_norm.bias, cur));
  432. // self_attn: qkv
  433. struct ggml_tensor * Qcur = ggml_mul_mat(ctx0,
  434. layer.self_attn_linear_q_w,
  435. cur);
  436. Qcur = ggml_add(ctx0,
  437. ggml_repeat(ctx0,
  438. layer.self_attn_linear_q_b,
  439. Qcur),
  440. Qcur);
  441. struct ggml_tensor * Kcur = ggml_mul_mat(ctx0,
  442. layer.self_attn_linear_k_w,
  443. cur);
  444. Kcur = ggml_add(ctx0,
  445. ggml_repeat(ctx0,
  446. layer.self_attn_linear_k_b,
  447. Kcur),
  448. Kcur);
  449. struct ggml_tensor * Vcur = ggml_mul_mat(ctx0,
  450. layer.self_attn_linear_v_w,
  451. cur);
  452. Vcur = ggml_add(ctx0,
  453. ggml_repeat(ctx0,
  454. layer.self_attn_linear_v_b,
  455. Vcur),
  456. Vcur);
  457. // self_attn: rel_pos SDPA (WIP)
  458. int32_t start_index = 4096 - 137;
  459. int32_t end_index = 4096 + 136;
  460. int num_indices = end_index - start_index + 1;
  461. struct ggml_tensor *rows = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, num_indices);
  462. rows->data = malloc(ggml_nbytes(rows));
  463. for (int i = 0; i < num_indices; i++) {
  464. ((int32_t *)rows->data)[i] = start_index + i;
  465. }
  466. // Load positional encoding weights
  467. struct ggml_tensor * pos_enc = ggml_get_rows(ctx0, model.audio_enc_pos_enc_w, rows);
  468. // conv
  469. // ffn2
  470. // norm
  471. inpL = cur;
  472. break; // debug
  473. }
  474. ggml_build_forward_expand(gf, inpL);
  475. ggml_free(ctx0);
  476. return gf;
  477. }
  478. extern "C" struct ggml_cgraph* unity_eval(
  479. ggml_allocr* allocr,
  480. const unity_model& model,
  481. ggml_tensor* input,
  482. const int n_threads) {
  483. // const auto & hparams = model.hparams;
  484. // reset the allocator to free all the memory allocated during the previous inference
  485. ggml_allocr_reset(allocr);
  486. struct ggml_cgraph * gf = unity_audio_encoder_graph(model, input);
  487. // allocate tensors
  488. ggml_allocr_alloc_graph(allocr, gf);
  489. // run the computation
  490. struct ggml_cplan plan = ggml_graph_plan(gf, n_threads);
  491. static std::vector<uint8_t> work_buffer;
  492. work_buffer.resize(plan.work_size);
  493. plan.work_data = work_buffer.data();
  494. ggml_graph_compute(gf, &plan);
  495. // in this case, the output tensor is the last one in the graph
  496. struct ggml_tensor * inpL = gf->nodes[gf->n_nodes - 1];
  497. printf("gf: %p, gf.nodes: %p, gf.n_nodes: %p", (void *)gf, (void *)gf->nodes, (void *)&(gf->n_nodes));
  498. for (int i = 0; i < 10; ++i) {
  499. printf("%8.4f ", ((float *)(inpL->data))[i]);
  500. }
  501. printf("\n");
  502. return gf;
  503. }
  504. int main(int argc, char ** argv) {
  505. // ggml_time_init();
  506. // const int64_t t_main_start_us = ggml_time_us();
  507. gpt_params params;
  508. if (gpt_params_parse(argc, argv, params) == false) {
  509. return 1;
  510. }
  511. if (params.seed < 0) {
  512. params.seed = time(NULL);
  513. }
  514. printf("%s: seed = %d\n", __func__, params.seed);
  515. std::mt19937 rng(params.seed);
  516. if (params.prompt.empty()) {
  517. params.prompt = gpt_random_prompt(rng);
  518. }
  519. gpt_vocab vocab;
  520. unity_model model;
  521. // load the model
  522. {
  523. if (!unity_model_load(params.model.c_str(), model, vocab)) {
  524. fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, params.model.c_str());
  525. return 1;
  526. }
  527. }
  528. /// For dev, load an example input before conformer blocks
  529. auto file = std::ifstream("/private/home/dnn/internal_sc/seamless_communication/ggml/examples/unity/dev/seqs_before_conformer_block.bin", std::ios::binary);
  530. if (!file) {
  531. file = std::ifstream("/home/guw/github/seamless_communication/ggml/examples/unity/models/unity-large/seqs_before_conformer_block.bin", std::ios::binary);
  532. if (!file) {
  533. std::cerr << "Failed to open binary file." << std::endl;
  534. exit(1);
  535. }
  536. }
  537. struct ggml_tensor * input = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, 1024, 137);
  538. input->data = malloc(ggml_nbytes(input));
  539. file.read(reinterpret_cast<char *>(input->data), ggml_nbytes(input));
  540. // keep this buffer alive while evaluating the model
  541. std::vector<uint8_t> compute_buffer;
  542. struct ggml_allocr * allocr = NULL;
  543. // allocate the compute buffer
  544. {
  545. allocr = ggml_allocr_new_measure(GGML_MEM_ALIGN);
  546. struct ggml_cgraph * gf = unity_audio_encoder_graph(model, input);
  547. // compute the required memory
  548. size_t mem_size = ggml_allocr_alloc_graph(allocr, gf) + GGML_MEM_ALIGN;
  549. // recreate the allocator with the required memory
  550. ggml_allocr_free(allocr);
  551. compute_buffer.resize(mem_size);
  552. allocr = ggml_allocr_new(compute_buffer.data(), mem_size, GGML_MEM_ALIGN);
  553. fprintf(stderr, "%s: compute buffer size: %.2f MB\n", __func__, mem_size/1024.0/1024.0);
  554. }
  555. if (!unity_eval(allocr, model, input, 1)) {
  556. printf("Failed to predict\n");
  557. return 1;
  558. }
  559. ggml_free(model.ctx);
  560. return 0;
  561. }