-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbertencoder.h
77 lines (53 loc) · 1.86 KB
/
bertencoder.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#ifndef BERTENCODER_H
#define BERTENCODER_H
#include "bertbase.h"
#include "bertbasemodel.h"
#include <cstring>
#include <cmath>
#include <ggml.h>
#include <stddef.h>
#include <stdint.h>
#include <stdbool.h>
#include <vector>
#include <map>
#include <string>
namespace bert {
class BertClassifierModel : public AbstractBertModel {
public:
// embeddings weights
// transformer attentions
BertEncoderBert bert;
ggml_tensor *pool_w;
ggml_tensor *pool_b;
ggml_tensor *cls_w;
ggml_tensor *cls_b;
ggml_context *_ctx = NULL;
std::map<std::string, ggml_tensor *> tensors;
void set_ggml_context(ggml_context *ctx_) { _ctx = ctx_; }
ggml_context* get_ggml_context() { return _ctx; }
ggml_tensor* forward(BertHiParams *hparams, ggml_context *ctx0, bert_vocab_id *tokens, int N) {
BERT_ASSERT(cls_w != NULL);
BERT_ASSERT(cls_b != NULL);
struct ggml_tensor *inpL = bert.forward(hparams, ctx0, tokens, N);
struct ggml_tensor *cur = ggml_view_2d(ctx0, inpL, inpL->ne[0], inpL->ne[2], inpL->ne[1]*inpL->ne[0], 0);
print_ggml_tensor("outitem ggml_view_2d 1 ", cur);
cur = ggml_add(ctx0, ggml_mul_mat(ctx0, pool_w, cur), pool_b);
print_ggml_tensor("pool liner ", cur);
cur = ggml_tanh(ctx0, cur);
print_ggml_tensor("pool tanh ", cur);
cur = ggml_add(ctx0, ggml_mul_mat(ctx0, cls_w, cur), cls_b);
print_ggml_tensor("classifier liner ", cur);
cur = ggml_soft_max(ctx0, cur);
print_ggml_tensor("classifier softmax ", cur);
return cur;
}
~BertClassifierModel() {
if (_ctx != NULL) {
ggml_free(_ctx);
_ctx = NULL;
}
}
};
struct BertBaseCtx * bertencoder_load_from_file(const char * fname);
}
#endif // BERTENCODER_H