55#include < string>
66#include < vector>
77
8+ // Add a message to `messages` and store its content in `owned_content`
9+ static void add_message (const std::string &role, const std::string &text,
10+ std::vector<llama_chat_message> &messages,
11+ std::vector<std::unique_ptr<char []>> &owned_content) {
12+ auto content = std::make_unique<char []>(text.size () + 1 );
13+ std::strcpy (content.get (), text.c_str ());
14+ messages.push_back ({role.c_str (), content.get ()});
15+ owned_content.push_back (std::move (content));
16+ }
17+
18+ // Function to apply the chat template and resize `formatted` if needed
19+ static int apply_chat_template (const llama_model *model,
20+ const std::vector<llama_chat_message> &messages,
21+ std::vector<char > &formatted, bool append) {
22+ int result = llama_chat_apply_template (model, nullptr , messages.data (),
23+ messages.size (), append,
24+ formatted.data (), formatted.size ());
25+ if (result > static_cast <int >(formatted.size ())) {
26+ formatted.resize (result);
27+ result = llama_chat_apply_template (model, nullptr , messages.data (),
28+ messages.size (), append,
29+ formatted.data (), formatted.size ());
30+ }
31+
32+ return result;
33+ }
34+
35+ // helper function to evaluate a prompt and generate a response
36+ static int generate (const llama_model *model, llama_sampler *smpl,
37+ llama_context *ctx, const std::string &prompt,
38+ std::string &response) {
39+ // tokenize the prompt
40+ const int n_prompt_tokens = -llama_tokenize (
41+ model, prompt.c_str (), prompt.size (), NULL , 0 , true , true );
42+ std::vector<llama_token> prompt_tokens (n_prompt_tokens);
43+ if (llama_tokenize (model, prompt.c_str (), prompt.size (),
44+ prompt_tokens.data (), prompt_tokens.size (),
45+ llama_get_kv_cache_used_cells (ctx) == 0 , true ) < 0 ) {
46+ GGML_ABORT (" failed to tokenize the prompt\n " );
47+ }
48+
49+ // prepare a batch for the prompt
50+ llama_batch batch =
51+ llama_batch_get_one (prompt_tokens.data (), prompt_tokens.size ());
52+ llama_token new_token_id;
53+ while (true ) {
54+ // check if we have enough space in the context to evaluate this batch
55+ int n_ctx = llama_n_ctx (ctx);
56+ int n_ctx_used = llama_get_kv_cache_used_cells (ctx);
57+ if (n_ctx_used + batch.n_tokens > n_ctx) {
58+ printf (" \033 [0m\n " );
59+ fprintf (stderr, " context size exceeded\n " );
60+ return 1 ;
61+ }
62+
63+ if (llama_decode (ctx, batch)) {
64+ GGML_ABORT (" failed to decode\n " );
65+ }
66+
67+ // sample the next token
68+ new_token_id = llama_sampler_sample (smpl, ctx, -1 );
69+
70+ // is it an end of generation?
71+ if (llama_token_is_eog (model, new_token_id)) {
72+ break ;
73+ }
74+
75+ // convert the token to a string, print it and add it to the response
76+ char buf[256 ];
77+ int n = llama_token_to_piece (model, new_token_id, buf, sizeof (buf), 0 ,
78+ true );
79+ if (n < 0 ) {
80+ GGML_ABORT (" failed to convert token to piece\n " );
81+ }
82+ std::string piece (buf, n);
83+ printf (" %s" , piece.c_str ());
84+ fflush (stdout);
85+ response += piece;
86+
87+ // prepare the next batch with the sampled token
88+ batch = llama_batch_get_one (&new_token_id, 1 );
89+ }
90+
91+ return 0 ;
92+ }
93+
894static void print_usage (int , char ** argv) {
995 printf (" \n example usage:\n " );
1096 printf (" \n %s -m model.gguf [-c context_size] [-ngl n_gpu_layers]\n " , argv[0 ]);
@@ -66,6 +152,7 @@ int main(int argc, char ** argv) {
66152 llama_model_params model_params = llama_model_default_params ();
67153 model_params.n_gpu_layers = ngl;
68154
155+ // This prints ........
69156 llama_model * model = llama_load_model_from_file (model_path.c_str (), model_params);
70157 if (!model) {
71158 fprintf (stderr , " %s: error: unable to load model\n " , __func__);
@@ -88,107 +175,49 @@ int main(int argc, char ** argv) {
88175 llama_sampler_chain_add (smpl, llama_sampler_init_min_p (0 .05f , 1 ));
89176 llama_sampler_chain_add (smpl, llama_sampler_init_temp (0 .8f ));
90177 llama_sampler_chain_add (smpl, llama_sampler_init_dist (LLAMA_DEFAULT_SEED));
91-
92- // helper function to evaluate a prompt and generate a response
93- auto generate = [&](const std::string & prompt) {
94- std::string response;
95-
96- // tokenize the prompt
97- const int n_prompt_tokens = -llama_tokenize (model, prompt.c_str (), prompt.size (), NULL , 0 , true , true );
98- std::vector<llama_token> prompt_tokens (n_prompt_tokens);
99- if (llama_tokenize (model, prompt.c_str (), prompt.size (), prompt_tokens.data (), prompt_tokens.size (), llama_get_kv_cache_used_cells (ctx) == 0 , true ) < 0 ) {
100- GGML_ABORT (" failed to tokenize the prompt\n " );
101- }
102-
103- // prepare a batch for the prompt
104- llama_batch batch = llama_batch_get_one (prompt_tokens.data (), prompt_tokens.size ());
105- llama_token new_token_id;
106- while (true ) {
107- // check if we have enough space in the context to evaluate this batch
108- int n_ctx = llama_n_ctx (ctx);
109- int n_ctx_used = llama_get_kv_cache_used_cells (ctx);
110- if (n_ctx_used + batch.n_tokens > n_ctx) {
111- printf (" \033 [0m\n " );
112- fprintf (stderr, " context size exceeded\n " );
113- exit (0 );
114- }
115-
116- if (llama_decode (ctx, batch)) {
117- GGML_ABORT (" failed to decode\n " );
118- }
119-
120- // sample the next token
121- new_token_id = llama_sampler_sample (smpl, ctx, -1 );
122-
123- // is it an end of generation?
124- if (llama_token_is_eog (model, new_token_id)) {
125- break ;
126- }
127-
128- // convert the token to a string, print it and add it to the response
129- char buf[256 ];
130- int n = llama_token_to_piece (model, new_token_id, buf, sizeof (buf), 0 , true );
131- if (n < 0 ) {
132- GGML_ABORT (" failed to convert token to piece\n " );
133- }
134- std::string piece (buf, n);
135- printf (" %s" , piece.c_str ());
136- fflush (stdout);
137- response += piece;
138-
139- // prepare the next batch with the sampled token
140- batch = llama_batch_get_one (&new_token_id, 1 );
141- }
142-
143- return response;
144- };
145-
146178 std::vector<llama_chat_message> messages;
179+ std::vector<std::unique_ptr<char []>> owned_content;
147180 std::vector<char > formatted (llama_n_ctx (ctx));
148181 int prev_len = 0 ;
149182 while (true ) {
150183 // get user input
151184 printf (" \033 [32m> \033 [0m" );
152185 std::string user;
153186 std::getline (std::cin, user);
154-
155187 if (user.empty ()) {
156188 break ;
157189 }
158190
159- // add the user input to the message list and format it
160- messages.push_back ({" user" , strdup (user.c_str ())});
161- int new_len = llama_chat_apply_template (model, nullptr , messages.data (), messages.size (), true , formatted.data (), formatted.size ());
162- if (new_len > (int )formatted.size ()) {
163- formatted.resize (new_len);
164- new_len = llama_chat_apply_template (model, nullptr , messages.data (), messages.size (), true , formatted.data (), formatted.size ());
165- }
191+ // Add user input to messages
192+ add_message (" user" , user, messages, owned_content);
193+ int new_len = apply_chat_template (model, messages, formatted, true );
166194 if (new_len < 0 ) {
167195 fprintf (stderr, " failed to apply the chat template\n " );
168196 return 1 ;
169197 }
170198
171- // remove previous messages to obtain the prompt to generate the response
172- std::string prompt (formatted.begin () + prev_len, formatted.begin () + new_len);
199+ // remove previous messages to obtain the prompt to generate the
200+ // response
201+ std::string prompt (formatted.begin () + prev_len,
202+ formatted.begin () + new_len);
173203
174204 // generate a response
175205 printf (" \033 [33m" );
176- std::string response = generate (prompt);
206+ std::string response;
207+ if (generate (model, smpl, ctx, prompt, response)) {
208+ return 1 ;
209+ }
210+
177211 printf (" \n\033 [0m" );
178212
179- // add the response to the messages
180- messages.push_back ({" assistant" , strdup (response.c_str ())});
181- prev_len = llama_chat_apply_template (model, nullptr , messages.data (), messages.size (), false , nullptr , 0 );
213+ // Add response to messages
214+ prev_len = apply_chat_template (model, messages, formatted, false );
182215 if (prev_len < 0 ) {
183216 fprintf (stderr, " failed to apply the chat template\n " );
184217 return 1 ;
185218 }
186219 }
187220
188- // free resources
189- for (auto & msg : messages) {
190- free (const_cast <char *>(msg.content ));
191- }
192221 llama_sampler_free (smpl);
193222 llama_free (ctx);
194223 llama_free_model (model);
0 commit comments