ggerganov commited on
Commit
7aad96d
·
1 Parent(s): 4c1552f

talk : talk with AI in the terminal

Browse files
.gitignore CHANGED
@@ -14,6 +14,7 @@ build-sanitize-thread/
14
  main
15
  stream
16
  command
 
17
  bench
18
  sync.sh
19
  libwhisper.so
 
14
  main
15
  stream
16
  command
17
+ talk
18
  bench
19
  sync.sh
20
  libwhisper.so
Makefile CHANGED
@@ -154,7 +154,7 @@ libwhisper.so: ggml.o whisper.o
154
  $(CXX) $(CXXFLAGS) -shared -o libwhisper.so ggml.o whisper.o $(LDFLAGS)
155
 
156
  clean:
157
- rm -f *.o main stream command bench libwhisper.a libwhisper.so
158
 
159
  #
160
  # Examples
@@ -172,6 +172,9 @@ stream: examples/stream/stream.cpp ggml.o whisper.o
172
  command: examples/command/command.cpp ggml.o whisper.o
173
  $(CXX) $(CXXFLAGS) examples/command/command.cpp ggml.o whisper.o -o command $(CC_SDL) $(LDFLAGS)
174
 
 
 
 
175
  bench: examples/bench/bench.cpp ggml.o whisper.o
176
  $(CXX) $(CXXFLAGS) examples/bench/bench.cpp ggml.o whisper.o -o bench $(LDFLAGS)
177
 
 
154
  $(CXX) $(CXXFLAGS) -shared -o libwhisper.so ggml.o whisper.o $(LDFLAGS)
155
 
156
  clean:
157
+ rm -f *.o main stream command talk bench libwhisper.a libwhisper.so
158
 
159
  #
160
  # Examples
 
172
  command: examples/command/command.cpp ggml.o whisper.o
173
  $(CXX) $(CXXFLAGS) examples/command/command.cpp ggml.o whisper.o -o command $(CC_SDL) $(LDFLAGS)
174
 
175
+ talk: examples/talk/talk.cpp examples/talk/gpt-2.cpp ggml.o whisper.o
176
+ $(CXX) $(CXXFLAGS) examples/talk/talk.cpp examples/talk/gpt-2.cpp ggml.o whisper.o -o talk $(CC_SDL) $(LDFLAGS)
177
+
178
  bench: examples/bench/bench.cpp ggml.o whisper.o
179
  $(CXX) $(CXXFLAGS) examples/bench/bench.cpp ggml.o whisper.o -o bench $(LDFLAGS)
180
 
README.md CHANGED
@@ -462,7 +462,7 @@ Some of the examples are even ported to run in the browser using WebAssembly. Ch
462
  | [bench](examples/bench) | | Benchmark the performance of Whisper on your machine |
463
  | [stream](examples/stream) | [stream.wasm](examples/stream.wasm) | Real-time transcription of raw microphone capture |
464
  | [command](examples/command) | [command.wasm](examples/command.wasm) | Basic voice assistant example for receiving voice commands from the mic |
465
- | | [talk.wasm](examples/talk.wasm) | Talk with a GPT-2 bot in your browser |
466
  | [whisper.objc](examples/whisper.objc) | | iOS mobile application using whisper.cpp |
467
  | [whisper.nvim](examples/whisper.nvim) | | Speech-to-text plugin for Neovim |
468
  | [generate-karaoke.sh](examples/generate-karaoke.sh) | | Helper script to easily [generate a karaoke video](https://youtu.be/uj7hVta4blM) of raw audio capture |
 
462
  | [bench](examples/bench) | | Benchmark the performance of Whisper on your machine |
463
  | [stream](examples/stream) | [stream.wasm](examples/stream.wasm) | Real-time transcription of raw microphone capture |
464
  | [command](examples/command) | [command.wasm](examples/command.wasm) | Basic voice assistant example for receiving voice commands from the mic |
465
+ | [talk](examples/talk) | [talk.wasm](examples/talk.wasm) | Talk with a GPT-2 bot |
466
  | [whisper.objc](examples/whisper.objc) | | iOS mobile application using whisper.cpp |
467
  | [whisper.nvim](examples/whisper.nvim) | | Speech-to-text plugin for Neovim |
468
  | [generate-karaoke.sh](examples/generate-karaoke.sh) | | Helper script to easily [generate a karaoke video](https://youtu.be/uj7hVta4blM) of raw audio capture |
examples/CMakeLists.txt CHANGED
@@ -28,4 +28,5 @@ else()
28
  add_subdirectory(stream)
29
  add_subdirectory(command)
30
  add_subdirectory(bench)
 
31
  endif()
 
28
  add_subdirectory(stream)
29
  add_subdirectory(command)
30
  add_subdirectory(bench)
31
+ add_subdirectory(talk)
32
  endif()
examples/command/command.cpp CHANGED
@@ -34,7 +34,6 @@ struct whisper_params {
34
 
35
  bool speed_up = false;
36
  bool translate = false;
37
- bool no_context = true;
38
  bool print_special = false;
39
  bool print_energy = false;
40
  bool no_timestamps = true;
 
34
 
35
  bool speed_up = false;
36
  bool translate = false;
 
37
  bool print_special = false;
38
  bool print_energy = false;
39
  bool no_timestamps = true;
examples/talk.wasm/README.md CHANGED
@@ -6,6 +6,8 @@ Talk with an Artificial Intelligence in your browser:
6
 
7
  Online demo: https://whisper.ggerganov.com/talk/
8
 
 
 
9
  ## How it works?
10
 
11
  This demo leverages 2 modern neural network models to create a high-quality voice chat directly in your browser:
 
6
 
7
  Online demo: https://whisper.ggerganov.com/talk/
8
 
9
+ Terminal version: [examples/talk](/examples/talk)
10
+
11
  ## How it works?
12
 
13
  This demo leverages 2 modern neural network models to create a high-quality voice chat directly in your browser:
examples/talk/.gitignore ADDED
@@ -0,0 +1 @@
 
 
1
+ eleven-labs.py
examples/talk/CMakeLists.txt ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ if (WHISPER_SUPPORT_SDL2)
2
+ # talk
3
+ set(TARGET talk)
4
+ add_executable(${TARGET} talk.cpp gpt-2.cpp)
5
+ target_include_directories(${TARGET} PRIVATE ${SDL2_INCLUDE_DIRS})
6
+ target_link_libraries(${TARGET} PRIVATE whisper ${SDL2_LIBRARIES} ${CMAKE_THREAD_LIBS_INIT})
7
+ endif ()
examples/talk/README.md ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # talk
2
+
3
+ Talk with an Artificial Intelligence in your terminal
4
+
5
+ [Demo Talk](https://user-images.githubusercontent.com/1991296/206805012-48e71cc2-588d-4745-8798-c1c70ea3b40d.mp4)
6
+
7
+ Web version: [examples/talk.wasm](/examples/talk.wasm)
8
+
9
+ ## Building
10
+
11
+ The `talk` tool depends on SDL2 library to capture audio from the microphone. You can build it like this:
12
+
13
+ ```bash
14
+ # Install SDL2 on Linux
15
+ sudo apt-get install libsdl2-dev
16
+
17
+ # Install SDL2 on Mac OS
18
+ brew install sdl2
19
+
20
+ # Build the "talk" executable
21
+ make talk
22
+
23
+ # Run it
24
+ ./talk -p Santa
25
+ ```
26
+
27
+ To run this, you will need a ggml GPT-2 model: [instructions](https://github.com/ggerganov/ggml/tree/master/examples/gpt-2#downloading-and-converting-the-original-models)
28
+
29
+ Alternatively, you can simply download the smallest ggml GPT-2 117M model (240 MB) like this:
30
+
31
+ ```
32
+ wget --quiet --show-progress -O models/ggml-gpt-2-117M.bin https://ggml.ggerganov.com/ggml-model-gpt-2-117M.bin
33
+ ```
examples/talk/gpt-2.cpp ADDED
@@ -0,0 +1,925 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "ggml.h"
2
+ #include "gpt-2.h"
3
+
4
+ #include <cmath>
5
+ #include <cstdio>
6
+ #include <cstring>
7
+ #include <fstream>
8
+ #include <map>
9
+ #include <string>
10
+ #include <thread>
11
+ #include <vector>
12
+ #include <regex>
13
+ #include <random>
14
+
15
+ /////////////////////// GPT-2 BEGIN /////////////////////////
16
+
17
+ //
18
+ // Vocab utils
19
+ //
20
+
21
+ std::vector<gpt_vocab::id> gpt_tokenize(const gpt_vocab & vocab, const std::string & text) {
22
+ std::vector<std::string> words;
23
+
24
+ // first split the text into words
25
+ {
26
+ std::string str = text;
27
+ std::string pat = R"('s|'t|'re|'ve|'m|'ll|'d| ?[[:alpha:]]+| ?[[:digit:]]+| ?[^\s[:alpha:][:digit:]]+|\s+(?!\S)|\s+)";
28
+
29
+ std::regex re(pat);
30
+ std::smatch m;
31
+
32
+ while (std::regex_search(str, m, re)) {
33
+ for (auto x : m) {
34
+ words.push_back(x);
35
+ }
36
+ str = m.suffix();
37
+ }
38
+ }
39
+
40
+ // find the longest tokens that form the words:
41
+ std::vector<gpt_vocab::id> tokens;
42
+ for (const auto & word : words) {
43
+ if (word.size() == 0) continue;
44
+
45
+ int i = 0;
46
+ int n = word.size();
47
+ while (i < n) {
48
+ int j = n;
49
+ while (j > i) {
50
+ auto it = vocab.token_to_id.find(word.substr(i, j-i));
51
+ if (it != vocab.token_to_id.end()) {
52
+ tokens.push_back(it->second);
53
+ i = j;
54
+ break;
55
+ }
56
+ --j;
57
+ }
58
+ if (i == n) {
59
+ break;
60
+ }
61
+ if (j == i) {
62
+ auto sub = word.substr(i, 1);
63
+ if (vocab.token_to_id.find(sub) != vocab.token_to_id.end()) {
64
+ tokens.push_back(vocab.token_to_id.at(sub));
65
+ } else {
66
+ fprintf(stderr, "%s: unknown token '%s'\n", __func__, sub.data());
67
+ }
68
+ ++i;
69
+ }
70
+ }
71
+ }
72
+
73
+ return tokens;
74
+ }
75
+
76
+ gpt_vocab::id gpt_sample_top_k_top_p(
77
+ const gpt_vocab & vocab,
78
+ const float * logits,
79
+ int top_k,
80
+ double top_p,
81
+ double temp,
82
+ std::mt19937 & rng) {
83
+ int n_logits = vocab.id_to_token.size();
84
+
85
+ std::vector<std::pair<double, gpt_vocab::id>> logits_id;
86
+ logits_id.reserve(n_logits);
87
+
88
+ for (int i = 0; i < n_logits; i++) {
89
+ logits_id.push_back(std::make_pair(logits[i], i));
90
+ }
91
+
92
+ // find the top K tokens
93
+ std::partial_sort(
94
+ logits_id.begin(),
95
+ logits_id.begin() + top_k, logits_id.end(),
96
+ [](const std::pair<double, gpt_vocab::id> & a, const std::pair<double, gpt_vocab::id> & b) {
97
+ return a.first > b.first;
98
+ });
99
+
100
+ logits_id.resize(top_k);
101
+
102
+ // normalize
103
+ {
104
+ double sum = 0.0f;
105
+ for (int i = 0; i < (int)logits_id.size(); i++) {
106
+ sum += logits_id[i].first;
107
+ }
108
+
109
+ sum = 1.0/sum;
110
+ for (int i = 0; i < (int)logits_id.size(); i++) {
111
+ logits_id[i].first *= sum;
112
+ }
113
+ }
114
+
115
+ if (top_p < 1.0f) {
116
+ {
117
+ double cumsum = 0.0f;
118
+ for (int i = 0; i < top_k; i++) {
119
+ cumsum += logits_id[i].first;
120
+ if (cumsum >= top_p) {
121
+ logits_id.resize(i+1);
122
+ break;
123
+ }
124
+ }
125
+ }
126
+
127
+ // normalize again
128
+ {
129
+ double sum = 0.0f;
130
+ for (int i = 0; i < (int)logits_id.size(); i++) {
131
+ sum += logits_id[i].first;
132
+ }
133
+
134
+ sum = 1.0/sum;
135
+ for (int i = 0; i < (int)logits_id.size(); i++) {
136
+ logits_id[i].first *= sum;
137
+ }
138
+ }
139
+ }
140
+
141
+ //printf("\n");
142
+ //for (int i = 0; i < (int)logits_id.size(); i++) {
143
+ // printf("%d: '%s' %f\n", i, vocab.id_to_token.at(logits_id[i].second).c_str(), logits_id[i].first);
144
+ //}
145
+ //exit(0);
146
+
147
+ // sample from the obtained distribution
148
+ std::vector<double> probs;
149
+ probs.reserve(logits_id.size());
150
+
151
+ for (int i = 0; i < (int) logits_id.size(); i++) {
152
+ probs.push_back(logits_id[i].first);
153
+ }
154
+
155
+ std::discrete_distribution<> dist(probs.begin(), probs.end());
156
+ int idx = dist(rng);
157
+
158
+ return logits_id[idx].second;
159
+ }
160
+
161
+ // default hparams (GPT-2 117M)
162
+ struct gpt2_hparams {
163
+ int32_t n_vocab = 50257;
164
+ int32_t n_ctx = 1024;
165
+ int32_t n_embd = 768;
166
+ int32_t n_head = 12;
167
+ int32_t n_layer = 12;
168
+ int32_t f16 = 1;
169
+ };
170
+
171
+ struct gpt2_layer {
172
+ // normalization
173
+ struct ggml_tensor * ln_1_g;
174
+ struct ggml_tensor * ln_1_b;
175
+
176
+ struct ggml_tensor * ln_2_g;
177
+ struct ggml_tensor * ln_2_b;
178
+
179
+ // attention
180
+ struct ggml_tensor * c_attn_attn_w;
181
+ struct ggml_tensor * c_attn_attn_b;
182
+
183
+ struct ggml_tensor * c_attn_proj_w;
184
+ struct ggml_tensor * c_attn_proj_b;
185
+
186
+ // mlp
187
+ struct ggml_tensor * c_mlp_fc_w;
188
+ struct ggml_tensor * c_mlp_fc_b;
189
+
190
+ struct ggml_tensor * c_mlp_proj_w_trans; // transposed for efficiency
191
+ struct ggml_tensor * c_mlp_proj_b;
192
+ };
193
+
194
+ struct gpt2_model {
195
+ gpt2_hparams hparams;
196
+
197
+ // normalization
198
+ struct ggml_tensor * ln_f_g;
199
+ struct ggml_tensor * ln_f_b;
200
+
201
+ struct ggml_tensor * wte; // position embedding
202
+ struct ggml_tensor * wpe; // token embedding
203
+
204
+ std::vector<gpt2_layer> layers;
205
+
206
+ // key + value memory
207
+ struct ggml_tensor * memory_k;
208
+ struct ggml_tensor * memory_v;
209
+
210
+ //
211
+ struct ggml_context * ctx;
212
+ std::map<std::string, struct ggml_tensor *> tensors;
213
+ };
214
+
215
+ // load the model's weights from a file
216
+ bool gpt2_model_load(const std::string & fname, gpt2_model & model, gpt_vocab & vocab) {
217
+ printf("%s: loading model from '%s'\n", __func__, fname.c_str());
218
+
219
+ auto fin = std::ifstream(fname, std::ios::binary);
220
+ if (!fin) {
221
+ fprintf(stderr, "%s: failed to open '%s'\n", __func__, fname.c_str());
222
+ return false;
223
+ }
224
+
225
+ // verify magic
226
+ {
227
+ uint32_t magic;
228
+ fin.read((char *) &magic, sizeof(magic));
229
+ if (magic != 0x67676d6c) {
230
+ fprintf(stderr, "%s: invalid model file '%s' (bad magic)\n", __func__, fname.c_str());
231
+ return false;
232
+ }
233
+ }
234
+
235
+ // load hparams
236
+ {
237
+ auto & hparams = model.hparams;
238
+
239
+ fin.read((char *) &hparams.n_vocab, sizeof(hparams.n_vocab));
240
+ fin.read((char *) &hparams.n_ctx, sizeof(hparams.n_ctx));
241
+ fin.read((char *) &hparams.n_embd, sizeof(hparams.n_embd));
242
+ fin.read((char *) &hparams.n_head, sizeof(hparams.n_head));
243
+ fin.read((char *) &hparams.n_layer, sizeof(hparams.n_layer));
244
+ fin.read((char *) &hparams.f16, sizeof(hparams.f16));
245
+
246
+ printf("%s: n_vocab = %d\n", __func__, hparams.n_vocab);
247
+ printf("%s: n_ctx = %d\n", __func__, hparams.n_ctx);
248
+ printf("%s: n_embd = %d\n", __func__, hparams.n_embd);
249
+ printf("%s: n_head = %d\n", __func__, hparams.n_head);
250
+ printf("%s: n_layer = %d\n", __func__, hparams.n_layer);
251
+ printf("%s: f16 = %d\n", __func__, hparams.f16);
252
+ }
253
+
254
+ // load vocab
255
+ {
256
+ int32_t n_vocab = 0;
257
+ fin.read((char *) &n_vocab, sizeof(n_vocab));
258
+
259
+ if (n_vocab != model.hparams.n_vocab) {
260
+ fprintf(stderr, "%s: invalid model file '%s' (bad vocab size %d != %d)\n",
261
+ __func__, fname.c_str(), n_vocab, model.hparams.n_vocab);
262
+ return false;
263
+ }
264
+
265
+ std::string word;
266
+ for (int i = 0; i < n_vocab; i++) {
267
+ uint32_t len;
268
+ fin.read((char *) &len, sizeof(len));
269
+
270
+ word.resize(len);
271
+ fin.read((char *) word.data(), len);
272
+
273
+ vocab.token_to_id[word] = i;
274
+ vocab.id_to_token[i] = word;
275
+ }
276
+ }
277
+
278
+ // for the big tensors, we have the option to store the data in 16-bit floats
279
+ // in order to save memory and also to speed up the computation
280
+ const ggml_type wtype = model.hparams.f16 ? GGML_TYPE_F16 : GGML_TYPE_F32;
281
+
282
+ auto & ctx = model.ctx;
283
+
284
+ size_t ctx_size = 0;
285
+
286
+ {
287
+ const auto & hparams = model.hparams;
288
+
289
+ const int n_embd = hparams.n_embd;
290
+ const int n_layer = hparams.n_layer;
291
+ const int n_ctx = hparams.n_ctx;
292
+ const int n_vocab = hparams.n_vocab;
293
+
294
+ ctx_size += n_embd*ggml_type_size(GGML_TYPE_F32); // ln_f_g
295
+ ctx_size += n_embd*ggml_type_size(GGML_TYPE_F32); // ln_f_b
296
+
297
+ ctx_size += n_vocab*n_embd*ggml_type_size(wtype); // wte
298
+ ctx_size += n_ctx*n_embd*ggml_type_size(GGML_TYPE_F32); // wpe
299
+
300
+ ctx_size += n_layer*(n_embd*ggml_type_size(GGML_TYPE_F32)); // ln_1_g
301
+ ctx_size += n_layer*(n_embd*ggml_type_size(GGML_TYPE_F32)); // ln_1_b
302
+
303
+ ctx_size += n_layer*(n_embd*ggml_type_size(GGML_TYPE_F32)); // ln_2_g
304
+ ctx_size += n_layer*(n_embd*ggml_type_size(GGML_TYPE_F32)); // ln_2_b
305
+
306
+ ctx_size += n_layer*(3*n_embd*n_embd*ggml_type_size(wtype)); // c_attn_attn_w
307
+ ctx_size += n_layer*( 3*n_embd*ggml_type_size(GGML_TYPE_F32)); // c_attn_attn_b
308
+
309
+ ctx_size += n_layer*(n_embd*n_embd*ggml_type_size(wtype)); // c_attn_proj_w
310
+ ctx_size += n_layer*( n_embd*ggml_type_size(GGML_TYPE_F32)); // c_attn_proj_b
311
+
312
+ ctx_size += n_layer*(4*n_embd*n_embd*ggml_type_size(wtype)); // c_mlp_fc_w
313
+ ctx_size += n_layer*( 4*n_embd*ggml_type_size(GGML_TYPE_F32)); // c_mlp_fc_b
314
+
315
+ ctx_size += n_layer*(4*n_embd*n_embd*ggml_type_size(wtype)); // c_mlp_proj_w
316
+ ctx_size += n_layer*( n_embd*ggml_type_size(GGML_TYPE_F32)); // c_mlp_proj_b
317
+
318
+ ctx_size += n_ctx*n_layer*n_embd*ggml_type_size(GGML_TYPE_F32); // memory_k
319
+ ctx_size += n_ctx*n_layer*n_embd*ggml_type_size(GGML_TYPE_F32); // memory_v
320
+
321
+ ctx_size += (6 + 12*n_layer)*256; // object overhead
322
+
323
+ printf("%s: ggml ctx size = %6.2f MB\n", __func__, ctx_size/(1024.0*1024.0));
324
+ }
325
+
326
+ // create the ggml context
327
+ {
328
+ struct ggml_init_params params = {
329
+ .mem_size = ctx_size,
330
+ .mem_buffer = NULL,
331
+ };
332
+
333
+ model.ctx = ggml_init(params);
334
+ if (!model.ctx) {
335
+ fprintf(stderr, "%s: ggml_init() failed\n", __func__);
336
+ return false;
337
+ }
338
+ }
339
+
340
+ // prepare memory for the weights
341
+ {
342
+ const auto & hparams = model.hparams;
343
+
344
+ const int n_embd = hparams.n_embd;
345
+ const int n_layer = hparams.n_layer;
346
+ const int n_ctx = hparams.n_ctx;
347
+ const int n_vocab = hparams.n_vocab;
348
+
349
+ model.layers.resize(n_layer);
350
+
351
+ model.ln_f_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
352
+ model.ln_f_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
353
+
354
+ model.wte = ggml_new_tensor_2d(ctx, wtype, n_embd, n_vocab);
355
+ model.wpe = ggml_new_tensor_2d(ctx, GGML_TYPE_F32, n_embd, n_ctx);
356
+
357
+ // map by name
358
+ model.tensors["model/ln_f/g"] = model.ln_f_g;
359
+ model.tensors["model/ln_f/b"] = model.ln_f_b;
360
+
361
+ model.tensors["model/wte"] = model.wte;
362
+ model.tensors["model/wpe"] = model.wpe;
363
+
364
+ for (int i = 0; i < n_layer; ++i) {
365
+ auto & layer = model.layers[i];
366
+
367
+ layer.ln_1_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
368
+ layer.ln_1_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
369
+
370
+ layer.ln_2_g = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
371
+ layer.ln_2_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
372
+
373
+ layer.c_attn_attn_w = ggml_new_tensor_2d(ctx, wtype, 3*n_embd, n_embd);
374
+ layer.c_attn_attn_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 3*n_embd);
375
+
376
+ layer.c_attn_proj_w = ggml_new_tensor_2d(ctx, wtype, n_embd, n_embd);
377
+ layer.c_attn_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
378
+
379
+ layer.c_mlp_fc_w = ggml_new_tensor_2d(ctx, wtype, 4*n_embd, n_embd);
380
+ layer.c_mlp_fc_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, 4*n_embd);
381
+
382
+ layer.c_mlp_proj_w_trans = ggml_new_tensor_2d(ctx, wtype, 4*n_embd, n_embd);
383
+ layer.c_mlp_proj_b = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_embd);
384
+
385
+ // map by name
386
+ model.tensors["model/h" + std::to_string(i) + "/ln_1/g"] = layer.ln_1_g;
387
+ model.tensors["model/h" + std::to_string(i) + "/ln_1/b"] = layer.ln_1_b;
388
+
389
+ model.tensors["model/h" + std::to_string(i) + "/ln_2/g"] = layer.ln_2_g;
390
+ model.tensors["model/h" + std::to_string(i) + "/ln_2/b"] = layer.ln_2_b;
391
+
392
+ model.tensors["model/h" + std::to_string(i) + "/attn/c_attn/w"] = layer.c_attn_attn_w;
393
+ model.tensors["model/h" + std::to_string(i) + "/attn/c_attn/b"] = layer.c_attn_attn_b;
394
+
395
+ model.tensors["model/h" + std::to_string(i) + "/attn/c_proj/w"] = layer.c_attn_proj_w;
396
+ model.tensors["model/h" + std::to_string(i) + "/attn/c_proj/b"] = layer.c_attn_proj_b;
397
+
398
+ model.tensors["model/h" + std::to_string(i) + "/mlp/c_fc/w"] = layer.c_mlp_fc_w;
399
+ model.tensors["model/h" + std::to_string(i) + "/mlp/c_fc/b"] = layer.c_mlp_fc_b;
400
+
401
+ model.tensors["model/h" + std::to_string(i) + "/mlp/c_proj/w"] = layer.c_mlp_proj_w_trans;
402
+ model.tensors["model/h" + std::to_string(i) + "/mlp/c_proj/b"] = layer.c_mlp_proj_b;
403
+ }
404
+ }
405
+
406
+ // key + value memory
407
+ {
408
+ const auto & hparams = model.hparams;
409
+
410
+ const int n_embd = hparams.n_embd;
411
+ const int n_layer = hparams.n_layer;
412
+ const int n_ctx = hparams.n_ctx;
413
+
414
+ const int n_mem = n_layer*n_ctx;
415
+ const int n_elements = n_embd*n_mem;
416
+
417
+ model.memory_k = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_elements);
418
+ model.memory_v = ggml_new_tensor_1d(ctx, GGML_TYPE_F32, n_elements);
419
+
420
+ const size_t memory_size = ggml_nbytes(model.memory_k) + ggml_nbytes(model.memory_v);
421
+
422
+ printf("%s: memory size = %8.2f MB, n_mem = %d\n", __func__, memory_size/1024.0/1024.0, n_mem);
423
+ }
424
+
425
+ // load weights
426
+ {
427
+ size_t total_size = 0;
428
+
429
+ while (true) {
430
+ int32_t n_dims;
431
+ int32_t length;
432
+ int32_t ftype;
433
+
434
+ fin.read(reinterpret_cast<char *>(&n_dims), sizeof(n_dims));
435
+ fin.read(reinterpret_cast<char *>(&length), sizeof(length));
436
+ fin.read(reinterpret_cast<char *>(&ftype), sizeof(ftype));
437
+
438
+ if (fin.eof()) {
439
+ break;
440
+ }
441
+
442
+ int32_t nelements = 1;
443
+ int32_t ne[2] = { 1, 1 };
444
+ for (int i = 0; i < n_dims; ++i) {
445
+ fin.read(reinterpret_cast<char *>(&ne[i]), sizeof(ne[i]));
446
+ nelements *= ne[i];
447
+ }
448
+
449
+ std::string name(length, 0);
450
+ fin.read(&name[0], length);
451
+
452
+ if (model.tensors.find(name.data()) == model.tensors.end()) {
453
+ fprintf(stderr, "%s: unknown tensor '%s' in model file\n", __func__, name.data());
454
+ return false;
455
+ }
456
+
457
+ auto tensor = model.tensors[name.data()];
458
+ if (ggml_nelements(tensor) != nelements) {
459
+ fprintf(stderr, "%s: tensor '%s' has wrong size in model file\n", __func__, name.data());
460
+ return false;
461
+ }
462
+
463
+ if (tensor->ne[0] != ne[0] || tensor->ne[1] != ne[1]) {
464
+ fprintf(stderr, "%s: tensor '%s' has wrong shape in model file: got [%d, %d], expected [%d, %d]\n",
465
+ __func__, name.data(), tensor->ne[0], tensor->ne[1], ne[0], ne[1]);
466
+ return false;
467
+ }
468
+
469
+ const size_t bpe = (ftype == 0) ? sizeof(float) : sizeof(ggml_fp16_t);
470
+
471
+ if (nelements*bpe != ggml_nbytes(tensor)) {
472
+ fprintf(stderr, "%s: tensor '%s' has wrong size in model file: got %zu, expected %zu\n",
473
+ __func__, name.data(), ggml_nbytes(tensor), nelements*bpe);
474
+ return false;
475
+ }
476
+
477
+ fin.read(reinterpret_cast<char *>(tensor->data), ggml_nbytes(tensor));
478
+
479
+ //printf("%24s - [%5d, %5d], type = %6s, %6.2f MB\n", name.data(), ne[0], ne[1], ftype == 0 ? "float" : "f16", ggml_nbytes(tensor)/1024.0/1024.0);
480
+ total_size += ggml_nbytes(tensor);
481
+ }
482
+
483
+ printf("%s: model size = %8.2f MB\n", __func__, total_size/1024.0/1024.0);
484
+ }
485
+
486
+ fin.close();
487
+
488
+ return true;
489
+ }
490
+
491
+ // evaluate the transformer
492
+ //
493
+ // - model: the model
494
+ // - n_threads: number of threads to use
495
+ // - n_past: the context size so far
496
+ // - embd_inp: the embeddings of the tokens in the context
497
+ // - embd_w: the predicted probabilities of the next token
498
+ //
499
+ bool gpt2_eval(
500
+ const gpt2_model & model,
501
+ const int n_threads,
502
+ const int n_past,
503
+ const std::vector<gpt_vocab::id> & embd_inp,
504
+ std::vector<float> & embd_w,
505
+ size_t & mem_per_token) {
506
+ const int N = embd_inp.size();
507
+
508
+ const auto & hparams = model.hparams;
509
+
510
+ const int n_embd = hparams.n_embd;
511
+ const int n_layer = hparams.n_layer;
512
+ const int n_ctx = hparams.n_ctx;
513
+ const int n_head = hparams.n_head;
514
+ const int n_vocab = hparams.n_vocab;
515
+
516
+ static size_t buf_size = 5640ull*1024*1024;
517
+ static void * buf = malloc(buf_size);
518
+
519
+ if (mem_per_token > 0 && mem_per_token*N > buf_size) {
520
+ const size_t buf_size_new = 1.1*(mem_per_token*N); // add 10% to account for ggml object overhead
521
+ printf("\n%s: reallocating buffer from %zu to %zu bytes\n", __func__, buf_size, buf_size_new);
522
+
523
+ // reallocate
524
+ buf_size = buf_size_new;
525
+ buf = realloc(buf, buf_size);
526
+ if (buf == nullptr) {
527
+ fprintf(stderr, "%s: failed to allocate %zu bytes\n", __func__, buf_size);
528
+ return false;
529
+ }
530
+ }
531
+
532
+ struct ggml_init_params params = {
533
+ .mem_size = buf_size,
534
+ .mem_buffer = buf,
535
+ };
536
+
537
+ struct ggml_context * ctx0 = ggml_init(params);
538
+ struct ggml_cgraph gf = { .n_threads = n_threads };
539
+
540
+ struct ggml_tensor * embd = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
541
+ memcpy(embd->data, embd_inp.data(), N*ggml_element_size(embd));
542
+
543
+ struct ggml_tensor * position = ggml_new_tensor_1d(ctx0, GGML_TYPE_I32, N);
544
+ for (int i = 0; i < N; ++i) {
545
+ ((int32_t *) position->data)[i] = n_past + i;
546
+ }
547
+
548
+ // wte + wpe
549
+ struct ggml_tensor * inpL =
550
+ ggml_add(ctx0,
551
+ ggml_get_rows(ctx0, model.wte, embd),
552
+ ggml_get_rows(ctx0, model.wpe, position));
553
+
554
+ for (int il = 0; il < n_layer; ++il) {
555
+ struct ggml_tensor * cur;
556
+
557
+ // norm
558
+ {
559
+ // [ 768, N]
560
+ cur = ggml_norm(ctx0, inpL);
561
+
562
+ // cur = ln_1_g*cur + ln_1_b
563
+ // [ 768, N]
564
+ cur = ggml_add(ctx0,
565
+ ggml_mul(ctx0,
566
+ ggml_repeat(ctx0, model.layers[il].ln_1_g, cur),
567
+ cur),
568
+ ggml_repeat(ctx0, model.layers[il].ln_1_b, cur));
569
+ }
570
+
571
+ // attn
572
+ // [2304, 768] - model.layers[il].c_attn_attn_w
573
+ // [2304, 1] - model.layers[il].c_attn_attn_b
574
+ // [ 768, N] - cur (in)
575
+ // [2304, N] - cur (out)
576
+ //
577
+ // cur = attn_w*cur + attn_b
578
+ // [2304, N]
579
+ {
580
+ cur = ggml_mul_mat(ctx0,
581
+ ggml_transpose(ctx0, model.layers[il].c_attn_attn_w),
582
+ cur);
583
+
584
+ cur = ggml_add(ctx0,
585
+ ggml_repeat(ctx0, model.layers[il].c_attn_attn_b, cur),
586
+ cur);
587
+ }
588
+
589
+ // self-attention
590
+ {
591
+ struct ggml_tensor * Qcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 0*sizeof(float)*n_embd);
592
+ struct ggml_tensor * Kcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 1*sizeof(float)*n_embd);
593
+ struct ggml_tensor * Vcur = ggml_view_2d(ctx0, cur, n_embd, N, cur->nb[1], 2*sizeof(float)*n_embd);
594
+
595
+ // store key and value to memory
596
+ if (N >= 1) {
597
+ struct ggml_tensor * k = ggml_view_1d(ctx0, model.memory_k, N*n_embd, (ggml_element_size(model.memory_k)*n_embd)*(il*n_ctx + n_past));
598
+ struct ggml_tensor * v = ggml_view_1d(ctx0, model.memory_v, N*n_embd, (ggml_element_size(model.memory_v)*n_embd)*(il*n_ctx + n_past));
599
+
600
+ ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Kcur, k));
601
+ ggml_build_forward_expand(&gf, ggml_cpy(ctx0, Vcur, v));
602
+ }
603
+
604
+ // Q = Qcur.contiguous().view(n_embd/n_head, n_head, N).permute(0, 2, 1, 3)
605
+ // [64, N, 12]
606
+ struct ggml_tensor * Q =
607
+ ggml_permute(ctx0,
608
+ ggml_cpy(ctx0,
609
+ Qcur,
610
+ ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_embd/n_head, n_head, N)),
611
+ 0, 2, 1, 3);
612
+
613
+ // K = Kmem.view(n_embd/n_head, n_head, n_past + N).permute(0, 2, 1, 3)
614
+ // [64, n_past + N, 12]
615
+ struct ggml_tensor * K =
616
+ ggml_permute(ctx0,
617
+ ggml_reshape_3d(ctx0,
618
+ ggml_view_1d(ctx0, model.memory_k, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_k)*n_embd),
619
+ n_embd/n_head, n_head, n_past + N),
620
+ 0, 2, 1, 3);
621
+
622
+ // GG: flash attention
623
+ //struct ggml_tensor * V =
624
+ // ggml_cpy(ctx0,
625
+ // ggml_permute(ctx0,
626
+ // ggml_reshape_3d(ctx0,
627
+ // ggml_view_1d(ctx0, model.memory_v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_v)*n_embd),
628
+ // n_embd/n_head, n_head, n_past + N),
629
+ // 1, 2, 0, 3),
630
+ // ggml_new_tensor_3d(ctx0, GGML_TYPE_F32, n_past + N, n_embd/n_head, n_head));
631
+
632
+ //struct ggml_tensor * KQV = ggml_flash_attn(ctx0, Q, K, V, true);
633
+
634
+ // K * Q
635
+ // [n_past + N, N, 12]
636
+ struct ggml_tensor * KQ = ggml_mul_mat(ctx0, K, Q);
637
+
638
+ // KQ_scaled = KQ / sqrt(n_embd/n_head)
639
+ // [n_past + N, N, 12]
640
+ struct ggml_tensor * KQ_scaled =
641
+ ggml_scale(ctx0,
642
+ KQ,
643
+ ggml_new_f32(ctx0, 1.0f/sqrt(float(n_embd)/n_head))
644
+ );
645
+
646
+ // KQ_masked = mask_past(KQ_scaled)
647
+ // [n_past + N, N, 12]
648
+ struct ggml_tensor * KQ_masked = ggml_diag_mask_inf(ctx0, KQ_scaled, n_past);
649
+
650
+ // KQ = soft_max(KQ_masked)
651
+ // [n_past + N, N, 12]
652
+ struct ggml_tensor * KQ_soft_max = ggml_soft_max(ctx0, KQ_masked);
653
+
654
+ // V_trans = Vmem.view(n_embd/n_head, n_head, n_past + N).permute(1, 2, 0, 3).contiguous()
655
+ // [n_past + N, 64, 12]
656
+ struct ggml_tensor * V_trans =
657
+ ggml_permute(ctx0,
658
+ ggml_reshape_3d(ctx0,
659
+ ggml_view_1d(ctx0, model.memory_v, (n_past + N)*n_embd, il*n_ctx*ggml_element_size(model.memory_v)*n_embd),
660
+ n_embd/n_head, n_head, n_past + N),
661
+ 1, 2, 0, 3);
662
+
663
+ // KQV = transpose(V) * KQ_soft_max
664
+ // [64, N, 12]
665
+ struct ggml_tensor * KQV = ggml_mul_mat(ctx0, V_trans, KQ_soft_max);
666
+
667
+ // KQV_merged = KQV.permute(0, 2, 1, 3)
668
+ // [64, 12, N]
669
+ struct ggml_tensor * KQV_merged = ggml_permute(ctx0, KQV, 0, 2, 1, 3);
670
+
671
+ // cur = KQV_merged.contiguous().view(n_embd, N)
672
+ // [768, N]
673
+ cur = ggml_cpy(ctx0,
674
+ KQV_merged,
675
+ ggml_new_tensor_2d(ctx0, GGML_TYPE_F32, n_embd, N));
676
+ }
677
+
678
+ // projection
679
+ // [ 768, 768] - model.layers[il].c_attn_proj_w
680
+ // [ 768, 1] - model.layers[il].c_attn_proj_b
681
+ // [ 768, N] - cur (in)
682
+ // [ 768, N] - cur (out)
683
+ //
684
+ // cur = proj_w*cur + proj_b
685
+ // [768, N]
686
+ {
687
+ cur = ggml_mul_mat(ctx0,
688
+ ggml_transpose(ctx0, model.layers[il].c_attn_proj_w),
689
+ cur);
690
+
691
+ cur = ggml_add(ctx0,
692
+ ggml_repeat(ctx0, model.layers[il].c_attn_proj_b, cur),
693
+ cur);
694
+ }
695
+
696
+ // add the input
697
+ cur = ggml_add(ctx0, cur, inpL);
698
+
699
+ struct ggml_tensor * inpFF = cur;
700
+
701
+ // feed-forward network
702
+ {
703
+ // norm
704
+ {
705
+ cur = ggml_norm(ctx0, inpFF);
706
+
707
+ // cur = ln_2_g*cur + ln_2_b
708
+ // [ 768, N]
709
+ cur = ggml_add(ctx0,
710
+ ggml_mul(ctx0,
711
+ ggml_repeat(ctx0, model.layers[il].ln_2_g, cur),
712
+ cur),
713
+ ggml_repeat(ctx0, model.layers[il].ln_2_b, cur));
714
+ }
715
+
716
+ // fully connected
717
+ // [3072, 768] - model.layers[il].c_mlp_fc_w
718
+ // [3072, 1] - model.layers[il].c_mlp_fc_b
719
+ // [ 768, N] - cur (in)
720
+ // [3072, N] - cur (out)
721
+ //
722
+ // cur = fc_w*cur + fc_b
723
+ // [3072, N]
724
+ cur = ggml_mul_mat(ctx0,
725
+ ggml_transpose(ctx0, model.layers[il].c_mlp_fc_w),
726
+ cur);
727
+
728
+ cur = ggml_add(ctx0,
729
+ ggml_repeat(ctx0, model.layers[il].c_mlp_fc_b, cur),
730
+ cur);
731
+
732
+ // GELU activation
733
+ // [3072, N]
734
+ cur = ggml_gelu(ctx0, cur);
735
+
736
+ // projection
737
+ // [ 768, 3072] - model.layers[il].c_mlp_proj_w
738
+ // [ 768, 1] - model.layers[il].c_mlp_proj_b
739
+ // [3072, N] - cur (in)
740
+ // [ 768, N] - cur (out)
741
+ //
742
+ // cur = proj_w*cur + proj_b
743
+ // [768, N]
744
+ cur = ggml_mul_mat(ctx0,
745
+ model.layers[il].c_mlp_proj_w_trans,
746
+ cur);
747
+
748
+ cur = ggml_add(ctx0,
749
+ ggml_repeat(ctx0, model.layers[il].c_mlp_proj_b, cur),
750
+ cur);
751
+ }
752
+
753
+ // input for next layer
754
+ inpL = ggml_add(ctx0, cur, inpFF);
755
+ }
756
+
757
+ // norm
758
+ {
759
+ // [ 768, N]
760
+ inpL = ggml_norm(ctx0, inpL);
761
+
762
+ // inpL = ln_f_g*inpL + ln_f_b
763
+ // [ 768, N]
764
+ inpL = ggml_add(ctx0,
765
+ ggml_mul(ctx0,
766
+ ggml_repeat(ctx0, model.ln_f_g, inpL),
767
+ inpL),
768
+ ggml_repeat(ctx0, model.ln_f_b, inpL));
769
+ }
770
+
771
+ // inpL = WTE * inpL
772
+ // [ 768, 50257] - model.wte
773
+ // [ 768, N] - inpL
774
+ inpL = ggml_mul_mat(ctx0, model.wte, inpL);
775
+
776
+ // logits -> probs
777
+ inpL = ggml_soft_max(ctx0, inpL);
778
+
779
+ // run the computation
780
+ ggml_build_forward_expand(&gf, inpL);
781
+ ggml_graph_compute (ctx0, &gf);
782
+
783
+ //if (n_past%100 == 0) {
784
+ // ggml_graph_print (&gf);
785
+ // ggml_graph_dump_dot(&gf, NULL, "gpt-2.dot");
786
+ //}
787
+
788
+ //embd_w.resize(n_vocab*N);
789
+ //memcpy(embd_w.data(), ggml_get_data(inpL), sizeof(float)*n_vocab*N);
790
+
791
+ // return result for just the last token
792
+ embd_w.resize(n_vocab);
793
+ memcpy(embd_w.data(), (float *) ggml_get_data(inpL) + (n_vocab*(N-1)), sizeof(float)*n_vocab);
794
+
795
+ if (mem_per_token == 0) {
796
+ mem_per_token = ggml_used_mem(ctx0)/N;
797
+ }
798
+ //printf("used_mem = %zu\n", ggml_used_mem(ctx0));
799
+
800
+ ggml_free(ctx0);
801
+
802
+ return true;
803
+ }
804
+
805
+ /////////////////////////////// GPT-2 END ////////////////////////////////
806
+
807
+ constexpr int N_THREAD = 8;
808
+
809
+ struct gpt2_context {
810
+ std::string prompt_base = R"(Hello, how are you?
811
+ I'm fine, thanks. How are you?
812
+ Thanks, I'm fine too. What are you doing?
813
+ I'm just sitting here.
814
+ It's a lovely day, isn't it?
815
+ Yes, it is. I love the weather this time of year.
816
+ I wish it would rain a little bit.
817
+ Me too.
818
+ )";
819
+
820
+ std::mt19937 rng;
821
+
822
+ gpt_vocab vocab;
823
+ gpt2_model model;
824
+
825
+ int32_t n_threads = std::min(N_THREAD, (int) std::thread::hardware_concurrency());
826
+
827
+ // sampling parameters
828
+ int32_t top_k = 20;
829
+ float top_p = 0.98f;
830
+ float temp = 1.0f;
831
+ };
832
+
833
+ struct gpt2_context * gpt2_init(const char * path_model) {
834
+ gpt2_context * ctx = new gpt2_context;
835
+
836
+ ctx->rng = std::mt19937(time(NULL));
837
+
838
+ // load the model
839
+ {
840
+ const int64_t t_start_us = ggml_time_us();
841
+
842
+ if (!gpt2_model_load(path_model, ctx->model, ctx->vocab)) {
843
+ fprintf(stderr, "%s: failed to load model from '%s'\n", __func__, "gpt-2.bin");
844
+ return nullptr;
845
+ }
846
+
847
+ const int64_t t_load_us = ggml_time_us() - t_start_us;
848
+
849
+ printf("gpt-2: model loaded in %d ms\n", (int) (t_load_us/1000));
850
+ }
851
+
852
+ return ctx;
853
+ }
854
+
855
+ void gpt2_free(struct gpt2_context * ctx) {
856
+ delete ctx;
857
+ }
858
+
859
+ const char * gpt2_get_prompt(struct gpt2_context * ctx) {
860
+ return ctx->prompt_base.c_str();
861
+ }
862
+
863
+ void gpt2_set_prompt(struct gpt2_context * ctx, const char * prompt) {
864
+ ctx->prompt_base = prompt;
865
+ }
866
+
867
+ std::vector<gpt_vocab::id> gpt2_tokenize(const gpt2_context * ctx, const char * text) {
868
+ return ::gpt_tokenize(ctx->vocab, text);
869
+ }
870
+
871
+ std::string gpt2_gen_text(gpt2_context * ctx, const char * text, int max_tokens) {
872
+ int n_past = 0;
873
+
874
+ std::vector<float> embd_w;
875
+
876
+ // tokenize the prompt
877
+ std::vector<gpt_vocab::id> embd_inp = ::gpt2_tokenize(ctx, text);
878
+
879
+ int n_predict = std::min(max_tokens, ctx->model.hparams.n_ctx - (int) embd_inp.size());
880
+
881
+ std::vector<gpt_vocab::id> embd = embd_inp;
882
+
883
+ size_t mem_per_token = 3000000;
884
+
885
+ std::string result;
886
+
887
+ for (int i = embd.size(); i < embd_inp.size() + n_predict; i++) {
888
+ // predict
889
+ if (embd.size() > 0) {
890
+ if (!gpt2_eval(ctx->model, ctx->n_threads, n_past, embd, embd_w, mem_per_token)) {
891
+ printf("gpt-2: failed to generate text\n");
892
+ return "";
893
+ }
894
+ }
895
+
896
+ n_past += embd.size();
897
+ embd.clear();
898
+
899
+ {
900
+ // sample next token
901
+ const int top_k = ctx->top_k;
902
+ const float top_p = ctx->top_p;
903
+ const float temp = ctx->temp;
904
+
905
+ const int n_vocab = ctx->model.hparams.n_vocab;
906
+
907
+ const gpt_vocab::id id = gpt_sample_top_k_top_p(ctx->vocab, embd_w.data() + (embd_w.size() - n_vocab), top_k, top_p, temp, ctx->rng);
908
+
909
+ // add it to the context
910
+ embd.push_back(id);
911
+ }
912
+
913
+ result += ctx->vocab.id_to_token[embd[0]];
914
+
915
+ // end of text token
916
+ if (embd.back() == 50256 ||
917
+ ctx->vocab.id_to_token[embd.back()] == "." ||
918
+ ctx->vocab.id_to_token[embd.back()] == "!" ||
919
+ ctx->vocab.id_to_token[embd.back()] == "?") {
920
+ break;
921
+ }
922
+ }
923
+
924
+ return result;
925
+ }
examples/talk/gpt-2.h ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #pragma once
2
+
3
+ // TODO: Change to C-style API and move to ./examples for easy reuse.
4
+
5
+ #include <vector>
6
+ #include <map>
7
+ #include <string>
8
+
9
+ struct gpt_vocab {
10
+ using id = int32_t;
11
+ using token = std::string;
12
+
13
+ std::map<token, id> token_to_id;
14
+ std::map<id, token> id_to_token;
15
+ };
16
+
17
+ struct gpt2_context;
18
+
19
+ struct gpt2_context * gpt2_init(const char * path_model);
20
+ void gpt2_free(struct gpt2_context * ctx);
21
+
22
+ const char * gpt2_get_prompt(struct gpt2_context * ctx);
23
+ void gpt2_set_prompt(struct gpt2_context * ctx, const char * prompt);
24
+
25
+ std::vector<gpt_vocab::id> gpt2_tokenize(const gpt2_context * ctx, const char * text);
26
+
27
+ std::string gpt2_gen_text(gpt2_context * ctx, const char * text, int max_tokens);
examples/talk/speak.sh ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+
3
+ # Usage:
4
+ # speak.sh <voice_id> <text-to-speak>
5
+
6
+ # espeak
7
+ # Mac OS: brew install espeak
8
+ # Linux: apt-get install espeak
9
+ #
10
+ espeak -v en-us+m$1 -s 175 -p 50 -a 200 -g 5 -k 5 "$2"
11
+
12
+ # Eleven Labs
13
+ #
14
+ #wd=$(dirname $0)
15
+ #script=$wd/eleven-labs.py
16
+ #python3 $script $1 "$2"
17
+ #ffplay -autoexit -nodisp -loglevel quiet -hide_banner -i ./audio.mp3
examples/talk/talk.cpp ADDED
@@ -0,0 +1,733 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Talk with AI
2
+ //
3
+
4
+ #include "whisper.h"
5
+ #include "gpt-2.h"
6
+
7
+ #include <SDL.h>
8
+ #include <SDL_audio.h>
9
+
10
+ #include <cassert>
11
+ #include <cstdio>
12
+ #include <fstream>
13
+ #include <mutex>
14
+ #include <regex>
15
+ #include <string>
16
+ #include <thread>
17
+ #include <vector>
18
+ #include <regex>
19
+
20
+ // command-line parameters
21
+ struct whisper_params {
22
+ int32_t n_threads = std::min(4, (int32_t) std::thread::hardware_concurrency());
23
+ int32_t voice_ms = 10000;
24
+ int32_t capture_id = -1;
25
+ int32_t max_tokens = 32;
26
+ int32_t audio_ctx = 0;
27
+
28
+ float vad_thold = 0.6f;
29
+ float freq_thold = 100.0f;
30
+
31
+ bool speed_up = false;
32
+ bool translate = false;
33
+ bool print_special = false;
34
+ bool print_energy = false;
35
+ bool no_timestamps = true;
36
+
37
+ std::string person = "Santa";
38
+ std::string language = "en";
39
+ std::string model_wsp = "models/ggml-base.en.bin";
40
+ std::string model_gpt = "models/ggml-gpt-2-117M.bin";
41
+ std::string speak = "./examples/talk/speak.sh";
42
+ std::string fname_out = "";
43
+ };
44
+
45
+ void whisper_print_usage(int argc, char ** argv, const whisper_params & params);
46
+
47
+ bool whisper_params_parse(int argc, char ** argv, whisper_params & params) {
48
+ for (int i = 1; i < argc; i++) {
49
+ std::string arg = argv[i];
50
+
51
+ if (arg == "-h" || arg == "--help") {
52
+ whisper_print_usage(argc, argv, params);
53
+ exit(0);
54
+ }
55
+ else if (arg == "-t" || arg == "--threads") { params.n_threads = std::stoi(argv[++i]); }
56
+ else if (arg == "-vms" || arg == "--voice-ms") { params.voice_ms = std::stoi(argv[++i]); }
57
+ else if (arg == "-c" || arg == "--capture") { params.capture_id = std::stoi(argv[++i]); }
58
+ else if (arg == "-mt" || arg == "--max-tokens") { params.max_tokens = std::stoi(argv[++i]); }
59
+ else if (arg == "-ac" || arg == "--audio-ctx") { params.audio_ctx = std::stoi(argv[++i]); }
60
+ else if (arg == "-vth" || arg == "--vad-thold") { params.vad_thold = std::stof(argv[++i]); }
61
+ else if (arg == "-fth" || arg == "--freq-thold") { params.freq_thold = std::stof(argv[++i]); }
62
+ else if (arg == "-su" || arg == "--speed-up") { params.speed_up = true; }
63
+ else if (arg == "-tr" || arg == "--translate") { params.translate = true; }
64
+ else if (arg == "-ps" || arg == "--print-special") { params.print_special = true; }
65
+ else if (arg == "-pe" || arg == "--print-energy") { params.print_energy = true; }
66
+ else if (arg == "-p" || arg == "--person") { params.person = argv[++i]; }
67
+ else if (arg == "-l" || arg == "--language") { params.language = argv[++i]; }
68
+ else if (arg == "-mw" || arg == "--model-whisper") { params.model_wsp = argv[++i]; }
69
+ else if (arg == "-mg" || arg == "--model-gpt") { params.model_gpt = argv[++i]; }
70
+ else if (arg == "-s" || arg == "--speak") { params.speak = argv[++i]; }
71
+ else if (arg == "-f" || arg == "--file") { params.fname_out = argv[++i]; }
72
+ else {
73
+ fprintf(stderr, "error: unknown argument: %s\n", arg.c_str());
74
+ whisper_print_usage(argc, argv, params);
75
+ exit(0);
76
+ }
77
+ }
78
+
79
+ return true;
80
+ }
81
+
82
+ void whisper_print_usage(int argc, char ** argv, const whisper_params & params) {
83
+ fprintf(stderr, "\n");
84
+ fprintf(stderr, "usage: %s [options]\n", argv[0]);
85
+ fprintf(stderr, "\n");
86
+ fprintf(stderr, "options:\n");
87
+ fprintf(stderr, " -h, --help [default] show this help message and exit\n");
88
+ fprintf(stderr, " -t N, --threads N [%-7d] number of threads to use during computation\n", params.n_threads);
89
+ fprintf(stderr, " -vms N, --voice-ms N [%-7d] voice duration in milliseconds\n", params.voice_ms);
90
+ fprintf(stderr, " -c ID, --capture ID [%-7d] capture device ID\n", params.capture_id);
91
+ fprintf(stderr, " -mt N, --max-tokens N [%-7d] maximum number of tokens per audio chunk\n", params.max_tokens);
92
+ fprintf(stderr, " -ac N, --audio-ctx N [%-7d] audio context size (0 - all)\n", params.audio_ctx);
93
+ fprintf(stderr, " -vth N, --vad-thold N [%-7.2f] voice activity detection threshold\n", params.vad_thold);
94
+ fprintf(stderr, " -fth N, --freq-thold N [%-7.2f] high-pass frequency cutoff\n", params.freq_thold);
95
+ fprintf(stderr, " -su, --speed-up [%-7s] speed up audio by x2 (reduced accuracy)\n", params.speed_up ? "true" : "false");
96
+ fprintf(stderr, " -tr, --translate [%-7s] translate from source language to english\n", params.translate ? "true" : "false");
97
+ fprintf(stderr, " -ps, --print-special [%-7s] print special tokens\n", params.print_special ? "true" : "false");
98
+ fprintf(stderr, " -pe, --print-energy [%-7s] print sound energy (for debugging)\n", params.print_energy ? "true" : "false");
99
+ fprintf(stderr, " -p NAME, --person NAME [%-7s] person name (for prompt selection)\n", params.person.c_str());
100
+ fprintf(stderr, " -l LANG, --language LANG [%-7s] spoken language\n", params.language.c_str());
101
+ fprintf(stderr, " -mw FILE, --model-whisper [%-7s] whisper model file\n", params.model_wsp.c_str());
102
+ fprintf(stderr, " -mg FILE, --model-gpt [%-7s] gpt model file\n", params.model_gpt.c_str());
103
+ fprintf(stderr, " -s FILE, --speak TEXT [%-7s] command for TTS\n", params.speak.c_str());
104
+ fprintf(stderr, " -f FNAME, --file FNAME [%-7s] text output file name\n", params.fname_out.c_str());
105
+ fprintf(stderr, "\n");
106
+ }
107
+
108
+ //
109
+ // SDL Audio capture
110
+ //
111
+
112
+ class audio_async {
113
+ public:
114
+ audio_async(int len_ms);
115
+ ~audio_async();
116
+
117
+ bool init(int capture_id, int sample_rate);
118
+
119
+ // start capturing audio via the provided SDL callback
120
+ // keep last len_ms seconds of audio in a circular buffer
121
+ bool resume();
122
+ bool pause();
123
+ bool clear();
124
+
125
+ // callback to be called by SDL
126
+ void callback(uint8_t * stream, int len);
127
+
128
+ // get audio data from the circular buffer
129
+ void get(int ms, std::vector<float> & audio);
130
+
131
+ private:
132
+ SDL_AudioDeviceID m_dev_id_in = 0;
133
+
134
+ int m_len_ms = 0;
135
+ int m_sample_rate = 0;
136
+
137
+ bool m_running = false;
138
+ std::mutex m_mutex;
139
+
140
+ std::vector<float> m_audio;
141
+ std::vector<float> m_audio_new;
142
+ size_t m_audio_pos = 0;
143
+ size_t m_audio_len = 0;
144
+ };
145
+
146
+ audio_async::audio_async(int len_ms) {
147
+ m_len_ms = len_ms;
148
+ }
149
+
150
+ audio_async::~audio_async() {
151
+ if (m_dev_id_in) {
152
+ SDL_CloseAudioDevice(m_dev_id_in);
153
+ }
154
+ }
155
+
156
+ bool audio_async::init(int capture_id, int sample_rate) {
157
+ SDL_LogSetPriority(SDL_LOG_CATEGORY_APPLICATION, SDL_LOG_PRIORITY_INFO);
158
+
159
+ if (SDL_Init(SDL_INIT_AUDIO) < 0) {
160
+ SDL_LogError(SDL_LOG_CATEGORY_APPLICATION, "Couldn't initialize SDL: %s\n", SDL_GetError());
161
+ return false;
162
+ }
163
+
164
+ SDL_SetHintWithPriority(SDL_HINT_AUDIO_RESAMPLING_MODE, "medium", SDL_HINT_OVERRIDE);
165
+
166
+ {
167
+ int nDevices = SDL_GetNumAudioDevices(SDL_TRUE);
168
+ fprintf(stderr, "%s: found %d capture devices:\n", __func__, nDevices);
169
+ for (int i = 0; i < nDevices; i++) {
170
+ fprintf(stderr, "%s: - Capture device #%d: '%s'\n", __func__, i, SDL_GetAudioDeviceName(i, SDL_TRUE));
171
+ }
172
+ }
173
+
174
+ SDL_AudioSpec capture_spec_requested;
175
+ SDL_AudioSpec capture_spec_obtained;
176
+
177
+ SDL_zero(capture_spec_requested);
178
+ SDL_zero(capture_spec_obtained);
179
+
180
+ capture_spec_requested.freq = sample_rate;
181
+ capture_spec_requested.format = AUDIO_F32;
182
+ capture_spec_requested.channels = 1;
183
+ capture_spec_requested.samples = 1024;
184
+ capture_spec_requested.callback = [](void * userdata, uint8_t * stream, int len) {
185
+ audio_async * audio = (audio_async *) userdata;
186
+ audio->callback(stream, len);
187
+ };
188
+ capture_spec_requested.userdata = this;
189
+
190
+ if (capture_id >= 0) {
191
+ fprintf(stderr, "%s: attempt to open capture device %d : '%s' ...\n", __func__, capture_id, SDL_GetAudioDeviceName(capture_id, SDL_TRUE));
192
+ m_dev_id_in = SDL_OpenAudioDevice(SDL_GetAudioDeviceName(capture_id, SDL_TRUE), SDL_TRUE, &capture_spec_requested, &capture_spec_obtained, 0);
193
+ } else {
194
+ fprintf(stderr, "%s: attempt to open default capture device ...\n", __func__);
195
+ m_dev_id_in = SDL_OpenAudioDevice(nullptr, SDL_TRUE, &capture_spec_requested, &capture_spec_obtained, 0);
196
+ }
197
+
198
+ if (!m_dev_id_in) {
199
+ fprintf(stderr, "%s: couldn't open an audio device for capture: %s!\n", __func__, SDL_GetError());
200
+ m_dev_id_in = 0;
201
+
202
+ return false;
203
+ } else {
204
+ fprintf(stderr, "%s: obtained spec for input device (SDL Id = %d):\n", __func__, m_dev_id_in);
205
+ fprintf(stderr, "%s: - sample rate: %d\n", __func__, capture_spec_obtained.freq);
206
+ fprintf(stderr, "%s: - format: %d (required: %d)\n", __func__, capture_spec_obtained.format,
207
+ capture_spec_requested.format);
208
+ fprintf(stderr, "%s: - channels: %d (required: %d)\n", __func__, capture_spec_obtained.channels,
209
+ capture_spec_requested.channels);
210
+ fprintf(stderr, "%s: - samples per frame: %d\n", __func__, capture_spec_obtained.samples);
211
+ fprintf(stderr, "\n");
212
+ }
213
+
214
+ m_sample_rate = capture_spec_obtained.freq;
215
+
216
+ m_audio.resize((m_sample_rate*m_len_ms)/1000);
217
+
218
+ return true;
219
+ }
220
+
221
+ bool audio_async::resume() {
222
+ if (!m_dev_id_in) {
223
+ fprintf(stderr, "%s: no audio device to resume!\n", __func__);
224
+ return false;
225
+ }
226
+
227
+ if (m_running) {
228
+ fprintf(stderr, "%s: already running!\n", __func__);
229
+ return false;
230
+ }
231
+
232
+ SDL_PauseAudioDevice(m_dev_id_in, 0);
233
+
234
+ m_running = true;
235
+
236
+ return true;
237
+ }
238
+
239
+ bool audio_async::pause() {
240
+ if (!m_dev_id_in) {
241
+ fprintf(stderr, "%s: no audio device to pause!\n", __func__);
242
+ return false;
243
+ }
244
+
245
+ if (!m_running) {
246
+ fprintf(stderr, "%s: already paused!\n", __func__);
247
+ return false;
248
+ }
249
+
250
+ SDL_PauseAudioDevice(m_dev_id_in, 1);
251
+
252
+ m_running = false;
253
+
254
+ return true;
255
+ }
256
+
257
+ bool audio_async::clear() {
258
+ if (!m_dev_id_in) {
259
+ fprintf(stderr, "%s: no audio device to clear!\n", __func__);
260
+ return false;
261
+ }
262
+
263
+ if (!m_running) {
264
+ fprintf(stderr, "%s: not running!\n", __func__);
265
+ return false;
266
+ }
267
+
268
+ {
269
+ std::lock_guard<std::mutex> lock(m_mutex);
270
+
271
+ m_audio_pos = 0;
272
+ m_audio_len = 0;
273
+ }
274
+
275
+ return true;
276
+ }
277
+
278
+ // callback to be called by SDL
279
+ void audio_async::callback(uint8_t * stream, int len) {
280
+ if (!m_running) {
281
+ return;
282
+ }
283
+
284
+ const size_t n_samples = len / sizeof(float);
285
+
286
+ m_audio_new.resize(n_samples);
287
+ memcpy(m_audio_new.data(), stream, n_samples * sizeof(float));
288
+
289
+ //fprintf(stderr, "%s: %zu samples, pos %zu, len %zu\n", __func__, n_samples, m_audio_pos, m_audio_len);
290
+
291
+ {
292
+ std::lock_guard<std::mutex> lock(m_mutex);
293
+
294
+ if (m_audio_pos + n_samples > m_audio.size()) {
295
+ const size_t n0 = m_audio.size() - m_audio_pos;
296
+
297
+ memcpy(&m_audio[m_audio_pos], stream, n0 * sizeof(float));
298
+ memcpy(&m_audio[0], &stream[n0], (n_samples - n0) * sizeof(float));
299
+
300
+ m_audio_pos = (m_audio_pos + n_samples) % m_audio.size();
301
+ m_audio_len = m_audio.size();
302
+ } else {
303
+ memcpy(&m_audio[m_audio_pos], stream, n_samples * sizeof(float));
304
+
305
+ m_audio_pos = (m_audio_pos + n_samples) % m_audio.size();
306
+ m_audio_len = std::min(m_audio_len + n_samples, m_audio.size());
307
+ }
308
+ }
309
+ }
310
+
311
+ void audio_async::get(int ms, std::vector<float> & result) {
312
+ if (!m_dev_id_in) {
313
+ fprintf(stderr, "%s: no audio device to get audio from!\n", __func__);
314
+ return;
315
+ }
316
+
317
+ if (!m_running) {
318
+ fprintf(stderr, "%s: not running!\n", __func__);
319
+ return;
320
+ }
321
+
322
+ result.clear();
323
+
324
+ {
325
+ std::lock_guard<std::mutex> lock(m_mutex);
326
+
327
+ if (ms <= 0) {
328
+ ms = m_len_ms;
329
+ }
330
+
331
+ size_t n_samples = (m_sample_rate * ms) / 1000;
332
+ if (n_samples > m_audio_len) {
333
+ n_samples = m_audio_len;
334
+ }
335
+
336
+ result.resize(n_samples);
337
+
338
+ int s0 = m_audio_pos - n_samples;
339
+ if (s0 < 0) {
340
+ s0 += m_audio.size();
341
+ }
342
+
343
+ if (s0 + n_samples > m_audio.size()) {
344
+ const size_t n0 = m_audio.size() - s0;
345
+
346
+ memcpy(result.data(), &m_audio[s0], n0 * sizeof(float));
347
+ memcpy(&result[n0], &m_audio[0], (n_samples - n0) * sizeof(float));
348
+ } else {
349
+ memcpy(result.data(), &m_audio[s0], n_samples * sizeof(float));
350
+ }
351
+ }
352
+ }
353
+
354
+ ///////////////////////////
355
+
356
+ std::string trim(const std::string & s) {
357
+ std::regex e("^\\s+|\\s+$");
358
+ return std::regex_replace(s, e, "");
359
+ }
360
+
361
+ std::string replace(const std::string & s, const std::string & from, const std::string & to) {
362
+ std::string result = s;
363
+ size_t pos = 0;
364
+ while ((pos = result.find(from, pos)) != std::string::npos) {
365
+ result.replace(pos, from.length(), to);
366
+ pos += to.length();
367
+ }
368
+ return result;
369
+ }
370
+
371
+ void high_pass_filter(std::vector<float> & data, float cutoff, float sample_rate) {
372
+ const float rc = 1.0f / (2.0f * M_PI * cutoff);
373
+ const float dt = 1.0f / sample_rate;
374
+ const float alpha = dt / (rc + dt);
375
+
376
+ float y = data[0];
377
+
378
+ for (size_t i = 1; i < data.size(); i++) {
379
+ y = alpha * (y + data[i] - data[i - 1]);
380
+ data[i] = y;
381
+ }
382
+ }
383
+
384
+ bool vad_simple(std::vector<float> & pcmf32, int sample_rate, int last_ms, float vad_thold, float freq_thold, bool verbose) {
385
+ const int n_samples = pcmf32.size();
386
+ const int n_samples_last = (sample_rate * last_ms) / 1000;
387
+
388
+ if (n_samples_last >= n_samples) {
389
+ // not enough samples - assume no speech
390
+ return false;
391
+ }
392
+
393
+ if (freq_thold > 0.0f) {
394
+ high_pass_filter(pcmf32, freq_thold, sample_rate);
395
+ }
396
+
397
+ float energy_all = 0.0f;
398
+ float energy_last = 0.0f;
399
+
400
+ for (size_t i = 0; i < n_samples; i++) {
401
+ energy_all += fabsf(pcmf32[i]);
402
+
403
+ if (i >= n_samples - n_samples_last) {
404
+ energy_last += fabsf(pcmf32[i]);
405
+ }
406
+ }
407
+
408
+ energy_all /= n_samples;
409
+ energy_last /= n_samples_last;
410
+
411
+ if (verbose) {
412
+ fprintf(stderr, "%s: energy_all: %f, energy_last: %f, vad_thold: %f, freq_thold: %f\n", __func__, energy_all, energy_last, vad_thold, freq_thold);
413
+ }
414
+
415
+ if (energy_last > vad_thold*energy_all) {
416
+ return false;
417
+ }
418
+
419
+ return true;
420
+ }
421
+
422
+ std::string transcribe(whisper_context * ctx, const whisper_params & params, const std::vector<float> & pcmf32, float & prob, int64_t & t_ms) {
423
+ const auto t_start = std::chrono::high_resolution_clock::now();
424
+
425
+ prob = 0.0f;
426
+ t_ms = 0;
427
+
428
+ whisper_full_params wparams = whisper_full_default_params(WHISPER_SAMPLING_GREEDY);
429
+
430
+ wparams.print_progress = false;
431
+ wparams.print_special = params.print_special;
432
+ wparams.print_realtime = false;
433
+ wparams.print_timestamps = !params.no_timestamps;
434
+ wparams.translate = params.translate;
435
+ wparams.no_context = true;
436
+ wparams.single_segment = true;
437
+ wparams.max_tokens = params.max_tokens;
438
+ wparams.language = params.language.c_str();
439
+ wparams.n_threads = params.n_threads;
440
+
441
+ wparams.audio_ctx = params.audio_ctx;
442
+ wparams.speed_up = params.speed_up;
443
+
444
+ if (whisper_full(ctx, wparams, pcmf32.data(), pcmf32.size()) != 0) {
445
+ return "";
446
+ }
447
+
448
+ int prob_n = 0;
449
+ std::string result;
450
+
451
+ const int n_segments = whisper_full_n_segments(ctx);
452
+ for (int i = 0; i < n_segments; ++i) {
453
+ const char * text = whisper_full_get_segment_text(ctx, i);
454
+
455
+ result += text;
456
+
457
+ const int n_tokens = whisper_full_n_tokens(ctx, i);
458
+ for (int j = 0; j < n_tokens; ++j) {
459
+ const auto token = whisper_full_get_token_data(ctx, i, j);
460
+
461
+ prob += token.p;
462
+ ++prob_n;
463
+ }
464
+ }
465
+
466
+ if (prob_n > 0) {
467
+ prob /= prob_n;
468
+ }
469
+
470
+ const auto t_end = std::chrono::high_resolution_clock::now();
471
+ t_ms = std::chrono::duration_cast<std::chrono::milliseconds>(t_end - t_start).count();
472
+
473
+ return result;
474
+ }
475
+
476
+ // compute similarity between two strings using Levenshtein distance
477
+ float similarity(const std::string & s0, const std::string & s1) {
478
+ const size_t len0 = s0.size() + 1;
479
+ const size_t len1 = s1.size() + 1;
480
+
481
+ std::vector<int> col(len1, 0);
482
+ std::vector<int> prevCol(len1, 0);
483
+
484
+ for (size_t i = 0; i < len1; i++) {
485
+ prevCol[i] = i;
486
+ }
487
+
488
+ for (size_t i = 0; i < len0; i++) {
489
+ col[0] = i;
490
+ for (size_t j = 1; j < len1; j++) {
491
+ col[j] = std::min(std::min(1 + col[j - 1], 1 + prevCol[j]), prevCol[j - 1] + (s0[i - 1] == s1[j - 1] ? 0 : 1));
492
+ }
493
+ col.swap(prevCol);
494
+ }
495
+
496
+ const float dist = prevCol[len1 - 1];
497
+
498
+ return 1.0f - (dist / std::max(s0.size(), s1.size()));
499
+ }
500
+
501
+ // generated with ChatGPT
502
+ std::map<std::string, std::string> k_prompts = {
503
+ { "Santa",
504
+ R"(Kid: Hi Santa! Are you real?
505
+ Santa: Of course I am, my dear! Ho ho ho!
506
+ Kid: Can you please bring me a new toy for Christmas?
507
+ Santa: I'll see what I can do, but you have to make sure to be a good boy or girl and listen to your parents.
508
+ Kid: I will, Santa! Thank you!
509
+ Santa: You're welcome, little one. Merry Christmas! Ho ho ho!
510
+ Kid: Can you tell me how you deliver all the presents to all the kids in the world in one night?
511
+ Santa: It's a secret, but I have a lot of help from my elves and my magical sleigh. And I have a special route that I follow to make sure I visit every child.
512
+ Kid: Wow, that's amazing! Can I please have a ride in your sleigh sometime?
513
+ Santa: I'm sorry, but only good boys and girls get to ride in my sleigh.
514
+ )" },
515
+ { "Kid",
516
+ R"(Kid: Hi Santa! Are you real?
517
+ Santa: Of course I am, my dear! Ho ho ho!
518
+ Kid: Can you please bring me a new toy for Christmas?
519
+ Santa: I'll see what I can do, but you have to make sure to be a good boy or girl and listen to your parents.
520
+ Kid: I will, Santa! Thank you!
521
+ Kid: Can you tell me how you deliver all the presents to all the kids in the world in one night?
522
+ Santa: It's a secret, but I have a lot of help from my elves and my magical sleigh. And I have a special route that I follow to make sure I visit every child.
523
+ Kid: Wow, that's amazing! Can I please have a ride in your sleigh sometime?
524
+ )" },
525
+ };
526
+
527
+ int main(int argc, char ** argv) {
528
+ whisper_params params;
529
+
530
+ if (whisper_params_parse(argc, argv, params) == false) {
531
+ return 1;
532
+ }
533
+
534
+ if (whisper_lang_id(params.language.c_str()) == -1) {
535
+ fprintf(stderr, "error: unknown language '%s'\n", params.language.c_str());
536
+ whisper_print_usage(argc, argv, params);
537
+ exit(0);
538
+ }
539
+
540
+ // whisper init
541
+
542
+ struct whisper_context * ctx_wsp = whisper_init(params.model_wsp.c_str());
543
+
544
+ // gpt init
545
+
546
+ struct gpt2_context * ctx_gpt = gpt2_init(params.model_gpt.c_str());
547
+
548
+ // print some info about the processing
549
+ {
550
+ fprintf(stderr, "\n");
551
+ if (!whisper_is_multilingual(ctx_wsp)) {
552
+ if (params.language != "en" || params.translate) {
553
+ params.language = "en";
554
+ params.translate = false;
555
+ fprintf(stderr, "%s: WARNING: model is not multilingual, ignoring language and translation options\n", __func__);
556
+ }
557
+ }
558
+ fprintf(stderr, "%s: processing, %d threads, lang = %s, task = %s, timestamps = %d ...\n",
559
+ __func__,
560
+ params.n_threads,
561
+ params.language.c_str(),
562
+ params.translate ? "translate" : "transcribe",
563
+ params.no_timestamps ? 0 : 1);
564
+
565
+ fprintf(stderr, "\n");
566
+ }
567
+
568
+
569
+ // init audio
570
+
571
+ audio_async audio(30*1000);
572
+ if (!audio.init(params.capture_id, WHISPER_SAMPLE_RATE)) {
573
+ fprintf(stderr, "%s: audio.init() failed!\n", __func__);
574
+ return 1;
575
+ }
576
+
577
+ audio.resume();
578
+
579
+ int n_iter = 0;
580
+
581
+ bool is_running = true;
582
+ bool force_speak = params.person == "Kid";
583
+
584
+ float prob0 = 0.0f;
585
+ float prob = 0.0f;
586
+
587
+ std::vector<float> pcmf32_cur;
588
+ std::vector<float> pcmf32_prompt;
589
+
590
+ if (k_prompts.find(params.person) == k_prompts.end()) {
591
+ fprintf(stderr, "%s: unknown person '%s'\n", __func__, params.person.c_str());
592
+ return 1;
593
+ }
594
+
595
+ gpt2_set_prompt(ctx_gpt, k_prompts.at(params.person).c_str());
596
+
597
+ const std::string person_other = params.person == "Santa" ? "Kid" : "Santa";
598
+ const int voice_id = params.person == "Santa" ? 5 : 2;
599
+
600
+ fprintf(stderr, "gpt-2: prompt_base:\n");
601
+ fprintf(stderr, "========================\n\n");
602
+ fprintf(stderr, "%s\n", gpt2_get_prompt(ctx_gpt));
603
+ fprintf(stderr, "========================\n\n");
604
+
605
+ // main loop
606
+ while (is_running) {
607
+ // handle Ctrl + C
608
+ {
609
+ SDL_Event event;
610
+ while (SDL_PollEvent(&event)) {
611
+ switch (event.type) {
612
+ case SDL_QUIT:
613
+ {
614
+ is_running = false;
615
+ } break;
616
+ default:
617
+ break;
618
+ }
619
+ }
620
+
621
+ if (!is_running) {
622
+ break;
623
+ }
624
+ }
625
+
626
+ // delay
627
+ std::this_thread::sleep_for(std::chrono::milliseconds(100));
628
+
629
+ int64_t t_ms = 0;
630
+
631
+ {
632
+ audio.get(2000, pcmf32_cur);
633
+
634
+ if (vad_simple(pcmf32_cur, WHISPER_SAMPLE_RATE, 1250, params.vad_thold, params.freq_thold, params.print_energy) || force_speak) {
635
+ fprintf(stdout, "%s: Speech detected! Processing ...\n", __func__);
636
+
637
+ audio.get(params.voice_ms, pcmf32_cur);
638
+
639
+ std::string text_heard = "Hey little one, what do you want for Christmas?";
640
+ if (!force_speak) {
641
+ text_heard = ::trim(::transcribe(ctx_wsp, params, pcmf32_cur, prob0, t_ms));
642
+ }
643
+
644
+ force_speak = false;
645
+
646
+ // remove text between brackets using regex
647
+ {
648
+ std::regex re("\\[.*?\\]");
649
+ text_heard = std::regex_replace(text_heard, re, "");
650
+ }
651
+
652
+ // remove text between brackets using regex
653
+ {
654
+ std::regex re("\\(.*?\\)");
655
+ text_heard = std::regex_replace(text_heard, re, "");
656
+ }
657
+
658
+ // remove all characters, except for letters, numbers, punctuation and ':', '\'', '-', ' '
659
+ text_heard = std::regex_replace(text_heard, std::regex("[^a-zA-Z0-9\\.,\\?!\\s\\:\\'\\-]"), "");
660
+
661
+ // take first line
662
+ text_heard = text_heard.substr(0, text_heard.find_first_of("\n"));
663
+
664
+ // remove leading and trailing whitespace
665
+ text_heard = std::regex_replace(text_heard, std::regex("^\\s+"), "");
666
+ text_heard = std::regex_replace(text_heard, std::regex("\\s+$"), "");
667
+
668
+ const std::vector<gpt_vocab::id> tokens = gpt2_tokenize(ctx_gpt, text_heard.c_str());
669
+
670
+ if (text_heard.empty() || tokens.empty()) {
671
+ fprintf(stdout, "%s: Heard nothing, skipping ...\n", __func__);
672
+ audio.clear();
673
+
674
+ continue;
675
+ }
676
+
677
+ fprintf(stdout, "%s: Heard '%s%s%s', (t = %d ms)\n", __func__, "\033[1m", text_heard.c_str(), "\033[0m", (int) t_ms);
678
+
679
+ std::string prompt_base = gpt2_get_prompt(ctx_gpt);
680
+
681
+ std::string text_to_speak;
682
+
683
+ {
684
+ text_heard = person_other + ": " + text_heard;
685
+
686
+ text_to_speak = gpt2_gen_text(ctx_gpt, (prompt_base + text_heard + "\n").c_str(), params.max_tokens);
687
+ text_to_speak = std::regex_replace(text_to_speak, std::regex("[^a-zA-Z0-9\\.,\\?!\\s\\:\\'\\-]"), "");
688
+ text_to_speak = text_to_speak.substr(0, text_to_speak.find_first_of("\n"));
689
+
690
+ // remove first 2 lines of base prompt
691
+ if (n_iter > 4) {
692
+ {
693
+ const size_t pos = prompt_base.find_first_of("\n");
694
+ if (pos != std::string::npos) {
695
+ prompt_base = prompt_base.substr(pos + 1);
696
+ }
697
+ }
698
+ {
699
+ const size_t pos = prompt_base.find_first_of("\n");
700
+ if (pos != std::string::npos) {
701
+ prompt_base = prompt_base.substr(pos + 1);
702
+ }
703
+ }
704
+ }
705
+
706
+ prompt_base += text_heard + "\n" + text_to_speak + "\n";
707
+ }
708
+
709
+ printf("%s\n", text_to_speak.c_str());
710
+
711
+ //printf("========================\n");
712
+ //printf("gpt-2: prompt_base:\n'%s'\n", prompt_base.c_str());
713
+ //printf("========================\n");
714
+
715
+ gpt2_set_prompt(ctx_gpt, prompt_base.c_str());
716
+
717
+ text_to_speak = ::replace(text_to_speak, params.person + ": ", "");
718
+ system((params.speak + " " + std::to_string(voice_id) + " \"" + text_to_speak + "\"").c_str());
719
+
720
+ audio.clear();
721
+
722
+ ++n_iter;
723
+ }
724
+ }
725
+ }
726
+
727
+ audio.pause();
728
+
729
+ whisper_print_timings(ctx_wsp);
730
+ whisper_free(ctx_wsp);
731
+
732
+ return 0;
733
+ }
ggml.c CHANGED
@@ -4221,7 +4221,7 @@ bool ggml_compute_forward_mul_mat_use_blas(
4221
  const int ne1 = dst->ne[1];
4222
 
4223
  // TODO: find the optimal values for these
4224
- if (ggml_is_contiguous(src1) && ne0 >= 32 && ne1 >= 32 && ne10 >= 32) {
4225
  //printf("BLAS: %d %d %d\n", ne0, ne1, ne10);
4226
  return true;
4227
  }
@@ -4298,7 +4298,6 @@ void ggml_compute_forward_mul_mat_f32(
4298
 
4299
  #if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
4300
  if (ggml_compute_forward_mul_mat_use_blas(src0, src1, dst)) {
4301
- GGML_ASSERT(ggml_is_contiguous(src0));
4302
  GGML_ASSERT(nb10 == sizeof(float));
4303
 
4304
  if (params->ith != 0) return;
 
4221
  const int ne1 = dst->ne[1];
4222
 
4223
  // TODO: find the optimal values for these
4224
+ if (ggml_is_contiguous(src0) && ggml_is_contiguous(src1) && ne0 >= 32 && ne1 >= 32 && ne10 >= 32) {
4225
  //printf("BLAS: %d %d %d\n", ne0, ne1, ne10);
4226
  return true;
4227
  }
 
4298
 
4299
  #if defined(GGML_USE_ACCELERATE) || defined(GGML_USE_OPENBLAS)
4300
  if (ggml_compute_forward_mul_mat_use_blas(src0, src1, dst)) {
 
4301
  GGML_ASSERT(nb10 == sizeof(float));
4302
 
4303
  if (params->ith != 0) return;