Elffuss BraidHub

kikocis/ncnn public

master · 2.5 KiBRawPermalink
1// Tencent is pleased to support the open source community by making ncnn available.
2//
3// Copyright (C) 2024 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
15#include "testutil.h"
16
17static int test_multiheadattention_oom(const ncnn::Mat& q, const ncnn::Mat& k, const ncnn::Mat& v, int embed_dim, int num_heads, int attn_mask)
18{
19 const int qdim = q.w;
20 const int kdim = k.w;
21 const int vdim = v.w;
22
23 ncnn::ParamDict pd;
24 pd.set(0, embed_dim);
25 pd.set(1, num_heads);
26 pd.set(2, embed_dim * qdim);
27 pd.set(3, kdim);
28 pd.set(4, vdim);
29 pd.set(5, attn_mask);
30
31 std::vector<ncnn::Mat> weights(8);
32 weights[0] = RandomMat(embed_dim * qdim);
33 weights[1] = RandomMat(embed_dim);
34 weights[2] = RandomMat(embed_dim * kdim);
35 weights[3] = RandomMat(embed_dim);
36 weights[4] = RandomMat(embed_dim * vdim);
37 weights[5] = RandomMat(embed_dim);
38 weights[6] = RandomMat(qdim * embed_dim);
39 weights[7] = RandomMat(qdim);
40
41 std::vector<ncnn::Mat> as(3);
42 as[0] = q;
43 as[1] = k;
44 as[2] = v;
45
46 if (attn_mask)
47 {
48 as.push_back(RandomMat(k.h, q.h));
49 }
50
51 int ret = test_layer_oom("MultiHeadAttention", pd, weights, as, 1);
52 if (ret != 0)
53 {
54 fprintf(stderr, "test_multiheadattention_oom failed q=(%d %d) k=(%d %d) v=(%d %d) embed_dim=%d num_heads=%d kdim=%d vdim=%d attn_mask=%d\n", q.w, q.h, k.w, k.h, v.w, v.h, embed_dim, num_heads, kdim, vdim, attn_mask);
55 }
56
57 return ret;
58}
59
60static int test_multiheadattention_0()
61{
62 return 0
63 || test_multiheadattention_oom(RandomMat(62, 66), RandomMat(32, 66), RandomMat(20, 66), 62, 2, 0)
64 || test_multiheadattention_oom(RandomMat(26, 64), RandomMat(32, 64), RandomMat(18, 64), 26, 2, 1)
65 || test_multiheadattention_oom(RandomMat(12, 17), RandomMat(28, 127), RandomMat(32, 127), 12, 3, 0)
66 || test_multiheadattention_oom(RandomMat(12, 17), RandomMat(28, 32), RandomMat(11, 32), 12, 3, 1);
67}
68
69int main()
70{
71 SRAND(7767517);
72
73 return test_multiheadattention_0();
74}