You can not select more than 25 topics Topics must start with a chinese character,a letter or number, can include dashes ('-') and can be up to 35 characters long.

multiheadattention.cpp 9.3 kB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307
  1. // Tencent is pleased to support the open source community by making ncnn available.
  2. //
  3. // Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved.
  4. //
  5. // Licensed under the BSD 3-Clause License (the "License"); you may not use this file except
  6. // in compliance with the License. You may obtain a copy of the License at
  7. //
  8. // https://opensource.org/licenses/BSD-3-Clause
  9. //
  10. // Unless required by applicable law or agreed to in writing, software distributed
  11. // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. // CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. // specific language governing permissions and limitations under the License.
  14. #include "multiheadattention.h"
  15. #include <float.h>
  16. namespace ncnn {
  17. MultiHeadAttention::MultiHeadAttention()
  18. {
  19. }
  20. int MultiHeadAttention::load_param(const ParamDict& pd)
  21. {
  22. embed_dim = pd.get(0, 0);
  23. num_heads = pd.get(1, 1);
  24. weight_data_size = pd.get(2, 0);
  25. kdim = pd.get(3, embed_dim);
  26. vdim = pd.get(4, embed_dim);
  27. attn_mask = pd.get(5, 0);
  28. return 0;
  29. }
  30. int MultiHeadAttention::load_model(const ModelBin& mb)
  31. {
  32. q_weight_data = mb.load(weight_data_size, 0);
  33. if (q_weight_data.empty())
  34. return -100;
  35. q_bias_data = mb.load(embed_dim, 1);
  36. if (q_bias_data.empty())
  37. return -100;
  38. k_weight_data = mb.load(embed_dim * kdim, 0);
  39. if (k_weight_data.empty())
  40. return -100;
  41. k_bias_data = mb.load(embed_dim, 1);
  42. if (k_bias_data.empty())
  43. return -100;
  44. v_weight_data = mb.load(embed_dim * vdim, 0);
  45. if (v_weight_data.empty())
  46. return -100;
  47. v_bias_data = mb.load(embed_dim, 1);
  48. if (v_bias_data.empty())
  49. return -100;
  50. out_weight_data = mb.load(weight_data_size, 0);
  51. if (out_weight_data.empty())
  52. return -100;
  53. out_bias_data = mb.load(embed_dim, 1);
  54. if (out_bias_data.empty())
  55. return -100;
  56. return 0;
  57. }
  58. // refers to https://pytorch.org/docs/stable/generated/torch.nn.MultiheadAttention.html
  59. int MultiHeadAttention::forward(const std::vector<Mat>& bottom_blobs, std::vector<Mat>& top_blobs, const Option& opt) const
  60. {
  61. const Mat& q_blob = bottom_blobs[0];
  62. const Mat& k_blob = (bottom_blobs.size() == 1 || (bottom_blobs.size() == 2 && attn_mask)) ? q_blob : bottom_blobs[1];
  63. const Mat& v_blob = (bottom_blobs.size() == 1 || (bottom_blobs.size() == 2 && attn_mask)) ? q_blob : (bottom_blobs.size() == 2 || (bottom_blobs.size() == 3 && attn_mask)) ? k_blob : bottom_blobs[2];
  64. const Mat& attn_mask_blob = attn_mask ? bottom_blobs[bottom_blobs.size() - 1] : Mat();
  65. const int src_seqlen = q_blob.h;
  66. const int dst_seqlen = k_blob.h;
  67. const int embed_dim_per_head = embed_dim / num_heads;
  68. // assert k_blob.h == v_blob.h
  69. Mat& top_blob = top_blobs[0];
  70. top_blob.create(embed_dim, src_seqlen, 4u, opt.blob_allocator);
  71. if (top_blob.empty())
  72. return -1;
  73. Mat xq(embed_dim_per_head, src_seqlen, num_heads, 4u, opt.workspace_allocator);
  74. Mat xk(embed_dim_per_head, dst_seqlen, num_heads, 4u, opt.workspace_allocator);
  75. Mat xv(dst_seqlen, embed_dim_per_head, num_heads, 4u, opt.workspace_allocator);
  76. Mat xqk(dst_seqlen, src_seqlen, num_heads, 4u, opt.workspace_allocator);
  77. Mat xqkv(embed_dim_per_head, num_heads, src_seqlen, 4u, opt.workspace_allocator);
  78. const float inv_sqrt_embed_dim_per_head = 1.f / sqrtf(embed_dim_per_head);
  79. #pragma omp parallel for num_threads(opt.num_threads)
  80. for (int q = 0; q < num_heads; q++)
  81. {
  82. // xq = affine(q) * inv_sqrt_embed_dim_per_head
  83. {
  84. Mat outm = xq.channel(q);
  85. for (int i = 0; i < src_seqlen; i++)
  86. {
  87. float* outptr = outm.row(i);
  88. for (int j = 0; j < embed_dim_per_head; j++)
  89. {
  90. const float* ptr = q_blob.row(i);
  91. const float* kptr = (const float*)q_weight_data + embed_dim * (q * embed_dim_per_head + j);
  92. float sum = q_bias_data[q * embed_dim_per_head + j];
  93. for (int k = 0; k < embed_dim; k++)
  94. {
  95. sum += *ptr++ * *kptr++;
  96. }
  97. outptr[j] = sum * inv_sqrt_embed_dim_per_head;
  98. }
  99. }
  100. }
  101. // xk = affine(k)
  102. {
  103. Mat outm = xk.channel(q);
  104. for (int i = 0; i < dst_seqlen; i++)
  105. {
  106. float* outptr = outm.row(i);
  107. for (int j = 0; j < embed_dim_per_head; j++)
  108. {
  109. const float* ptr = k_blob.row(i);
  110. const float* kptr = (const float*)k_weight_data + kdim * (q * embed_dim_per_head + j);
  111. float sum = k_bias_data[q * embed_dim_per_head + j];
  112. for (int k = 0; k < kdim; k++)
  113. {
  114. sum += *ptr++ * *kptr++;
  115. }
  116. outptr[j] = sum;
  117. }
  118. }
  119. }
  120. // xv = affine(v)
  121. {
  122. Mat outm = xv.channel(q);
  123. for (int i = 0; i < embed_dim_per_head; i++)
  124. {
  125. for (int j = 0; j < dst_seqlen; j++)
  126. {
  127. const float* ptr = v_blob.row(j);
  128. const float* kptr = (const float*)v_weight_data + vdim * (q * embed_dim_per_head + i);
  129. float sum = v_bias_data[q * embed_dim_per_head + i];
  130. for (int k = 0; k < vdim; k++)
  131. {
  132. sum += *ptr++ * *kptr++;
  133. }
  134. float* outptr = outm.row(i);
  135. outptr[j] = sum;
  136. }
  137. }
  138. }
  139. // xqk = xq * xk
  140. // xq (embed_dim_per_head, src_seqlen)
  141. // xk (embed_dim_per_head, dst_seqlen)
  142. {
  143. const Mat xqm = xq.channel(q);
  144. const Mat xkm = xk.channel(q);
  145. Mat outm = xqk.channel(q);
  146. for (int i = 0; i < src_seqlen; i++)
  147. {
  148. float* outptr = outm.row(i);
  149. for (int j = 0; j < dst_seqlen; j++)
  150. {
  151. const float* qptr = xqm.row(i);
  152. const float* kptr = xkm.row(j);
  153. float sum = 0.f;
  154. for (int k = 0; k < embed_dim_per_head; k++)
  155. {
  156. sum += *qptr++ * *kptr++;
  157. }
  158. outptr[j] = sum;
  159. }
  160. }
  161. }
  162. // xqk = xqk + mask
  163. if (attn_mask)
  164. {
  165. const Mat& maskm = attn_mask_blob.dims == 3 ? attn_mask_blob.channel(q) : attn_mask_blob;
  166. Mat outm = xqk.channel(q);
  167. for (int i = 0; i < src_seqlen; i++)
  168. {
  169. const float* mptr = maskm.row(i);
  170. float* outptr = outm.row(i);
  171. for (int j = 0; j < dst_seqlen; j++)
  172. {
  173. outptr[j] += mptr[j];
  174. }
  175. }
  176. }
  177. // softmax(xqk)
  178. {
  179. Mat outm = xqk.channel(q);
  180. for (int i = 0; i < src_seqlen; i++)
  181. {
  182. float* ptr = outm.row(i);
  183. float max = -FLT_MAX;
  184. for (int j = 0; j < dst_seqlen; j++)
  185. {
  186. max = std::max(max, ptr[j]);
  187. }
  188. float sum = 0.f;
  189. for (int j = 0; j < dst_seqlen; j++)
  190. {
  191. ptr[j] = (float)(expf(ptr[j] - max));
  192. sum += ptr[j];
  193. }
  194. for (int j = 0; j < dst_seqlen; j++)
  195. {
  196. ptr[j] /= sum;
  197. }
  198. }
  199. }
  200. // xqkv = xqk * xv
  201. // xqk (dst_seqlen, src_seqlen)
  202. // xv (dst_seqlen, embed_dim_per_head)
  203. // out (embed_dim_per_head, num_heads, src_seqlen)
  204. {
  205. const Mat xqkm = xqk.channel(q);
  206. const Mat xvm = xv.channel(q);
  207. for (int i = 0; i < src_seqlen; i++)
  208. {
  209. float* outptr = xqkv.channel(i).row(q);
  210. for (int j = 0; j < embed_dim_per_head; j++)
  211. {
  212. const float* qkptr = xqkm.row(i);
  213. const float* vptr = xvm.row(j);
  214. float sum = 0.f;
  215. for (int k = 0; k < dst_seqlen; k++)
  216. {
  217. sum += *qkptr++ * *vptr++;
  218. }
  219. outptr[j] = sum;
  220. }
  221. }
  222. }
  223. }
  224. // out = affine(xqkv)
  225. // xqkv (embed_dim, src_seqlen)
  226. #pragma omp parallel for num_threads(opt.num_threads)
  227. for (int i = 0; i < src_seqlen; i++)
  228. {
  229. float* outptr = top_blob.row(i);
  230. for (int j = 0; j < embed_dim; j++)
  231. {
  232. const float* ptr = xqkv.channel(i);
  233. const float* kptr = (const float*)out_weight_data + embed_dim * j;
  234. float sum = out_bias_data[j];
  235. for (int k = 0; k < embed_dim; k++)
  236. {
  237. sum += *ptr++ * *kptr++;
  238. }
  239. outptr[j] = sum;
  240. }
  241. }
  242. return 0;
  243. }
  244. } // namespace ncnn