forked from ggerganov/ggml
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rnn_text_generation.cpp
331 lines (271 loc) · 10.3 KB
/
rnn_text_generation.cpp
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
#include <ggml.h>
#include <vector>
#include <string>
#include <cstdlib>
#include <iostream>
#include <fstream>
#include <algorithm>
#include <map>
#include <cstring>
#include <cmath>
using namespace std;
/**
Layer: my_model/embedding/embeddings:0 with shape (66, 256)
Layer: my_model/gru/gru_cell/kernel:0 with shape (256, 3072) ->read to 3072, 256 -> transpose 256, 3072
Layer: my_model/gru/gru_cell/recurrent_kernel:0 with shape (1024, 3072)
Layer: my_model/gru/gru_cell/bias:0 with shape (2, 3072)
Layer: my_model/dense/kernel:0 with shape (1024, 66)
Layer: my_model/dense/bias:0 with shape (66,)
**/
string vocab = "\t\n !$&',-.3:;?ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
void print_2d(ggml_tensor * ts){
for (int i1 = 0; i1 < ts->ne[1]; i1++){
for (int i0 = 0; i0 < ts->ne[0]; i0++){
if (i0 == 10) break;
cout << ggml_get_f32_1d(ts, i1*ts->ne[0] + i0) << " ";
}
cout << endl;
}
}
void print_shape(struct ggml_tensor * t, string name){
cout << name << " ";
for (int i = 0; i < t->n_dims; i++)
cout << t->ne[i] << " ";
cout << endl;
}
// for matrix a (n, m) -> slicing (a[start_index: end_index, :]
struct ggml_tensor * slice_2d(ggml_context * ctx, struct ggml_tensor * t, int start_index, int end_index){
struct ggml_tensor * mask = ggml_new_tensor_1d(ctx, GGML_TYPE_I32, end_index - start_index);
for (int i = 0; i < end_index - start_index; i++){
ggml_set_i32_1d(mask, i, (int32_t) (start_index + i));
}
struct ggml_tensor * result = ggml_get_rows(ctx, t, mask);
return result;
}
struct ggml_tensor * sigmoid_2d(ggml_context * ctx, struct ggml_tensor * x) {
// ggml has no native sigmoid, but silu(x) / x can be an approximation
x = ggml_div(ctx, ggml_silu(ctx, x), x);
return x;
}
int map_char_to_id(char c, map<char, int> char2id){
auto it = char2id.find(c);
if (it != char2id.end()){
return it->second;
}
// return the default value
return char2id['\t'];
}
vector<int> encode_text(string text, map<char, int> &char2id){
// input has shape [sequence_length, 1] as we are supporting batch of 1
vector<int> result;
for (int i = 0; i< text.length(); i++) result.push_back(map_char_to_id(text[i], char2id));
return result;
}
// max index on the first dimension
int argmax_1d(struct ggml_tensor * t){
float * probs = ggml_get_data_f32(t);
return max_element(probs, probs + t->ne[0]) - probs;
}
struct rnn_generator {
struct ggml_context * ctx;
struct ggml_tensor * embeddings;
struct ggml_tensor * cell_kernel;
struct ggml_tensor * cell_kernel_t;
struct ggml_tensor * cell_recurrent_kernel;
struct ggml_tensor * cell_recurrent_kernel_t;
struct ggml_tensor * cell_bias;
struct ggml_tensor * dense_kernel;
struct ggml_tensor * dense_kernel_t;
struct ggml_tensor * dense_bias;
};
void print_text(vector<int> ids){
for(int i = 0; i< ids.size(); i++) cout << vocab[ids[i]] ;
cout << endl;
cout << "--------" << endl;
}
struct rnn_generator load_model(){
struct ggml_init_params params = {
.mem_size = 64 * 1024 * 1024,
.mem_buffer = NULL,
.no_alloc = false
};
struct ggml_context *ctx = ggml_init(params);
struct rnn_generator model;
model.ctx = ctx;
model.embeddings = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, 256, 66);
model.cell_kernel = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, 3072, 256);
model.cell_recurrent_kernel = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, 3072, 1024);
model.cell_bias = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, 3072, 2);
model.dense_kernel = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, 66, 1024);
model.dense_bias = ggml_new_tensor_2d(model.ctx, GGML_TYPE_F32, 66, 1);
auto fin = ifstream("rnn_text_gen/gru.bin", ios::binary);
if (! fin) cout << "Error reading file" << endl;
int dummy;
// Read the embeddings
for (int i = 0; i < 3; i++) { fin.read((char*)&dummy, sizeof(dummy)); }
fin.read((char*)model.embeddings->data, 256*66*sizeof(float));
// Read the cell kernel
for (int i = 0; i < 3; i++) fin.read((char*)&dummy, sizeof(dummy));
fin.read((char*)model.cell_kernel->data, 3072*256*sizeof(float));
model.cell_kernel_t = ggml_cont(ctx, ggml_transpose(ctx, model.cell_kernel));
// Read the cell recurrent kernel, saved as python [1024, 3072]
for (int i = 0; i < 3; i++) { fin.read((char*)&dummy, sizeof(dummy)); }
fin.read((char*) model.cell_recurrent_kernel->data, 3072*1024*sizeof(float));
model.cell_recurrent_kernel_t = ggml_cont(ctx, ggml_transpose(ctx, model.cell_recurrent_kernel));
// Read the cell bias
for (int i = 0; i < 3; i++) { fin.read((char*)&dummy, sizeof(dummy)); }
fin.read((char*)model.cell_bias->data, 3072*2*sizeof(float));
// Read the dense kernel
for (int i = 0; i < 3; i++) { fin.read((char*)&dummy, sizeof(dummy)); }
fin.read((char*)model.dense_kernel->data, 66*1024*sizeof(float));
model.dense_kernel_t = ggml_cont(ctx, ggml_transpose(ctx, model.dense_kernel));
// Read the dense kernel
for (int i = 0; i < 2; i++){ fin.read((char*)&dummy, sizeof(dummy)); }
fin.read((char*)model.dense_bias->data, 66*1*sizeof(float));
struct ggml_cgraph gf = {};
ggml_set_param(ctx, model.cell_kernel);
ggml_set_param(ctx, model.cell_recurrent_kernel);
ggml_set_param(ctx, model.dense_kernel);
ggml_build_forward_expand(&gf, model.cell_kernel_t);
ggml_build_forward_expand(&gf, model.cell_recurrent_kernel_t);
ggml_build_forward_expand(&gf, model.dense_kernel_t);
ggml_graph_compute_with_ctx(ctx, &gf, 1);
print_2d(model.dense_kernel_t);
fin.close();
return model;
}
map<char, int> load_char2id(){
map<char, int> char2id;
for (int i = 0; i < vocab.length();i ++){
char2id[vocab[i]] = i;
}
return char2id;
}
struct cell_output {
struct ggml_tensor * output;
struct ggml_tensor * states;
struct ggml_tensor * z;
struct ggml_tensor * matrix_x;
};
struct cell_output gru_forward(
struct ggml_context * ctx0,
struct rnn_generator & model,
struct ggml_tensor * input_id,
struct ggml_tensor * states
){
struct cell_output cell;
int embedding_size = 256;
struct ggml_tensor * input_vector;
struct ggml_tensor * matrix_x, *output;
struct ggml_tensor * xz, *xr, *xh,* inner_matrix;
struct ggml_tensor *rz, *rr, *rh, *hh, *z, *r, *h;
input_vector = ggml_cont(ctx0, ggml_get_rows(ctx0, model.embeddings, input_id));
matrix_x = ggml_transpose(ctx0,
ggml_add(ctx0,
ggml_mul_mat(ctx0,
model.cell_kernel_t, //3072, 256 -> 256, 3072
input_vector
),
slice_2d(ctx0, model.cell_bias, 0, 1)
)
); // 3072, 1 -> 1, 3072
matrix_x->nb[0] = sizeof(float);
xz = slice_2d(ctx0, matrix_x, 0, 1024); // 1, 1024
xr = slice_2d(ctx0, matrix_x, 1024, 2048); // 1, 1024
xh = slice_2d(ctx0, matrix_x, 2048, 3072); // 1, 1024
inner_matrix = ggml_transpose(ctx0,
ggml_add(ctx0, // 3072, 1
ggml_mul_mat(ctx0, // 3072, 1
model.cell_recurrent_kernel_t, // 3072, 1024 ->
states // 1024, 3072 , 1024, 1
),
slice_2d(ctx0, model.cell_bias, 1, 2)
)
);
inner_matrix->nb[0] = sizeof(float);
rz = slice_2d(ctx0, inner_matrix, 0, 1024);
rr = slice_2d(ctx0, inner_matrix, 1024, 2048);
rh = slice_2d(ctx0, inner_matrix, 2048, 3072);
z = sigmoid_2d(ctx0, ggml_add(ctx0, xz, rz)); // (1, 1024)
r = sigmoid_2d(ctx0, ggml_add(ctx0, xr, rr));
rh = ggml_mul(ctx0, r, rh); // (1, 1024)
hh = ggml_tanh(ctx0, ggml_add(ctx0, xh, rh)); // (1, 1024)
states = ggml_transpose(ctx0, //(1024, 1)
ggml_add(ctx0,
ggml_mul(ctx0, z, ggml_transpose(ctx0, states)),
ggml_mul(ctx0,
ggml_sub(ctx0,
ggml_repeat(ctx0, ggml_new_f32(ctx0, 1.0f), z),
z
),
hh
)
)
);
output = ggml_add(ctx0,
ggml_mul_mat(ctx0,
model.dense_kernel_t,
states
),
model.dense_bias
);
cell.output = output;
cell.states = states;
return cell;
}
void inference(
struct rnn_generator & model,
vector<int> & encoded_input
){
// create the context holding the variables
struct ggml_init_params params = {
.mem_size = 1 * 1024 * 1024,
.mem_buffer = NULL,
.no_alloc = false
};
struct ggml_context * ctx0 = ggml_init(params);
int n_units = model.cell_kernel->ne[0] / 3;
int embedding_size = model.embeddings->ne[0];
// get the weights from the model
struct ggml_tensor * states = ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_units, 1); // (1024, 1)
struct ggml_tensor * input_id = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, 1);
struct cell_output output = gru_forward(ctx0, model, input_id, states);
ggml_set_param(ctx0, states);
ggml_set_param(ctx0, input_id);
struct ggml_cgraph gf = ggml_build_forward(output.output);
// feed the graph with input, get the output
int char_index;
for (int i = 0; i < 200; i++){
// for c in the prompt
if (i < encoded_input.size()){
// embedding lookup. this step is verified
char_index = encoded_input[i];
} else{
encoded_input.push_back(char_index);
print_text(encoded_input);
}
ggml_set_i32_1d(input_id, 0, char_index);
if (i != 0){
memcpy(
(float*) states->data,
(float*) output.states->data,
1024*sizeof(float)
);
}
ggml_graph_compute_with_ctx(ctx0, &gf, 1);
char_index = argmax_1d(output.output);
}
}
int main(){
// load the tokenizer map
map<char, int> char2id = load_char2id();
// load the model
struct rnn_generator my_model = load_model();
// run the inference code
char input_prompt[50];
cout << "type: " << endl;
cin.getline(input_prompt, 50);
auto encoded_input = encode_text(input_prompt, char2id);
cout << endl;
inference(my_model, encoded_input);
}