fairseq2.cpp 65 KB

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