fairseq2.cpp 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756
  1. #include <algorithm>
  2. #include <fnmatch.h>
  3. #include <iostream>
  4. #include <math.h>
  5. #include <queue>
  6. #include <unordered_map>
  7. #include "kaldi-native-fbank/csrc/feature-fbank.h"
  8. #include "kaldi-native-fbank/csrc/feature-window.h"
  9. #include "fairseq2.h"
  10. #include "ggml.h"
  11. #include "ggml-alloc.h"
  12. ggml_tensor* ggml_detach(ggml_tensor* a) {
  13. a->op = GGML_OP_NONE;
  14. std::fill(a->src, a->src + GGML_MAX_SRC, nullptr);
  15. return a;
  16. }
  17. // generate_sequence uses ggml_context and ggml_allocr to reuse memory buffers across steps.
  18. // This can lead to dangling pointers, which don't segfault, but instead read garbage data.
  19. // Enabling this flag allows to explictly reset memory buffers, making it more explicit
  20. // when we read garbage data.
  21. // It also prints memory usage information, which is useful to
  22. #define DEBUG_MEM_USAGE DEBUG
  23. void printf_mem_usage(ggml_context* ctx, std::string name) {
  24. #if DEBUG_MEM_USAGE
  25. double mb = 1024.0 * 1024.0;
  26. printf(
  27. "ctx %s: memory used = %8.2f MB, memory reserved = %8.2f Mb\n",
  28. name.c_str(),
  29. ggml_used_mem(ctx) / mb,
  30. ggml_get_mem_size(ctx) / mb
  31. );
  32. #endif
  33. }
  34. #define SWAP(x, y) \
  35. auto tmp_ ## x = x; x = y; y = tmp_ ## x;
  36. #define GGML_ASSERT_SHAPE(x, ne0, ne1, ne2, ne3) \
  37. GGML_ASSERT((ne0 == -1 || x->ne[0] == ne0) && (ne1 == -1 || x->ne[1] == ne1) && (ne2 == -1 || x->ne[2] == ne2) && (ne3 == -1 || x->ne[3] == ne3));
  38. /// allocate the fairseq2 model and hyperparameters
  39. extern "C" fairseq2_model* fairseq2_model_alloc() {
  40. // pre-allocate some memory to write hyperparameters and tensors pointers
  41. auto* model = new fairseq2_model;
  42. model->tensors_ctx = nullptr;
  43. return model;
  44. }
  45. extern "C" void fairseq2_kv_cache_alloc(fairseq2_model& model, ggml_context* kv_cache_ctx, int beam_size, int max_seq_len) {
  46. // Note: we only allocate the masks, proper kv cache allocation is delayed.
  47. GGML_ASSERT(kv_cache_ctx);
  48. GGML_ASSERT(!ggml_get_no_alloc(kv_cache_ctx)); // We need to be able to alloc the kv_cache buffers
  49. model.kv_cache_ctx = kv_cache_ctx;
  50. auto attn_glob = "text_decoder.*_attn.k_proj.weight";
  51. FORCE_ALLOC(self_attn_mask, kv_cache_ctx, ggml_new_tensor_2d(kv_cache_ctx, GGML_TYPE_F32, max_seq_len, max_seq_len));
  52. self_attn_mask = ggml_diag_mask_inf_inplace(kv_cache_ctx, self_attn_mask, 0);
  53. ggml_format_name(self_attn_mask, "self_attn_mask[%d]", max_seq_len);
  54. for (auto named_tensor : model.tensors) {
  55. const std::string& name = named_tensor.first;
  56. if (::fnmatch(attn_glob, name.c_str(), 0) == FNM_NOMATCH)
  57. continue;
  58. // create a cache entry without the ".k_proj.weight" suffix
  59. const std::string& shortname = name.substr(0, name.size() - 14);
  60. KeyValueTensor& kv = model.kv_cache[shortname];
  61. kv.step_nr = 0;
  62. kv.full_k = nullptr;
  63. kv.full_v = nullptr;
  64. kv.self_attn_mask = self_attn_mask;
  65. }
  66. }
  67. extern "C" void fairseq2_kv_cache_reset(const fairseq2_model& model) {
  68. // TODO: use a dedicated allocator, so that kv_cache.clear actually frees the memory
  69. model.kv_cache.clear();
  70. }
  71. bool has_kv_cache(const fairseq2_model& model) {
  72. return model.kv_cache.size() > 0;
  73. }
  74. inline ggml_tensor* ggml_squeeze(ggml_context* ctx, ggml_tensor* x, int dim) {
  75. int n_dims = x->n_dims;
  76. GGML_ASSERT(dim >= 0);
  77. GGML_ASSERT(dim < n_dims);
  78. GGML_ASSERT(x->ne[dim] == 1);
  79. return ggml_flatten_1d(ctx, x, dim);
  80. }
  81. inline ggml_tensor* ggml_unsqueeze(ggml_context* ctx, ggml_tensor* x, int dim) {
  82. return ggml_unflatten_1d(ctx, x, dim, 1);
  83. }
  84. // copy k and v to kv cache
  85. // kv.full_k[step_nr] = k;
  86. // kv.full_v[step_nr] = v;
  87. void append_to_prev_kv(const fairseq2_model& model, const std::string& prefix, ggml_tensor** k, ggml_tensor** v, ggml_tensor** self_attn_mask) {
  88. KeyValueTensor& kv = model.kv_cache[prefix];
  89. int step_nr = kv.step_nr;
  90. ggml_context* ctx = model.kv_cache_ctx ? model.kv_cache_ctx : model.ctx;
  91. int n_steps = (*k)->ne[1];
  92. int k_proj, batch_size;
  93. if (kv.full_k != nullptr) {
  94. // (N, S_kv, K_proj)
  95. k_proj = kv.full_k->ne[0];
  96. batch_size = kv.full_k->ne[2];
  97. ggml_detach(kv.full_k);
  98. ggml_detach(kv.full_v);
  99. kv.full_k = ggml_squeeze(ctx, ggml_concat(ctx, ggml_unsqueeze(ctx, kv.full_k, 1), ggml_unsqueeze(ctx, *k, 1)), 1);
  100. kv.full_v = ggml_squeeze(ctx, ggml_concat(ctx, ggml_unsqueeze(ctx, kv.full_v, 1), ggml_unsqueeze(ctx, *v, 1)), 1);
  101. } else {
  102. GGML_ASSERT(step_nr == 0);
  103. k_proj = (*k)->ne[0];
  104. batch_size = (*v)->ne[2];
  105. kv.full_k = ggml_dup(ctx, *k);
  106. kv.full_v = ggml_dup(ctx, *v);
  107. }
  108. *k = kv.full_k;
  109. *v = kv.full_v;
  110. ggml_format_name(kv.full_k, "%s.k (step=%d)", prefix.c_str(), step_nr);
  111. ggml_format_name(kv.full_v, "%s.v (step=%d)", prefix.c_str(), step_nr);
  112. step_nr += n_steps;
  113. GGML_ASSERT_SHAPE(kv.full_k, k_proj, step_nr, batch_size, 1);
  114. // qk is (B * H, Sq, Sk) == (B*H, 1, Sk) in incremental mode
  115. // we return the Sq slice of the (Sq, Sk) attention mask
  116. *self_attn_mask = ggml_slice(
  117. model.ctx,
  118. ggml_slice(model.ctx, kv.self_attn_mask, 0, 0, step_nr),
  119. 1,
  120. step_nr - 1,
  121. step_nr
  122. );
  123. kv.step_nr = step_nr;
  124. }
  125. // variant of ggml_get_rows that allows for a with more than 2 dims.
  126. ggml_tensor* ggml_get_rows2(ggml_context* ctx, ggml_tensor* a, ggml_tensor* b) {
  127. int flattened = 0;
  128. GGML_ASSERT(a->n_dims <= 3);
  129. if (a->n_dims == 3) {
  130. flattened = a->ne[0];
  131. a = ggml_flatten_1d(ctx, a, 0);
  132. }
  133. a = ggml_get_rows(ctx, a, b);
  134. if (flattened) {
  135. a = ggml_unflatten_1d(ctx, a, 0, flattened);
  136. }
  137. return a;
  138. }
  139. void _reorder_kv_cache(ggml_context* ctx, ggml_cgraph* gf, KeyValueTensor& kv, ggml_tensor* new_order) {
  140. // GGML_ASSERT(ctx == kv.full_k->con);
  141. if (kv.full_k != nullptr) {
  142. ggml_detach(kv.full_k);
  143. const char* name = kv.full_k->name;
  144. kv.full_k = ggml_get_rows2(ctx, kv.full_k, new_order);
  145. ggml_build_forward_expand(gf, kv.full_k);
  146. ggml_format_name(kv.full_k, "%s (sorted)", name);
  147. }
  148. if (kv.full_v != nullptr) {
  149. ggml_detach(kv.full_v);
  150. const char* name = kv.full_v->name;
  151. kv.full_v = ggml_get_rows2(ctx, kv.full_v, new_order);
  152. ggml_build_forward_expand(gf, kv.full_v);
  153. ggml_format_name(kv.full_v, "%s (sorted)", name);
  154. }
  155. }
  156. void reorder_kv_cache(const fairseq2_model& model, ggml_context* ctx, ggml_cgraph* gf, ggml_tensor* new_order) {
  157. auto self_attn_glob = "*.self_attn";
  158. for (auto& named_kv : model.kv_cache) {
  159. if (::fnmatch(self_attn_glob, named_kv.first.c_str(), 0) == FNM_NOMATCH)
  160. continue;
  161. _reorder_kv_cache(ctx, gf, named_kv.second, new_order);
  162. }
  163. }
  164. inline double model_layer_config_d(const fairseq2_model& model, std::string name) {
  165. const std::int64_t* data = &model.layer_config.at(name);
  166. double val = *(const double*)data;
  167. return val;
  168. }
  169. extern "C" double fairseq2_model_layer_config_double(const fairseq2_model& model, const char* name) {
  170. return model_layer_config_d(model, std::string(name));
  171. }
  172. extern "C" std::int64_t fairseq2_model_layer_config_int(const fairseq2_model& model, const char* name) {
  173. return model.layer_config.at(std::string(name));
  174. }
  175. extern "C" void fairseq2_model_free(fairseq2_model* model) {
  176. if (model->tensors_ctx) ggml_free(model->tensors_ctx);
  177. delete model;
  178. }
  179. extern "C" void fairseq2_model_set_inference_ctx(fairseq2_model* model, ggml_context* ctx) {
  180. model->ctx = ctx;
  181. }
  182. extern "C" std::string* std_string_alloc(char* c_str) {
  183. return new std::string(c_str);
  184. }
  185. extern "C" void std_string_free(std::string* str) {
  186. delete str;
  187. }
  188. bool has_layer(fairseq2_model& model, const std::string& name) {
  189. return model.tensors.find(name) != model.tensors.end();
  190. }
  191. ggml_tensor* mul_mat(ggml_context* ctx, ggml_tensor* a, ggml_tensor* b) {
  192. if (b->ne[1] == 1 && b->ne[2] > 1 && a->n_dims == 2) {
  193. // `b` has shape (B, 1, D).
  194. // if `a` is (D_out, D), then we do one matmul for the full batch.
  195. b = ggml_flatten_1d(ctx, b, 1);
  196. return ggml_unflatten_1d(ctx, ggml_mul_mat(ctx, a, b), 1, 1);
  197. }
  198. // there is also the k * q matmul -> (D, 1, B) * (D, 1, B) -> (1, 1, B)
  199. // not sure what's the best way to compute this with BLAS
  200. return ggml_mul_mat(ctx, a, b); // (d_out)
  201. }
  202. extern "C" ggml_tensor* Linear_forward(
  203. fairseq2_model& model,
  204. const std::string &prefix,
  205. ggml_tensor* input // (d_in)
  206. ) {
  207. // Note: for now we assumed un-batched input
  208. ggml_tensor* weight = model.tensors[prefix + ".weight"]; // (d_in, d_out)
  209. GGML_ASSERT(weight != nullptr);
  210. ggml_tensor* out = mul_mat(model.ctx, weight, input); // (d_out)
  211. ggml_tensor* bias = model.tensors[prefix + ".bias"]; // (d_out)
  212. if (bias == nullptr) return out;
  213. return ggml_add(model.ctx, out, bias);
  214. }
  215. extern "C" ggml_tensor* LayerNorm_forward(
  216. fairseq2_model& model,
  217. const std::string &prefix,
  218. ggml_tensor* input
  219. ) {
  220. ggml_tensor* weight = model.tensors[prefix + ".weight"];
  221. GGML_ASSERT(weight != nullptr);
  222. ggml_tensor* bias = model.tensors[prefix + ".bias"];
  223. GGML_ASSERT(bias != nullptr);
  224. auto ctx = model.ctx;
  225. double eps = model_layer_config_d(model, prefix + ".eps");
  226. input = ggml_norm(ctx, input, /*eps*/eps);
  227. return ggml_add_inplace(
  228. ctx,
  229. ggml_mul_inplace(ctx, ggml_repeat(ctx, weight, input), input),
  230. ggml_repeat(ctx, bias, input)
  231. );
  232. }
  233. extern "C" ggml_tensor* StandardFeedForwardNetwork_forward(
  234. fairseq2_model& model,
  235. const std::string& prefix,
  236. ggml_tensor* seqs
  237. ) {
  238. seqs = Linear_forward(model, prefix + ".inner_proj", seqs);
  239. // inner_activation = ReLu // TODO: allow other activation
  240. seqs = ggml_relu_inplace(model.ctx, seqs);
  241. if (has_layer(model, prefix + ".inner_layer_norm")) {
  242. seqs = LayerNorm_forward(model, prefix + ".inner_layer_norm", seqs);
  243. }
  244. seqs = Linear_forward(model, prefix + ".output_proj", seqs);
  245. return seqs;
  246. }
  247. extern "C" ggml_tensor* SiluFeedForwardNetwork_forward(
  248. fairseq2_model& model,
  249. const std::string& prefix,
  250. ggml_tensor* seqs
  251. ) {
  252. seqs = Linear_forward(model, prefix + ".inner_proj", seqs);
  253. seqs = ggml_silu(model.ctx, seqs);
  254. if (has_layer(model, prefix + ".inner_layer_norm")) {
  255. seqs = LayerNorm_forward(model, prefix + ".inner_layer_norm", seqs);
  256. }
  257. seqs = Linear_forward(model, prefix + ".output_proj", seqs);
  258. return seqs;
  259. }
  260. ggml_tensor* ggml_flatten_1d(ggml_context* ctx, ggml_tensor* x, int dim) {
  261. int n_dims = x->n_dims;
  262. GGML_ASSERT(dim >= 0);
  263. GGML_ASSERT(dim < n_dims);
  264. GGML_ASSERT(ggml_is_contiguous(x));
  265. // Nothing to do
  266. if (dim == n_dims - 1) return x;
  267. if (n_dims == 2) {
  268. return ggml_reshape_1d(ctx, x, x->ne[0] * x->ne[1]);
  269. } else if (n_dims == 3) {
  270. if (dim == 0) {
  271. return ggml_reshape_2d(ctx, x, x->ne[0] * x->ne[1], x->ne[2]);
  272. } else { // dim == 1
  273. return ggml_reshape_2d(ctx, x, x->ne[0], x->ne[1] * x->ne[2]);
  274. }
  275. } else { // n_dims == 4
  276. if (dim == 0) {
  277. return ggml_reshape_3d(ctx, x, x->ne[0] * x->ne[1], x->ne[2], x->ne[3]);
  278. } else if (dim == 1) {
  279. return ggml_reshape_3d(ctx, x, x->ne[0], x->ne[1] * x->ne[2], x->ne[3]);
  280. } else { // dim == 2
  281. return ggml_reshape_3d(ctx, x, x->ne[0], x->ne[1], x->ne[2] * x->ne[3]);
  282. }
  283. }
  284. }
  285. ggml_tensor* ggml_unflatten_1d(ggml_context* ctx, ggml_tensor* x, int dim, int num_el) {
  286. int n_dims = x->n_dims;
  287. GGML_ASSERT(dim >= 0);
  288. GGML_ASSERT(dim < n_dims);
  289. GGML_ASSERT(n_dims < 4);
  290. GGML_ASSERT(x->ne[dim] % num_el == 0);
  291. GGML_ASSERT(x->nb[dim + 1] == x->nb[dim] * x->ne[dim]); // `x` isn't contiguous along `dim`
  292. if (n_dims == 1) {
  293. return ggml_view_2d(ctx, x, num_el, x->ne[0] / num_el, x->nb[0] * num_el, 0);
  294. } else if (n_dims == 2) {
  295. if (dim == 0) {
  296. return ggml_view_3d(ctx, x, num_el, x->ne[0] / num_el, x->ne[1], x->nb[0] * num_el, x->nb[1], 0);
  297. } else { // dim == 1
  298. return ggml_view_3d(ctx, x, x->ne[0], num_el, x->ne[1] / num_el, x->nb[1], num_el * x->nb[1], 0);
  299. }
  300. } else { // (n_dims == 3)
  301. if (dim == 0) {
  302. return ggml_view_4d(ctx, x, num_el, x->ne[0] / num_el, x->ne[1], x->ne[2], x->nb[0] * num_el, x->nb[1], x->nb[2], 0);
  303. } else if (dim == 1) {
  304. return ggml_view_4d(ctx, x, x->ne[0], num_el, x->ne[1] / num_el, x->ne[2], x->nb[1], num_el * x->nb[1], x->nb[2], 0);
  305. } else { // dim == 2
  306. return ggml_view_4d(ctx, x, x->ne[0], x->ne[1], num_el, x->ne[2] / num_el, x->nb[1], x->nb[2], num_el * x->nb[2], 0);
  307. }
  308. }
  309. }
  310. ggml_tensor* _reshape_num_head(ggml_context* ctx, ggml_tensor* x, int head_dim) {
  311. // (B, S, dim) -> (B, S, H, H_dim)
  312. x = ggml_unflatten_1d(ctx, x, 0, head_dim);
  313. x = ggml_permute(ctx, x, 0, 2, 1, 3); // (B, H, S, H_dim)
  314. x = ggml_cont(ctx, x);
  315. x = ggml_flatten_1d(ctx, x, 2); // (B * H, S, H_dim)
  316. return x;
  317. }
  318. /// (B, Sk, dim) -> // (B?, H, H_dim, Sk)
  319. ggml_tensor* _reshape_num_head_values(ggml_context* ctx, ggml_tensor* v, int head_dim ) {
  320. // (B, Sk, dim) -> (B, Sk, H, H_dim)
  321. v = ggml_unflatten_1d(ctx, v, 0, head_dim);
  322. v = ggml_permute(ctx, v, 1, 2, 0, 3); // (B?, H, H_dim, Sk)
  323. v = ggml_cont(ctx, v);
  324. v = ggml_flatten_1d(ctx, v, 2); // (B * H, S, H_dim)
  325. return v;
  326. }
  327. // flash_attn doesn't work for cross attention because it assumes Q <= K
  328. // and it seems to yield slightly different scores than expected, and thus a different beam search
  329. # define UNITY_FLASH_ATTN 0
  330. extern "C" ggml_tensor* MultiheadAttention_forward(
  331. fairseq2_model& model,
  332. const std::string &prefix,
  333. ggml_tensor* queries, // (slen, d_in)
  334. ggml_tensor* keys, // (klen, d_in)
  335. ggml_tensor* values, // (klen, d_out)
  336. ggml_tensor* attn_mask // (klen, slen)
  337. ) {
  338. int model_dim = queries->ne[0];
  339. int num_heads = model.layer_config.at(prefix + ".num_heads");
  340. int head_dim = model_dim / num_heads;
  341. GGML_ASSERT(model_dim % num_heads == 0);
  342. ggml_context* ctx = model.ctx;
  343. ggml_tensor* q = Linear_forward(model, prefix + ".q_proj", queries); // (B, S, H * H_dim)
  344. q = _reshape_num_head(ctx, q, head_dim); // (B * H, S, H_dim)
  345. ggml_set_name(q, "q");
  346. ggml_tensor *k, *v;
  347. if (!has_kv_cache(model)) {
  348. k = Linear_forward(model, prefix + ".k_proj", keys);
  349. ggml_set_name(k, "k");
  350. v = Linear_forward(model, prefix + ".v_proj", values);
  351. ggml_set_name(v, "v");
  352. } else {
  353. bool encoder_decoder_attn = keys == values && keys != queries;
  354. if (encoder_decoder_attn) {
  355. // The K and V tensors of an encoder-decoder attention (i.e. the
  356. // projected encoder outputs) remain static during evaluation.
  357. KeyValueTensor& kv_cache = model.kv_cache[prefix];
  358. if (kv_cache.step_nr == 0) {
  359. // If possible we use the ctx dedicated to kv_cache here,
  360. // because the enc dec attention is typically long lived.
  361. if (model.kv_cache_ctx) model.ctx = model.kv_cache_ctx;
  362. k = Linear_forward(model, prefix + ".k_proj", keys);
  363. ggml_set_name(k, "k");
  364. v = Linear_forward(model, prefix + ".v_proj", values);
  365. ggml_set_name(v, "v");
  366. // Note we are only storing a pointer to the buffer, not the full graph
  367. kv_cache.full_k = ggml_detach(ggml_dup_inplace(model.ctx, k));
  368. ggml_format_name(kv_cache.full_k, "%s.k_cache", prefix.c_str());
  369. kv_cache.full_v = ggml_detach(ggml_dup_inplace(model.ctx, v));
  370. ggml_format_name(kv_cache.full_v, "%s.v_cache", prefix.c_str());
  371. kv_cache.step_nr = keys->ne[1];
  372. model.ctx = ctx;
  373. } else {
  374. k = kv_cache.full_k;
  375. v = kv_cache.full_v;
  376. GGML_ASSERT(keys->ne[1] == k->ne[1]); // cache content doesn't match the input sequence
  377. GGML_ASSERT(values->ne[1] == v->ne[1]); // cache content doesn't match the input sequence
  378. }
  379. } else { // self attention
  380. // (1, K) -> (N, 1, K_proj)
  381. k = Linear_forward(model, prefix + ".k_proj", keys);
  382. ggml_set_name(k, "k");
  383. // (1, V) -> (N, 1, V_proj)
  384. v = Linear_forward(model, prefix + ".v_proj", values);
  385. ggml_set_name(v, "v");
  386. append_to_prev_kv(model, prefix, &k, &v, &attn_mask);
  387. }
  388. }
  389. k = _reshape_num_head(ctx, k, head_dim); // (B * H, Sk, H_dim)
  390. v = _reshape_num_head_values(ctx, v, head_dim); // (B * H, H_dim, Sk)
  391. v = ggml_cont(ctx, v);
  392. #if UNITY_FLASH_ATTN
  393. // For flash_attn, we assume either no masks, or triangular masks.
  394. ggml_tensor* attn = ggml_flash_attn(ctx, q, k, v, /*masked*/attn_mask != nullptr); // (B * H, S, H_dim)
  395. ggml_set_name(attn, "attn");
  396. attn = ggml_unflatten_1d(ctx, attn, 2, num_heads); // (B, H, H_dim, S)
  397. attn = ggml_permute(ctx, attn, 0, 2, 1, 3); // (B, S, H, H_dim)
  398. #else
  399. // (B * H, Sk, H_dim) x (B * H, S, H_dim) -> (B * H, S, Sk)
  400. ggml_tensor* qk = mul_mat(ctx, k, q);
  401. ggml_set_name(qk, "qk");
  402. FORCE_ALLOC(qk_scale, ctx, ggml_new_tensor_1d(ctx, qk->type, 1));
  403. ggml_set_f32(qk_scale, 1.0f/sqrtf(float(head_dim)));
  404. qk = ggml_scale(ctx, qk, qk_scale);
  405. ggml_set_name(qk, "qk_scaled");
  406. if (attn_mask) qk = ggml_add_inplace(ctx, qk, attn_mask);
  407. // TODO: upgrade qk to float32 if needed
  408. ggml_tensor* attn_weights = ggml_soft_max(ctx, qk); // (B * H, S, Sk)
  409. ggml_set_name(attn_weights, "attn_weights");
  410. // (B * H, S, Sk) x (B * H, H_dim, Sk) -> (B * H, H_dim, S)
  411. ggml_tensor* attn = mul_mat(ctx, attn_weights, v);
  412. ggml_set_name(attn, "attn");
  413. attn = ggml_unflatten_1d(ctx, attn, 2, num_heads); // (B, H, H_dim, S)
  414. attn = ggml_permute(ctx, attn, 2, 0, 1, 3); // (B, S, H, H_dim)
  415. #endif // UNITY_FLASH_ATTN
  416. attn = ggml_cont(ctx, attn);
  417. attn = ggml_flatten_1d(ctx, attn, 0); // (B, S, H * H_dim)
  418. // out -> (B, S, d_out)
  419. ggml_tensor* out = Linear_forward(model, prefix + ".output_proj", attn);
  420. ggml_set_name(out, "out");
  421. return out;
  422. }
  423. extern "C" ggml_tensor* StandardTransformerEncoderLayer_forward(
  424. fairseq2_model& model,
  425. const std::string& prefix,
  426. ggml_tensor* seqs,
  427. ggml_tensor* padding_mask
  428. ) {
  429. ggml_context* ctx = model.ctx;
  430. auto norm_order = model.layer_config.at(prefix + ".norm_order");
  431. // _forward_self_attn(seqs, padding_mask)
  432. auto residual = seqs;
  433. if (norm_order != TRANSFORMER_NORM_ORDER_POST)
  434. seqs = LayerNorm_forward(model, prefix + ".self_attn_layer_norm", seqs);
  435. // TODO: add padding_mask to MultiheadAttention_forward
  436. GGML_ASSERT(padding_mask == nullptr);
  437. seqs = MultiheadAttention_forward(
  438. model,
  439. prefix + ".self_attn",
  440. seqs,
  441. seqs,
  442. seqs,
  443. /*attn_mask=*/nullptr
  444. );
  445. if (has_layer(model, prefix + ".self_attn_norm"))
  446. seqs = LayerNorm_forward(model, prefix + ".self_attn_norm", seqs);
  447. seqs = ggml_add_inplace(ctx, seqs, residual);
  448. if (norm_order == TRANSFORMER_NORM_ORDER_POST)
  449. seqs = LayerNorm_forward(model, prefix + ".self_attn_layer_norm", seqs);
  450. // _forward_ffn(seqs)
  451. residual = seqs;
  452. if (norm_order != TRANSFORMER_NORM_ORDER_POST)
  453. seqs = LayerNorm_forward(model, prefix + ".ffn_layer_norm", seqs);
  454. seqs = StandardFeedForwardNetwork_forward(model, prefix + ".ffn", seqs);
  455. // TODO: if self.residual_scale is not None:
  456. // residual = self.residual_scale * residual
  457. seqs = ggml_add_inplace(ctx, seqs, residual);
  458. if (norm_order == TRANSFORMER_NORM_ORDER_POST)
  459. seqs = LayerNorm_forward(model, prefix + ".ffn_layer_norm", seqs);
  460. return seqs;
  461. }
  462. extern "C" ggml_tensor* WaveformToFbank_forward(
  463. fairseq2_model& model,
  464. const std::string &prefix,
  465. ggml_tensor* waveform
  466. ) {
  467. // Hardcoding: num_bins 80, sample rate 16k, always standardize
  468. ggml_context* ctx = model.ctx;
  469. knf::MelBanksOptions mel_opts{};
  470. mel_opts.num_bins = 80;
  471. knf::FrameExtractionOptions frame_opts{};
  472. frame_opts.samp_freq = 16000;
  473. knf::FbankOptions opts{};
  474. opts.frame_opts = frame_opts;
  475. opts.mel_opts = mel_opts;
  476. std::vector<float_t> signal_frame{};
  477. std::int32_t num_frames = knf::NumFrames(/*num_samples=*/waveform->ne[0], frame_opts);
  478. FORCE_ALLOC(output, ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 80, num_frames));
  479. knf::FbankComputer native_(opts);
  480. knf::FeatureWindowFunction window_fn_(native_.GetFrameOptions());
  481. for (std::int32_t frame_nr = 0; frame_nr < num_frames; ++frame_nr) {
  482. signal_frame.resize(0);
  483. // Extract the frame from the waveform tensor.
  484. knf::ExtractWindow(
  485. /*sample_offset=*/0,
  486. (float *)(waveform->data),
  487. waveform->ne[0],
  488. frame_nr,
  489. frame_opts,
  490. window_fn_,
  491. &signal_frame);
  492. native_.Compute(
  493. /*signal_raw_log_energy=*/0, /*vtln_warp=*/1.0, &signal_frame, ((float *)(output->data) + frame_nr * 80));
  494. }
  495. output = ggml_dup(ctx, ggml_transpose(ctx, output));
  496. output = ggml_norm(ctx, output, 1e-5);
  497. output = ggml_dup(ctx, ggml_transpose(ctx, output));
  498. if (output->ne[1] % 2 == 1) {
  499. ggml_tensor* remove_last = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, output->ne[1]-1);
  500. for (int i = 0; i < output->ne[1]-1; ++i) {
  501. ((int32_t *) remove_last->data)[i] = i;
  502. }
  503. output = ggml_get_rows(ctx, output, remove_last);
  504. }
  505. output = ggml_reshape_2d(ctx, output, output->ne[0] * 2, output->ne[1] / 2);
  506. return output;
  507. }
  508. // TODO: Check if it's possible to merge with standard MHA
  509. extern "C" ggml_tensor* RelativePositionMHA_forward(
  510. fairseq2_model& model,
  511. const std::string& prefix,
  512. ggml_tensor* seqs
  513. ) {
  514. ggml_context* ctx = model.ctx;
  515. ggml_tensor* residual = seqs;
  516. seqs = LayerNorm_forward(model, prefix + "_layer_norm", seqs);
  517. // self_attn: qkv
  518. ggml_tensor* Qcur = Linear_forward(model, prefix + ".q_proj", seqs);
  519. ggml_tensor* Kcur = Linear_forward(model, prefix + ".k_proj", seqs);
  520. ggml_tensor* Vcur = Linear_forward(model, prefix + ".v_proj", seqs);
  521. // self_attn: rel_pos SDPA
  522. int32_t S = seqs->ne[1];
  523. int32_t H = 16; // TODO: Make this configurable
  524. int32_t n_ctx = 4096;
  525. int32_t K_h = seqs->ne[0] / H;
  526. int32_t start_index = n_ctx - S;
  527. int32_t end_index = n_ctx + S - 1;
  528. int num_indices = end_index - start_index;
  529. FORCE_ALLOC(rows, ctx, ggml_new_tensor_1d(ctx, GGML_TYPE_I32, num_indices));
  530. for (int i = 0; i < num_indices; i++) {
  531. ((int32_t *)rows->data)[i] = start_index + i;
  532. }
  533. // self_attn: load pos_enc weights & compute_r
  534. // In fairseq2 pos_enc weights are calculated on the fly, since some more custom operators might be needed to enable this,
  535. // we store the results (fixed) in checkpoint as model.audio_enc_pos_enc_w and load directly.
  536. ggml_tensor* r = ggml_get_rows(ctx, model.tensors["speech_encoder.pos_enc"], rows);
  537. r = mul_mat(ctx, model.tensors[prefix + ".sdpa.r_proj.weight"], r);
  538. r = ggml_dup(ctx, ggml_permute(ctx,
  539. ggml_cpy(ctx,
  540. r,
  541. ggml_new_tensor_3d(ctx, GGML_TYPE_F32, K_h, H, S*2-1)),
  542. 0, 2, 1, 3));
  543. ggml_tensor* u_bias = ggml_reshape_3d(ctx, model.tensors[prefix + ".sdpa.u_bias"], K_h, 1, H);
  544. ggml_tensor* v_bias = ggml_reshape_3d(ctx, model.tensors[prefix + ".sdpa.v_bias"], K_h, 1, H);
  545. // self_attn: Permute QKV
  546. ggml_tensor* Q = ggml_cont(ctx, ggml_permute(ctx,
  547. ggml_cpy(ctx,
  548. Qcur,
  549. ggml_new_tensor_3d(ctx, GGML_TYPE_F32, K_h, H, S)),
  550. 0, 2, 1, 3)); // (H * K_h, S) -> (K_h, H, S) -> (K_h, S, H)
  551. ggml_tensor* K = ggml_cont(ctx, ggml_permute(ctx,
  552. ggml_cpy(ctx,
  553. Kcur,
  554. ggml_new_tensor_3d(ctx, GGML_TYPE_F32, K_h, H, S)),
  555. 0, 2, 1, 3)); // (H * K_h, S) -> (K_h, H, S) -> (K_h, S, H)
  556. ggml_tensor* V = ggml_cont(ctx, ggml_permute(ctx,
  557. ggml_cpy(ctx,
  558. Vcur,
  559. ggml_new_tensor_3d(ctx, GGML_TYPE_F32, K_h, H, S)),
  560. 1, 2, 0, 3)); // (H * K_h, S) -> (K_h, H, S) -> (H, S, K_h)
  561. ggml_tensor* q_with_u_bias = ggml_add_inplace(ctx, ggml_dup(ctx, Q), u_bias); // (K_h, S, H)
  562. ggml_tensor* q_with_v_bias = ggml_add_inplace(ctx, Q, v_bias); // (K_h, S, H)
  563. ggml_tensor* ac = mul_mat(ctx, K, q_with_u_bias);
  564. ggml_tensor* bd = mul_mat(ctx, r, q_with_v_bias);
  565. // self_attn: shift_bd. Logic follows https://github.com/facebookresearch/fairseq2/blob/main/src/fairseq2/nn/transformer/relative_attention.py#L161
  566. bd = ggml_dup(ctx, ggml_permute(ctx, bd, 2, 1, 0, 3)); // H, S, 2S-1
  567. FORCE_ALLOC(pad, ctx, ggml_new_tensor_3d(ctx, GGML_TYPE_F32, H, S, 1));
  568. pad = ggml_set_f32(pad, 0.0);
  569. bd = ggml_concat(ctx, pad, bd); // bd[i][j][0] == 0, (H, S, 2S)
  570. bd = ggml_dup(ctx, ggml_permute(ctx, bd, 2, 1, 0, 3)); // (2S, S, H)
  571. bd = ggml_reshape_3d(ctx, bd, S, 2 * S, H); // (S, 2S, H)
  572. // discard the first set of positive positions
  573. bd = ggml_dup(ctx, ggml_slice(ctx, bd, 1, 1, 2 * S));
  574. // shifts each row by an extra step
  575. bd = ggml_reshape_3d(ctx, bd, 2 * S - 1, S, H);
  576. // Discard positions used for shift.
  577. bd = ggml_slice(ctx, bd, 0, 0, S);
  578. // self_attn: compute attn / weights
  579. ggml_tensor* attn_weights = ggml_add_inplace(ctx, ac, bd);
  580. FORCE_ALLOC(attn_scale, ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, 1));
  581. ggml_set_f32(attn_scale, 1.0 / pow(K_h, 0.5));
  582. attn_weights = ggml_mul_inplace(ctx, attn_weights, ggml_repeat(ctx, attn_scale, attn_weights));
  583. attn_weights = ggml_soft_max(ctx, attn_weights);
  584. ggml_tensor* attn = mul_mat(ctx, V, attn_weights); // K_h, S, H
  585. attn = ggml_dup(ctx, ggml_permute(ctx, attn, 0, 2, 1, 3));
  586. ggml_tensor* attn_2d = ggml_reshape_2d(ctx, attn, K_h * H, S);
  587. ggml_tensor* attn_out = mul_mat(ctx, model.tensors[prefix + ".output_proj.weight"], attn_2d);
  588. attn_out = ggml_add_inplace(
  589. ctx,
  590. attn_out,
  591. ggml_repeat(ctx, model.tensors[prefix + ".output_proj.bias"], attn_out)
  592. );
  593. attn_out = ggml_add_inplace(ctx, attn_out, residual);
  594. return attn_out;
  595. }
  596. extern "C" ggml_tensor* ConvModule_forward(
  597. fairseq2_model& model,
  598. const std::string& prefix,
  599. ggml_tensor* seqs
  600. ) {
  601. ggml_context* ctx = model.ctx;
  602. ggml_tensor* residual = seqs;
  603. seqs = LayerNorm_forward(model, prefix + "_layer_norm", seqs);
  604. // conv: Use matmul for pointwise conv 1 - kernel_size=1, no padding case
  605. seqs = mul_mat(ctx, model.tensors[prefix + ".pointwise_conv1.weight"], seqs);
  606. // conv: GLU
  607. seqs = ggml_glu(ctx, seqs);
  608. seqs = ggml_dup(ctx, ggml_permute(ctx, seqs, 1, 0, 2, 3));
  609. // S x C -> (S+K-1) x C -> K x S x C -> S x C
  610. seqs = ggml_conv_1d(ctx, model.tensors[prefix + ".depthwise_conv.weight"], seqs, 1, 15, 1);
  611. // conv: Custom implementation of batch norm
  612. seqs = ggml_batch_norm(ctx, seqs, model.tensors[prefix + ".batch_norm.weight"], model.tensors[prefix + ".batch_norm.bias"], model.tensors[prefix + ".batch_norm.running_mean"], model.tensors[prefix + ".batch_norm.running_var"], 1e-5);
  613. // conv: SiLU actvation
  614. seqs = ggml_silu_inplace(ctx, seqs);
  615. seqs = ggml_dup(ctx, ggml_permute(ctx, seqs, 1, 0, 2, 3));
  616. // conv: Use matmul for pointwise conv 2 - kernel_size=1, no padding case
  617. seqs = mul_mat(ctx, model.tensors[prefix + ".pointwise_conv2.weight"], seqs);
  618. // conv: + residual
  619. seqs = ggml_add_inplace(ctx, seqs, residual);
  620. return seqs;
  621. }
  622. extern "C" ggml_tensor* StandardConformerEncoderLayer_forward(
  623. fairseq2_model& model,
  624. const std::string& prefix,
  625. ggml_tensor* seqs,
  626. ggml_tensor* padding_mask
  627. ) {
  628. ggml_context* ctx = model.ctx;
  629. FORCE_ALLOC(ffn_scale, ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, 1));
  630. ggml_set_f32(ffn_scale, 0.5f);
  631. ggml_tensor* residual = seqs;
  632. seqs = LayerNorm_forward(model, prefix + ".ffn1_layer_norm", seqs);
  633. seqs = SiluFeedForwardNetwork_forward(model, prefix + ".ffn1", seqs);
  634. seqs = ggml_mul_inplace(ctx, seqs, ggml_repeat(ctx, ffn_scale, seqs));
  635. seqs = ggml_add_inplace(ctx, seqs, residual);
  636. seqs = RelativePositionMHA_forward(model, prefix + ".self_attn", seqs);
  637. seqs = ConvModule_forward(model, prefix + ".conv", seqs);
  638. residual = seqs;
  639. seqs = LayerNorm_forward(model, prefix + ".ffn2_layer_norm", seqs);
  640. seqs = SiluFeedForwardNetwork_forward(model, prefix + ".ffn2", seqs);
  641. seqs = ggml_mul_inplace(ctx, seqs, ggml_repeat(ctx, ffn_scale, seqs));
  642. seqs = ggml_add_inplace(ctx, seqs, residual);
  643. seqs = LayerNorm_forward(model, prefix + ".layer_norm", seqs);
  644. return seqs;
  645. }
  646. extern "C" ggml_tensor* StandardConformerEncoder_forward(
  647. fairseq2_model& model,
  648. const std::string& prefix,
  649. ggml_tensor* seqs,
  650. ggml_tensor* padding_mask
  651. ) {
  652. ggml_context* ctx = model.ctx;
  653. seqs = WaveformToFbank_forward(model, prefix, seqs);
  654. seqs = LayerNorm_forward(model, prefix + "_frontend.post_extract_layer_norm", seqs);
  655. seqs = Linear_forward(model, prefix + "_frontend.model_dim_proj", seqs);
  656. int layer_idx = 0;
  657. std::string layer_name = prefix + ".inner.layers." + std::to_string(layer_idx);
  658. while (has_layer(model, layer_name)) {
  659. seqs = StandardConformerEncoderLayer_forward(
  660. model, layer_name, seqs, padding_mask
  661. );
  662. ggml_set_name(seqs, ("x_enc_" + std::to_string(layer_idx)).c_str());
  663. layer_idx += 1;
  664. layer_name = prefix + ".inner.layers." + std::to_string(layer_idx);
  665. }
  666. seqs = LayerNorm_forward(model, prefix + ".inner_layer_norm", seqs);
  667. ggml_tensor* residual = seqs;
  668. seqs = Linear_forward(model, prefix + ".proj1", seqs);
  669. seqs = ggml_relu_inplace(ctx, seqs);
  670. seqs = Linear_forward(model, prefix + ".proj2", seqs);
  671. FORCE_ALLOC(ffn_scale, ctx, ggml_new_tensor_2d(ctx, GGML_TYPE_F32, 1, 1));
  672. ggml_set_f32(ffn_scale, 0.5f);
  673. seqs = ggml_mul(ctx, ggml_repeat(ctx, ffn_scale, seqs), seqs);
  674. seqs = ggml_add_inplace(ctx, seqs, residual);
  675. layer_idx = 0;
  676. layer_name = prefix + ".adaptor_layers." + std::to_string(layer_idx);
  677. while (has_layer(model, layer_name)) {
  678. seqs = StandardConformerEncoderAdaptorLayer_forward(
  679. model, layer_name, seqs, padding_mask
  680. );
  681. ggml_set_name(seqs, ("x_ada_" + std::to_string(layer_idx)).c_str());
  682. layer_idx += 1;
  683. layer_name = prefix + ".adaptor_layers." + std::to_string(layer_idx);
  684. }
  685. seqs = LayerNorm_forward(model, prefix + ".layer_norm", seqs);
  686. return seqs;
  687. }
  688. extern "C" ggml_tensor* StandardConformerEncoderAdaptorLayer_forward(
  689. fairseq2_model& model,
  690. const std::string& prefix,
  691. ggml_tensor* seqs,
  692. ggml_tensor* padding_mask
  693. ) {
  694. ggml_context* ctx = model.ctx;
  695. ggml_tensor* residual = seqs;
  696. residual = LayerNorm_forward(model, prefix + ".residual_layer_norm", residual);
  697. residual = ggml_dup(ctx, ggml_permute(ctx, residual, 1, 0, 2, 3));
  698. residual = ggml_conv_1d_generic(ctx, model.tensors[prefix + ".residual_conv.weight"], residual, 8, 4, 1);
  699. residual = ggml_dup(ctx, ggml_permute(ctx, residual, 1, 0, 2, 3));
  700. residual = ggml_add_inplace(ctx, ggml_repeat(ctx, model.tensors[prefix + ".residual_conv.bias"], residual), residual);
  701. residual = ggml_glu(ctx, residual);
  702. seqs = LayerNorm_forward(model, prefix + ".self_attn_layer_norm", seqs);
  703. seqs = ggml_dup(ctx, ggml_permute(ctx, seqs, 1, 0, 2, 3));
  704. seqs = ggml_conv_1d_generic(ctx, model.tensors[prefix + ".self_attn_conv.weight"], seqs, 8, 4, 1);
  705. seqs = ggml_dup(ctx, ggml_permute(ctx, seqs, 1, 0, 2, 3));
  706. seqs = ggml_add_inplace(ctx, seqs, ggml_repeat(ctx, model.tensors[prefix + ".self_attn_conv.bias"], seqs));
  707. seqs = ggml_glu(ctx, seqs);
  708. seqs = MultiheadAttention_forward(
  709. model,
  710. prefix + ".self_attn",
  711. seqs,
  712. seqs,
  713. seqs,
  714. /*attention masks=*/nullptr
  715. );
  716. seqs = ggml_add_inplace(ctx, seqs, residual);
  717. residual = seqs;
  718. seqs = LayerNorm_forward(model, prefix + ".ffn_layer_norm", seqs);
  719. seqs = StandardFeedForwardNetwork_forward(model, prefix + ".ffn", seqs);
  720. seqs = ggml_add_inplace(ctx, seqs, residual);
  721. return seqs;
  722. }
  723. /// ggml_slice(X, -1, start, end) is equivalent to X[start:end]
  724. /// ggml_slice(X, 0, start, end) is equivalent to X[..., start:end]
  725. ggml_tensor* ggml_slice(
  726. struct ggml_context * ctx,
  727. struct ggml_tensor * a,
  728. int axis,
  729. int64_t start,
  730. int64_t end
  731. ) {
  732. int64_t ne[4];
  733. std::copy(a->ne, a->ne + 4, ne);
  734. if (axis < 0) axis = a->n_dims + axis;
  735. if (start < 0) start = ne[axis] + start;
  736. if (end <= 0) end = ne[axis] + end;
  737. GGML_ASSERT(0 <= start);
  738. GGML_ASSERT(start < end);
  739. GGML_ASSERT(end <= ne[axis]);
  740. ne[axis] = end - start;
  741. size_t offset = a->nb[axis] * start;
  742. size_t* nb = a->nb;
  743. ggml_tensor* result = ggml_view_4d(ctx, a, ne[0], ne[1], ne[2], ne[3], nb[1], nb[2], nb[3], offset);
  744. ggml_format_name(result, "%s [(%d)%ld:%ld]", a->name, axis, start, end);
  745. result->n_dims = a->n_dims;
  746. return result;
  747. }
  748. ggml_tensor* ggml_select(
  749. struct ggml_context * ctx,
  750. struct ggml_tensor * a,
  751. int axis,
  752. int64_t index
  753. ) {
  754. int64_t ne[GGML_MAX_DIMS];
  755. std::copy(a->ne, a->ne + GGML_MAX_DIMS, ne);
  756. if (axis < 0) axis = a->n_dims + axis;
  757. if (index < 0) index = ne[axis] + index;
  758. GGML_ASSERT(0 <= index);
  759. GGML_ASSERT(index < ne[axis]);
  760. std::copy(a->ne + axis + 1, a->ne + GGML_MAX_DIMS, ne + axis);
  761. size_t offset = a->nb[axis] * index;
  762. size_t* nb = a->nb;
  763. GGML_ASSERT(GGML_MAX_DIMS == 4);
  764. ggml_tensor* result = ggml_view_3d(ctx, a, ne[0], ne[1], ne[2], nb[1], nb[2], offset);
  765. ggml_format_name(result, "%s [(%d)%ld]", a->name, axis, index);
  766. result->n_dims = a->n_dims - 1;
  767. return result;
  768. }
  769. // Inplace computation of PositionalEmbedding
  770. extern "C" ggml_tensor* PositionalEmbedding_forward(
  771. fairseq2_model& model,
  772. const std::string& prefix,
  773. ggml_tensor* embeds
  774. ) {
  775. // This only work with the simple pos encoders
  776. int seq_len = embeds->ne[1];
  777. ggml_tensor* full_pos_embeds = model.tensors[prefix];
  778. int start_step = 0;
  779. if (has_kv_cache(model)) {
  780. start_step = model.kv_cache[prefix].step_nr++;
  781. }
  782. ggml_tensor* pos_embeds = ggml_slice(model.ctx, full_pos_embeds, /*axis*/1, start_step, seq_len + start_step);
  783. return ggml_add(model.ctx, embeds, pos_embeds);
  784. }
  785. extern "C" ggml_tensor* TransformerEmbeddingFrontend_forward(
  786. fairseq2_model& model,
  787. const std::string& prefix,
  788. ggml_tensor* seqs
  789. ) {
  790. GGML_ASSERT(seqs->n_dims < GGML_MAX_DIMS);
  791. ggml_context* ctx = model.ctx;
  792. ggml_tensor* embed_weights = model.tensors[prefix + ".embed.weight"];
  793. GGML_ASSERT(embed_weights != nullptr);
  794. ggml_tensor* embeds;
  795. if (seqs->n_dims == 1) {
  796. embeds = ggml_get_rows(ctx, embed_weights, seqs);
  797. } else {
  798. // ggml_get_rows isn't very flexible, we have to handle the reshape ourselves.
  799. ggml_tensor* flat_seqs = seqs;
  800. if (!ggml_is_contiguous(seqs)) {
  801. flat_seqs = ggml_cont(ctx, flat_seqs);
  802. }
  803. flat_seqs = ggml_reshape_1d(ctx, flat_seqs, ggml_nelements(seqs));
  804. embeds = ggml_get_rows(ctx, embed_weights, flat_seqs);
  805. embeds = ggml_reshape_4d(ctx, embeds, embed_weights->ne[0], seqs->ne[0], seqs->ne[1], seqs->ne[2]);
  806. embeds->n_dims = seqs->n_dims + 1;
  807. }
  808. // padding mask ?
  809. // padding_mask = to_padding_mask(embeds, seq_lens)
  810. if (has_layer(model, prefix + ".pos_encoder")) {
  811. embeds = PositionalEmbedding_forward(model, prefix + ".pos_encoder", embeds);
  812. }
  813. if (has_layer(model, prefix + ".layer_norm")) {
  814. embeds = LayerNorm_forward(model, prefix + ".layer_norm", embeds);
  815. }
  816. return embeds;
  817. }
  818. extern "C" ggml_tensor* StandardTransformerEncoder_forward(
  819. fairseq2_model& model,
  820. const std::string& prefix,
  821. ggml_tensor* seqs,
  822. ggml_tensor* padding_mask
  823. ) {
  824. int layer_idx = 0;
  825. std::string layer_name = prefix + ".layers." + std::to_string(layer_idx);
  826. while (has_layer(model, layer_name)) {
  827. seqs = StandardTransformerEncoderLayer_forward(
  828. model, layer_name, seqs, padding_mask
  829. );
  830. ggml_set_name(seqs, ("x_enc_" + std::to_string(layer_idx)).c_str());
  831. layer_idx += 1;
  832. layer_name = prefix + ".layers." + std::to_string(layer_idx);
  833. }
  834. if (has_layer(model, prefix + ".layer_norm"))
  835. seqs = LayerNorm_forward(model, prefix + ".layer_norm", seqs);
  836. return seqs;
  837. }
  838. extern "C" ggml_tensor* StandardTransformerDecoderLayer_forward(
  839. fairseq2_model& model,
  840. const std::string& prefix,
  841. ggml_tensor* seqs,
  842. ggml_tensor* self_attn_mask,
  843. ggml_tensor* encoder_output,
  844. ggml_tensor* encoder_padding_mask
  845. ) {
  846. ggml_context* ctx = model.ctx;
  847. auto norm_order = model.layer_config.at(prefix + ".norm_order");
  848. // _forward_self_attn(seqs, padding_mask)
  849. auto residual = seqs;
  850. if (norm_order != TRANSFORMER_NORM_ORDER_POST)
  851. seqs = LayerNorm_forward(model, prefix + ".self_attn_layer_norm", seqs);
  852. seqs = MultiheadAttention_forward(
  853. model,
  854. prefix + ".self_attn",
  855. seqs,
  856. seqs,
  857. seqs,
  858. /*attn_mask=*/self_attn_mask
  859. );
  860. if (has_layer(model, prefix + ".self_attn_norm"))
  861. seqs = LayerNorm_forward(model, prefix + ".self_attn_norm", seqs);
  862. seqs = ggml_add_inplace(ctx, seqs, residual);
  863. if (norm_order == TRANSFORMER_NORM_ORDER_POST)
  864. seqs = LayerNorm_forward(model, prefix + ".self_attn_layer_norm", seqs);
  865. // _forward_encoder_decoder_attn
  866. if (! has_layer(model, prefix + ".encoder_decoder_attn")) {
  867. // `encoder_output` must be `None` for decoder-only attention.
  868. GGML_ASSERT(encoder_output == nullptr);
  869. return seqs;
  870. }
  871. // `encoder_output` must not be `None` for encoder-decoder attention.
  872. GGML_ASSERT(encoder_output != nullptr);
  873. residual = seqs;
  874. if (norm_order != TRANSFORMER_NORM_ORDER_POST)
  875. seqs = LayerNorm_forward(model, prefix + ".encoder_decoder_attn_layer_norm", seqs);
  876. seqs = MultiheadAttention_forward(
  877. model,
  878. prefix + ".encoder_decoder_attn",
  879. seqs,
  880. encoder_output,
  881. encoder_output,
  882. /*attention masks=*/encoder_padding_mask
  883. );
  884. seqs = ggml_add_inplace(ctx, seqs, residual);
  885. if (norm_order == TRANSFORMER_NORM_ORDER_POST)
  886. seqs = LayerNorm_forward(model, prefix + ".encoder_decoder_attn_layer_norm", seqs);
  887. // _forward_ffn(seqs)
  888. residual = seqs;
  889. if (norm_order != TRANSFORMER_NORM_ORDER_POST)
  890. seqs = LayerNorm_forward(model, prefix + ".ffn_layer_norm", seqs);
  891. seqs = StandardFeedForwardNetwork_forward(model, prefix + ".ffn", seqs);
  892. // TODO:
  893. // if self.residual_scale is not None:
  894. // residual = self.residual_scale * residual
  895. seqs = ggml_add_inplace(ctx, seqs, residual);
  896. if (norm_order == TRANSFORMER_NORM_ORDER_POST)
  897. seqs = LayerNorm_forward(model, prefix + ".ffn_layer_norm", seqs);
  898. return seqs;
  899. }
  900. extern "C" ggml_tensor* causal_attention_mask(ggml_context* ctx, ggml_tensor* seqs) {
  901. auto seq_len = seqs->ne[1];
  902. // TODO: allow other ggml_type
  903. ggml_tensor* mask = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, seq_len, seq_len);
  904. return ggml_diag_mask_inf(ctx, mask, 0);
  905. }
  906. extern "C" ggml_tensor* StandardTransformerDecoder_forward(
  907. fairseq2_model& model,
  908. const std::string& prefix,
  909. ggml_tensor* seqs,
  910. ggml_tensor* padding_mask,
  911. ggml_tensor* encoder_output,
  912. ggml_tensor* encoder_padding_mask
  913. ) {
  914. int layer_idx = 0;
  915. std::string layer_name = prefix + ".layers." + std::to_string(layer_idx);
  916. ggml_tensor* self_attn_mask = causal_attention_mask(model.ctx, seqs);
  917. while (has_layer(model, layer_name)) {
  918. seqs = StandardTransformerDecoderLayer_forward(
  919. model, layer_name, seqs, self_attn_mask, encoder_output, encoder_padding_mask
  920. );
  921. ggml_set_name(seqs, ("x_dec_" + std::to_string(layer_idx)).c_str());
  922. layer_idx += 1;
  923. layer_name = prefix + ".layers." + std::to_string(layer_idx);
  924. }
  925. if (has_layer(model, prefix + ".layer_norm"))
  926. seqs = LayerNorm_forward(model, prefix + ".layer_norm", seqs);
  927. return seqs;
  928. }
  929. int _determine_max_seq_len(const SequenceGeneratorJob& job, int source_seq_len) {
  930. auto opts = job.opts;
  931. int max_seq_len = -1;
  932. if (source_seq_len <= 0 || opts.soft_max_seq_len_a <= 0) {
  933. max_seq_len = opts.hard_max_seq_len;
  934. } else {
  935. max_seq_len = std::min(opts.hard_max_seq_len, int(opts.soft_max_seq_len_a * source_seq_len) + opts.soft_max_seq_len_b);
  936. }
  937. if (opts.min_seq_len > max_seq_len) {
  938. printf(
  939. "The effective maximum sequence length must be greater than or equal to `min_seq_len` (%d), but is %d instead. Adjust your soft and hard maximum sequence length limits.\n",
  940. opts.min_seq_len,
  941. max_seq_len
  942. );
  943. GGML_ASSERT(opts.min_seq_len <= max_seq_len);
  944. }
  945. int prefix_seq_len = job.prefix_seq->ne[0];
  946. if (prefix_seq_len >= max_seq_len) {
  947. printf(
  948. "The effective maximum sequence length must be greater than `prefix_seq_len` (%d), but is %d instead.\n",
  949. prefix_seq_len,
  950. max_seq_len
  951. );
  952. GGML_ASSERT(prefix_seq_len < max_seq_len);
  953. }
  954. return max_seq_len;
  955. }
  956. void _fan_out_encoder_output(
  957. ggml_context* ctx,
  958. ggml_tensor** encoder_output_out,
  959. ggml_tensor** encoder_padding_mask_out,
  960. int beam_size
  961. ) {
  962. // (S_enc, M)
  963. ggml_tensor* encoder_output = *encoder_output_out;
  964. ggml_tensor* encoder_padding_mask = *encoder_padding_mask_out;
  965. // (B, S_enc, M)
  966. ggml_tensor* shape = ggml_new_tensor_3d(ctx, GGML_TYPE_I8, encoder_output->ne[0], encoder_output->ne[1], beam_size);
  967. // (S_enc, M) -> (B, S_enc, M)
  968. *encoder_output_out = ggml_repeat(ctx, encoder_output, shape);
  969. // (S_enc) -> (B, S_enc)
  970. if (encoder_padding_mask != nullptr) {
  971. ggml_tensor* shape_mask = ggml_new_tensor_3d(ctx, GGML_TYPE_I8, encoder_padding_mask->ne[0], 1, beam_size);
  972. *encoder_padding_mask_out = ggml_repeat(ctx, encoder_padding_mask, shape_mask);
  973. }
  974. }
  975. ggml_tensor* ggml_log_softmax(ggml_context* ctx, ggml_tensor* logits) {
  976. // TODO: this isn't the most precise way of doing this
  977. return ggml_log_inplace(ctx, ggml_soft_max_inplace(ctx, logits));
  978. }
  979. ggml_tensor* ggml_expand_2d(ggml_context* ctx, ggml_tensor* x, int64_t ne0, int64_t ne1) {
  980. ggml_tensor* shape = ggml_new_tensor_2d(ctx, GGML_TYPE_I8, ne0, ne1);
  981. ggml_type true_type = x->type;
  982. ggml_tensor* y = ggml_repeat(ctx, x, shape);
  983. y->type = true_type;
  984. return y;
  985. }
  986. extern "C" void _bootstrap_seqs_and_scores(
  987. fairseq2_model& model,
  988. const SequenceGeneratorJob& job,
  989. ggml_tensor* full_seqs,
  990. ggml_tensor* scores,
  991. ggml_tensor* encoder_output,
  992. ggml_tensor* encoder_padding_mask,
  993. int n_threads
  994. ) {
  995. int prefix_seq_len = job.prefix_seq->ne[0];
  996. int max_seq_len = scores->ne[0];
  997. int beam_size = scores->ne[1];
  998. GGML_ASSERT(prefix_seq_len > 0);
  999. if (prefix_seq_len == 1)
  1000. return;
  1001. ggml_context* ctx = model.ctx;
  1002. // full_seqs[:, : prefix_seq_len] = job.prefix_seq;
  1003. ggml_tensor* seqs = ggml_slice(ctx, full_seqs, 0, 0, prefix_seq_len);
  1004. seqs = ggml_cpy(ctx, ggml_repeat(ctx, job.prefix_seq, seqs), seqs);
  1005. // We have to bootstrap the model with the already fanned-out encoder
  1006. // output to correctly initialize its incremental state.
  1007. // Note: we don't start decoding the last prefix token just yet.
  1008. seqs = ggml_slice(ctx, seqs, 0, 0, prefix_seq_len - 1);
  1009. // Bootstrap the model state with prefix sequence.
  1010. seqs = TransformerEmbeddingFrontend_forward(model, "text_decoder_frontend", seqs);
  1011. ggml_tensor* decoder_output = StandardTransformerDecoder_forward(
  1012. model,
  1013. "text_decoder",
  1014. seqs,
  1015. /*padding_mask*/ nullptr,
  1016. encoder_output,
  1017. encoder_padding_mask
  1018. );
  1019. // logits, lprobs: (N, S_pfx - 1, V)
  1020. ggml_tensor* logits = Linear_forward(model, "final_proj", decoder_output);
  1021. int vocab_size = logits->ne[0];
  1022. ggml_tensor* lprobs = ggml_log_softmax(ctx, ggml_slice(ctx, logits, 1, 0, 1));
  1023. ggml_cgraph gf = ggml_build_forward(lprobs);
  1024. ggml_graph_compute_with_ctx(ctx, &gf, 1);
  1025. // Fetch scores of next steps from "lprobs"
  1026. float p_score = 0;
  1027. for (int i = 1; i < prefix_seq_len; ++i) {
  1028. int p = ggml_get_i32_1d(job.prefix_seq, i);
  1029. p_score += ggml_get_f32_1d(lprobs, i * vocab_size + p);
  1030. for (int b = 0; b < beam_size; ++b) {
  1031. // scores: (N, S)
  1032. // Note: First step (e.g. BOS)'s score is always 0.
  1033. ggml_set_f32_1d(scores, b * max_seq_len + i, p_score);
  1034. }
  1035. }
  1036. }
  1037. /// Finds the topk indices, and write the winning indices in "candidate_indices" array.
  1038. int topk(
  1039. ggml_tensor* lprobs, // (B, V)
  1040. std::int64_t k,
  1041. ggml_tensor* candidate_indices
  1042. ) {
  1043. // Take the best 2 x `beam_size` predictions. We'll choose the first
  1044. // `beam_size` of these which don't predict EOS to continue with.
  1045. // (N, 2 x B)
  1046. // `vocab_size` - 1 to never select PAD.
  1047. std::int64_t K = std::min(k, ggml_nelements(lprobs));
  1048. auto comp = [lprobs](std::int32_t a, std::int32_t b) {
  1049. return ggml_get_f32_1d(lprobs, a) > ggml_get_f32_1d(lprobs, b);
  1050. };
  1051. GGML_ASSERT(ggml_nelements(candidate_indices) >= k);
  1052. auto cand = (std::int32_t*)candidate_indices->data;
  1053. std::partial_sort(cand, cand + K, cand + ggml_nelements(lprobs), comp);
  1054. return K;
  1055. }
  1056. void _tweak_lprobs(const SequenceGeneratorJob& job, ggml_tensor* lprobs, int step_nr, int max_seq_len, std::size_t vocab_size) {
  1057. std::size_t beam_size = job.opts.beam_size;
  1058. std::size_t eos_idx = job.eos_idx;
  1059. // Do not allow EOS before reaching the minimum sequence length.
  1060. if (step_nr < job.opts.min_seq_len) {
  1061. // lprobs[:, :, self.eos_idx] = -INFINITY;
  1062. for (size_t i = 0; i < beam_size; ++i)
  1063. ggml_set_f32_1d(lprobs, vocab_size * i + eos_idx, -INFINITY);
  1064. }
  1065. // If we have reached the maximum length, force the last step to be EOS.
  1066. if (step_nr == max_seq_len - 2) {
  1067. // lprobs[:, :, : self.eos_idx] = -torch.inf
  1068. // lprobs[:, :, self.eos_idx + 1 :] = -torch.inf
  1069. for (size_t b = 0; b < beam_size; ++b) {
  1070. size_t t = 0;
  1071. for (t = 0; t < eos_idx; ++t)
  1072. ggml_set_f32_1d(lprobs, vocab_size * b + t, -INFINITY);
  1073. for (t = eos_idx + 1; t < vocab_size; ++t)
  1074. ggml_set_f32_1d(lprobs, vocab_size * b + t, -INFINITY);
  1075. }
  1076. }
  1077. // Never allow PAD.
  1078. std::size_t pad_idx = job.pad_idx;
  1079. for (size_t i = 0; i < beam_size; ++i)
  1080. ggml_set_f32_1d(lprobs, vocab_size * i + pad_idx, -INFINITY);
  1081. // Apply UNK penalty.
  1082. if (job.unk_idx >= 0 && job.opts.unk_penalty != 0) {
  1083. // lprobs[:, :, self.unk_idx] -= self.opts.unk_penalty
  1084. auto lprobs_raw = ggml_get_data_f32(lprobs);
  1085. for (size_t i = 0; i < beam_size; ++i)
  1086. lprobs_raw[vocab_size * i + job.unk_idx] -= job.opts.unk_penalty;
  1087. }
  1088. }
  1089. /// Copies the sequence and scores of a given candidate beam.
  1090. void _finalize_hypothesis(
  1091. const SequenceGeneratorJob& job,
  1092. ggml_context* ctx,
  1093. int step_nr,
  1094. std::int32_t beam,
  1095. std::int32_t token,
  1096. float eos_score,
  1097. ggml_tensor* seqs, // (beam_size, seq_len)
  1098. ggml_tensor* scores, // (beam_size, seq_len)
  1099. Hypothesis* hypothesis
  1100. ) {
  1101. ggml_tensor* seq = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, step_nr + 2);
  1102. hypothesis->seq = seq;
  1103. ggml_tensor* step_scores = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, step_nr + 2);
  1104. hypothesis->step_scores = step_scores;
  1105. auto tok = (std::int32_t*)seq->data;
  1106. for (int i = 0; i < step_nr + 1; ++i) {
  1107. tok[i] = ggml_get_i32_1d(seqs, seqs->ne[0] * beam + i);
  1108. }
  1109. tok[step_nr + 1] = token;
  1110. // Convert from cumulative to per-step scores.
  1111. auto sc = (float*)step_scores->data;
  1112. float last_score = eos_score;
  1113. for (int i = step_nr; i >= 0; --i) {
  1114. float sc0 = ggml_get_f32_1d(scores, scores->ne[0] * beam + i);
  1115. sc[i + 1] = last_score - sc0;
  1116. last_score = sc0;
  1117. }
  1118. sc[0] = 0;
  1119. if (job.opts.normalize_scores)
  1120. // Skip first EOS since it is always 0 and skews normalization.
  1121. eos_score /= (float)std::pow((step_nr + 1), job.opts.len_penalty);
  1122. hypothesis->score = eos_score;
  1123. }
  1124. // Uses ggml_context to store any object.
  1125. #define GGML_CTX_ALLOC(ctx, Type, n) \
  1126. (Type*)(ggml_new_tensor_1d(ctx, GGML_TYPE_I8, sizeof(Type) * n)->data);
  1127. ggml_context* ctx_from_buffer(std::vector<uint8_t>& buffer) {
  1128. return ggml_init({
  1129. /*.mem_size =*/ static_cast<int64_t>(buffer.capacity()),
  1130. /*.mem_buffer =*/ buffer.data(),
  1131. /*.no_alloc =*/ false,
  1132. });
  1133. }
  1134. ggml_allocr* new_arena_allocr(std::vector<uint8_t>& buffer) {
  1135. return ggml_allocr_new(buffer.data(), buffer.capacity(), 8);
  1136. }
  1137. /// Generates a translation for a single sequence
  1138. /// The results Hypothesis are written inside `result_ctx`.
  1139. extern "C" Hypothesis* generate_sequence(
  1140. fairseq2_model& model,
  1141. const SequenceGeneratorJob& job,
  1142. ggml_tensor* encoder_output,
  1143. ggml_tensor* encoder_padding_mask,
  1144. ggml_context* result_ctx,
  1145. int n_threads
  1146. ) {
  1147. // Pre allocate memory buffers.
  1148. // * step_ctx: contains metadata for the model graph, as well as some explicit
  1149. // buffers for the lprobs tweaking.
  1150. // * prev_step_ctx: is an additional buffer because we need some results from previous steps,
  1151. // to compute next step. Notably self attention kv cache.
  1152. // * search_ctx contains tensors that should live for the full search,
  1153. // like encoder kv cache.
  1154. // * step_alloc contains buffer for the forward pass of the model.
  1155. // TODO: the size allocated should depend on the input length and vocab size
  1156. std::vector<uint8_t> local_bufs[5] = {
  1157. std::vector<uint8_t>(128 * 1024 * 1024), // step_ctx
  1158. std::vector<uint8_t>(128 * 1024 * 1024), // prev_step_ctx
  1159. std::vector<uint8_t>(256 * 1024 * 1024), // search_ctx
  1160. std::vector<uint8_t>(256 * 1024 * 1024), // step_alloc
  1161. };
  1162. ggml_allocr* step_alloc = new_arena_allocr(local_bufs[3]);
  1163. ggml_tensor* embed = model.tensors["text_decoder_frontend.embed.weight"];
  1164. size_t vocab_size = embed->ne[1];
  1165. std::size_t beam_size = job.opts.beam_size;
  1166. ggml_detach(encoder_output);
  1167. int source_seq_len = encoder_output->ne[1];
  1168. int max_seq_len = _determine_max_seq_len(job, source_seq_len);
  1169. ggml_context* search_ctx = ctx_from_buffer(local_bufs[2]);
  1170. ggml_context* original_ctx = model.ctx;
  1171. fairseq2_kv_cache_alloc(model, search_ctx, beam_size, max_seq_len);
  1172. // (S_enc, M) -> (B, S_enc, M)
  1173. model.ctx = search_ctx;
  1174. _fan_out_encoder_output(search_ctx, &encoder_output, &encoder_padding_mask, beam_size);
  1175. // Allocate results in the context provided by the caller.
  1176. ggml_set_no_alloc(result_ctx, false);
  1177. Hypothesis* finished_searches_begin = GGML_CTX_ALLOC(result_ctx, Hypothesis, beam_size);
  1178. Hypothesis* finished_searches = finished_searches_begin;
  1179. for (std::size_t i = 0; i < beam_size; ++i) finished_searches[i] = {nullptr, -INFINITY, nullptr};
  1180. Hypothesis* finished_searches_end = finished_searches + beam_size;
  1181. // Initialize buffers. (B, S)
  1182. ggml_tensor* seqs = ggml_new_tensor_2d(search_ctx, GGML_TYPE_I32, max_seq_len, beam_size);
  1183. ggml_set_i32(seqs, 0);
  1184. ggml_set_name(seqs, "seqs_0");
  1185. ggml_tensor* scores = ggml_new_tensor_2d(search_ctx, GGML_TYPE_F32, max_seq_len, beam_size);
  1186. ggml_set_name(scores, "scores_0");
  1187. ggml_set_f32(scores, 0.0);
  1188. int prefix_seq_len = job.prefix_seq->ne[0];
  1189. int start_step = prefix_seq_len - 1;
  1190. ggml_context* prev_step_ctx = ctx_from_buffer(local_bufs[(start_step - 1) % 2]);
  1191. ggml_context* step_ctx = ctx_from_buffer(local_bufs[start_step % 2]);
  1192. GGML_ASSERT(step_ctx != search_ctx);
  1193. GGML_ASSERT(prev_step_ctx != step_ctx);
  1194. model.ctx = prev_step_ctx;
  1195. // search_ctx because we need encoder_decoder_attn.k_cache to survive for the full search
  1196. model.kv_cache_ctx = search_ctx;
  1197. _bootstrap_seqs_and_scores(
  1198. model, job, seqs, scores, encoder_output, encoder_padding_mask, n_threads
  1199. );
  1200. // Holds the indices of beams (a beam can occur more than once) that we
  1201. // should continue with in the next step.
  1202. ggml_tensor* beam_indices = ggml_new_tensor_1d(search_ctx, GGML_TYPE_I32, beam_size);
  1203. ggml_tensor* next_tokens = ggml_new_tensor_1d(search_ctx, GGML_TYPE_I32, beam_size);
  1204. ggml_tensor* next_scores = ggml_new_tensor_1d(search_ctx, GGML_TYPE_F32, beam_size);
  1205. // Array with integers up to 'vocab_size * beam_size' to represent next beams to explore
  1206. ggml_tensor* candidate_indices = ggml_new_tensor_1d(search_ctx, GGML_TYPE_I32, vocab_size * beam_size);
  1207. for (std::size_t i = 0; i < vocab_size * beam_size; ++i)
  1208. ((int32_t *)(candidate_indices->data))[i] = i;
  1209. printf_mem_usage(search_ctx, "search_ctx");
  1210. for (int step_nr = start_step; step_nr < max_seq_len - 1; ++step_nr) {
  1211. model.ctx = step_ctx;
  1212. ggml_set_no_alloc(step_ctx, true); // Use allocr for the model forward pass
  1213. ggml_tensor* prev_token = ggml_slice(step_ctx, seqs, 0, step_nr, step_nr + 1);
  1214. ggml_tensor* decoder_input = TransformerEmbeddingFrontend_forward(model, "text_decoder_frontend", prev_token);
  1215. ggml_tensor* decoder_output = StandardTransformerDecoder_forward(
  1216. model,
  1217. "text_decoder",
  1218. decoder_input,
  1219. nullptr, // We never generate PAD.
  1220. encoder_output,
  1221. encoder_padding_mask
  1222. ); // (B, 1, D)
  1223. decoder_output = ggml_flatten_1d(step_ctx, decoder_output, 0); // (B, model_dim)
  1224. // Force logits to be allocated in step_ctx, not in step_alloc.
  1225. ggml_set_no_alloc(step_ctx, false);
  1226. ggml_tensor* logits = Linear_forward(model, "final_proj", decoder_output); // (B, vocab_size)
  1227. ggml_tensor* lprobs = ggml_log_softmax(step_ctx, logits);
  1228. // Compute lprobs here so we can modify it in place in the lprob tweaking phase
  1229. // TODO: use ggml properly compute the tweaks
  1230. ggml_cgraph gf = ggml_build_forward(lprobs);
  1231. size_t fwd_mem = ggml_allocr_alloc_graph(step_alloc, &gf);
  1232. GGML_UNUSED(fwd_mem);
  1233. ggml_graph_compute_with_ctx(step_ctx, &gf, 1);
  1234. ggml_detach(lprobs);
  1235. ggml_allocr_reset(step_alloc);
  1236. #if DEBUG_MEM_USAGE
  1237. printf("beam search step %d. Graph.n_nodes: %d.\n", step_nr, gf.n_nodes);
  1238. printf(" Fwd mem: %.1fMB\n", fwd_mem/1024.0/1024.0);
  1239. std::fill(local_bufs[3].begin(), local_bufs[3].end(), 0xAA);
  1240. #endif
  1241. _tweak_lprobs(job, lprobs, step_nr, max_seq_len, vocab_size);
  1242. ggml_tensor* last_scores = ggml_slice(step_ctx, scores, 0, step_nr, step_nr+1);
  1243. if (step_nr == start_step) {
  1244. // At the initial step, all hypotheses are equally likely, so we use
  1245. // only the first beam.
  1246. lprobs = ggml_slice(step_ctx, lprobs, 1, 0, 1);
  1247. lprobs = ggml_cont(step_ctx, lprobs);
  1248. // The first step always indicates the beginning of the sequence and has no score.
  1249. if (step_nr > 0) {
  1250. last_scores = ggml_slice(step_ctx, last_scores, 1, 0, 1);
  1251. lprobs = ggml_add_inplace(step_ctx, lprobs, ggml_repeat(step_ctx, last_scores, lprobs));
  1252. }
  1253. } else {
  1254. // Make probabilities contain cumulative scores for each hypothesis.
  1255. lprobs = ggml_add_inplace(step_ctx, lprobs, ggml_repeat(step_ctx, last_scores, lprobs));
  1256. }
  1257. gf = ggml_build_forward(lprobs);
  1258. ggml_graph_compute_with_ctx(step_ctx, &gf, n_threads);
  1259. // Determine (beam, token) candidates for the next step.
  1260. // (N, 2 x B)
  1261. std::int64_t K = topk(
  1262. lprobs, std::min(2 * beam_size, vocab_size - 1), candidate_indices
  1263. );
  1264. std::size_t ongoing_beams = 0;
  1265. for (std::int32_t i = 0; i < K; ++i) {
  1266. int c = ggml_get_f32_1d(candidate_indices, i);
  1267. std::int32_t beam = c / vocab_size;
  1268. std::int32_t token = c % vocab_size;
  1269. float tok_score = ggml_get_f32_1d(lprobs, c);
  1270. // Detect beams that reached the minimum length and that end with an EOS.
  1271. bool eos = token == job.eos_idx;
  1272. eos &= tok_score != -INFINITY;
  1273. if (eos) {
  1274. _finalize_hypothesis(job, result_ctx, step_nr, beam, token, tok_score, seqs, scores, finished_searches++);
  1275. if (finished_searches == finished_searches_end)
  1276. goto end_of_beam_search;
  1277. continue;
  1278. }
  1279. ggml_set_f32_1d(beam_indices, ongoing_beams, beam);
  1280. ggml_set_f32_1d(next_tokens, ongoing_beams, token);
  1281. ggml_set_f32_1d(next_scores, ongoing_beams, tok_score);
  1282. ongoing_beams += 1;
  1283. if (ongoing_beams >= beam_size) break;
  1284. }
  1285. // Reorder beams in the `seq` and `score` buffers. The same beam can
  1286. // be selected more than once.
  1287. // (B, S), (B) -> (B, S)
  1288. ggml_tensor* new_seqs = ggml_get_rows(step_ctx, seqs, beam_indices);
  1289. ggml_tensor* new_scores = ggml_get_rows(step_ctx, scores, beam_indices);
  1290. ggml_cgraph gf_reorder = ggml_build_forward(new_seqs);
  1291. ggml_build_forward_expand(&gf_reorder, new_scores);
  1292. reorder_kv_cache(model, step_ctx, &gf_reorder, beam_indices);
  1293. ggml_graph_compute_with_ctx(step_ctx, &gf_reorder, 1);
  1294. seqs = ggml_detach(new_seqs);
  1295. scores = ggml_detach(new_scores);
  1296. // seqs[:, step_nr + 1] = next_tokens
  1297. // scores[:, step_nr + 1] = next_scores
  1298. for (std::size_t i = 0; i < beam_size; ++i) {
  1299. ((std::int32_t*)seqs->data)[step_nr + 1 + i * max_seq_len] = ggml_get_i32_1d(next_tokens, i);
  1300. ((float*)scores->data)[step_nr + 1 + i * max_seq_len] = ggml_get_f32_1d(next_scores, i);
  1301. }
  1302. printf_mem_usage(step_ctx, "step_ctx");
  1303. ggml_free(prev_step_ctx);
  1304. prev_step_ctx = step_ctx;
  1305. #if DEBUG_MEM_USAGE
  1306. std::fill(local_bufs[(step_nr + 1) % 2].begin(), local_bufs[(step_nr + 1) % 2].end(), 0xAA);
  1307. #endif
  1308. step_ctx = ctx_from_buffer(local_bufs[(step_nr + 1) % 2]);
  1309. }
  1310. end_of_beam_search:
  1311. // Ensure that hypotheses are sorted by decreasing scores before returning.
  1312. std::sort(
  1313. finished_searches_begin,
  1314. finished_searches_end,
  1315. [](Hypothesis a, Hypothesis b) { return a.score > b.score; }
  1316. );
  1317. fairseq2_kv_cache_reset(model);
  1318. model.ctx = original_ctx;
  1319. return finished_searches_begin;
  1320. }
  1321. extern "C" Hypothesis* _testing_return_hypothesis_ptr(ggml_context* ctx) {
  1322. Hypothesis* result = GGML_CTX_ALLOC(ctx, struct Hypothesis, 2);
  1323. result[0] = {ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1), 3.14f, (ggml_tensor*)result};
  1324. ggml_set_i32_1d(result[0].seq, 0, 314);
  1325. result[1] = {ggml_new_tensor_1d(ctx, GGML_TYPE_I32, 1), 4.21f, nullptr};
  1326. ggml_set_i32_1d(result[1].seq, 0, 421);
  1327. return result;
  1328. }
  1329. // SPM tokenizer
  1330. // original implementation:
  1331. // https://github.com/ggerganov/llama.cpp/commit/074bea2eb1f1349a0118239c4152914aecaa1be4
  1332. struct llm_symbol {
  1333. using index = int;
  1334. index prev;
  1335. index next;
  1336. const char * text;
  1337. size_t n;
  1338. llama_vocab::id id;
  1339. };
  1340. static_assert(std::is_trivially_copyable<llm_symbol>::value, "llm_symbol is not trivially copyable");
  1341. static size_t utf8_len(char src) {
  1342. const size_t lookup[] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 4 };
  1343. uint8_t highbits = static_cast<uint8_t>(src) >> 4;
  1344. return lookup[highbits];
  1345. }
  1346. struct llm_bigram_spm {
  1347. struct comparator {
  1348. bool operator()(llm_bigram_spm & l, llm_bigram_spm & r) {
  1349. return (l.score < r.score) || (l.score == r.score && l.left > r.left);
  1350. }
  1351. };
  1352. using queue_storage = std::vector<llm_bigram_spm>;
  1353. using queue = std::priority_queue<llm_bigram_spm, queue_storage, comparator>;
  1354. llm_symbol::index left;
  1355. llm_symbol::index right;
  1356. float score;
  1357. size_t size;
  1358. llama_vocab::id id;
  1359. };
  1360. struct llm_tokenizer_spm {
  1361. llm_tokenizer_spm(const llama_vocab & vocab): vocab(vocab) {}
  1362. void tokenize(const std::string& input_text, ggml_tensor& output) {
  1363. llama_vocab::id unk_idx = vocab.token_to_id.at("<unk>");
  1364. // split string into utf8 chars
  1365. int index = 0;
  1366. size_t offs = 0;
  1367. // This is kind of annoying, but needed because with SPM,
  1368. // characters following a space have a special meaning.
  1369. // And the algorithm rely on substrings to do the lookups.
  1370. std::string text = input_text;
  1371. bool need_extra_space = text.size() > 0 && text[0] != ' ';
  1372. if (need_extra_space) text = " " + text;
  1373. while (offs < text.size()) {
  1374. size_t len = utf8_len(text[offs]);
  1375. size_t n = std::min(len, text.size() - offs);
  1376. auto token = vocab.token_to_id.find(std::string(text, offs, n));
  1377. llama_vocab::id id = token == vocab.token_to_id.end() ? unk_idx : token->second;
  1378. llm_symbol sym = {
  1379. /*prev*/ index - 1,
  1380. /*next*/ offs + n == text.size() ? -1 : index + 1,
  1381. /*text*/ text.c_str() + offs,
  1382. /*n*/ n,
  1383. /*id*/ id
  1384. };
  1385. offs += n;
  1386. index++;
  1387. symbols.emplace_back(sym);
  1388. }
  1389. // seed the work queue with all possible 2-character tokens.
  1390. for (size_t i = 1; i < symbols.size(); ++i) {
  1391. try_add_bigram(i - 1, i);
  1392. }
  1393. // keep substituting the highest frequency pairs for as long as we can.
  1394. while (!work_queue.empty()) {
  1395. auto bigram = work_queue.top();
  1396. work_queue.pop();
  1397. auto & left_sym = symbols[bigram.left];
  1398. auto & right_sym = symbols[bigram.right];
  1399. const std::string text = std::string(left_sym.text, left_sym.n + right_sym.n);
  1400. // if one of the symbols already got merged, skip it.
  1401. if (
  1402. left_sym.n == 0
  1403. || right_sym.n == 0
  1404. || left_sym.n + right_sym.n != bigram.size
  1405. ) continue;
  1406. // merge the right sym into the left one
  1407. left_sym.n += right_sym.n;
  1408. left_sym.id = bigram.id;
  1409. right_sym.n = 0;
  1410. // remove the right sym from the chain
  1411. left_sym.next = right_sym.next;
  1412. if (right_sym.next >= 0) {
  1413. symbols[right_sym.next].prev = bigram.left;
  1414. }
  1415. // find more substitutions
  1416. try_add_bigram(left_sym.prev, bigram.left);
  1417. try_add_bigram(bigram.left, left_sym.next);
  1418. }
  1419. llama_vocab::id* out = (llama_vocab::id*)output.data;
  1420. int out_step = sizeof(llama_vocab::id) / output.nb[0];
  1421. int num_tokens = 0;
  1422. for (int i = 0; i > -1; i = symbols[i].next) {
  1423. llm_symbol& symbol = symbols[i];
  1424. *(out + num_tokens * out_step) = symbol.id;
  1425. num_tokens += 1;
  1426. }
  1427. *(out + num_tokens * out_step) = vocab.token_to_id.at("</s>");
  1428. num_tokens += 1;
  1429. output.ne[0] = num_tokens;
  1430. }
  1431. private:
  1432. void try_add_bigram(int left, int right) {
  1433. if (left == -1 || right == -1) {
  1434. return;
  1435. }
  1436. const std::string text = std::string(symbols[left].text, symbols[left].n + symbols[right].n);
  1437. auto token = vocab.token_to_id.find(text);
  1438. if (token == vocab.token_to_id.end()) {
  1439. return;
  1440. }
  1441. llama_vocab::id id = token->second;
  1442. if (static_cast<size_t>(id) >= vocab.id_to_token.size()) {
  1443. return;
  1444. }
  1445. const auto& tok_data = vocab.id_to_token[id];
  1446. llm_bigram_spm bigram = {
  1447. /*left */ left,
  1448. /*right*/ right,
  1449. /*score*/ tok_data.score,
  1450. /*size */ text.size(),
  1451. /*id */ id
  1452. };
  1453. work_queue.push(bigram);
  1454. }
  1455. const llama_vocab& vocab;
  1456. std::vector<llm_symbol> symbols;
  1457. llm_bigram_spm::queue work_queue;
  1458. };
  1459. extern "C" void fairseq2_spm_tokenize(fairseq2_model* model, const char* text, ggml_tensor& out) {
  1460. llm_tokenizer_spm spm = {model->vocab};
  1461. spm.tokenize(std::string(text), out);
  1462. }
  1463. extern "C" std::size_t fairseq2_spm_detokenize(fairseq2_model* model, ggml_tensor* tokens, char* out) {
  1464. int eos_idx = model->vocab.token_to_id["</s>"];
  1465. int sent_len = tokens->ne[0];
  1466. std::size_t written = 0;
  1467. for (int i = 0; i < sent_len; ++i) {
  1468. int id = ggml_get_i32_1d(tokens, i);
  1469. // Don't print the EOS token but only if it appear at the end.
  1470. if (i == sent_len - 1 && eos_idx == id) break;
  1471. std::string token = model->vocab.id_to_token.at(id).text;
  1472. // Skip the first space outputted.
  1473. auto begin = token.begin();
  1474. if (i == 0 && token.size() > 0 && token[0] == ' ') begin += 1;
  1475. std::copy(begin, token.end(), out);
  1476. std::size_t n = token.end() - begin;
  1477. written += n;
  1478. out += n;
  1479. }
  1480. *out = '0';
  1481. return written;
  1482. }