char-fork/llama.cpp
git clone https://git.t4t.associates/char-fork/llama.cpp
5594d1322
char/aliceai-t5-moe
1#include "debug.h" 2#include "arg.h" 3#include "common.h" 4#include "log.h" 5#include "llama.h" 6 7#include <cstdlib> 8#include <string> 9#include <vector> 10#include <filesystem> 11#include <fstream> 12#include <optional> 13#include <regex> 14 15static void print_usage (int /*argc*/ ,char ** argv ) { 16const std::string usage_template = R"( 17example usage: 18 19Print tensors: 20 21{prog} -m model.gguf -p "Hello my name is" --verbose 22 23The tensors to be printed can be filtered with --tensor-filter option. 24 25Save logits/embeddings: 26 27{prog} -m model.gguf -p "Hello my name is" --save-logits 28 29Add --embedding to save embeddings)" "\n" ; 30 31// Fix the source code indentation above that is introduced by the raw string literal. 32 std::string usage = std::regex_replace (usage_template , std::regex ("\\n {8}" ),"\n" ); 33usage = std::regex_replace (usage , std::regex ("\\{prog\\}" ),argv [0 ]); 34LOG ("%s\n" ,usage .c_str ()); 35} 36 37static bool has_pooling (llama_context * ctx ) { 38switch (llama_pooling_type (ctx )) { 39case LLAMA_POOLING_TYPE_NONE : 40case LLAMA_POOLING_TYPE_UNSPECIFIED : 41return false; 42default : 43return true; 44 } 45} 46 47struct output_data { 48float * data_ptr = nullptr ; 49int data_size = 0 ; 50 std::string type_suffix ; 51 std::vector < float > embd_norm ; 52 std::string prompt ; 53 std::vector < llama_token > tokens ; 54 55output_data (llama_context * ctx ,const llama_model * model ,const common_params & params ) { 56const llama_vocab * vocab = llama_model_get_vocab (model ); 57const bool add_bos = llama_vocab_get_add_bos (vocab ); 58 59tokens = common_tokenize (ctx ,params .prompt ,add_bos ); 60prompt = params .prompt ; 61 62if (params .embedding ) { 63const int n_embd = llama_model_n_embd_out (model ); 64const bool pooling = has_pooling (ctx ); 65const int n_embd_count = pooling ?1 :tokens .size (); 66const int n_floats = n_embd * n_embd_count ; 67 68float * embd_raw = pooling ?llama_get_embeddings_seq (ctx ,0 ) :llama_get_embeddings (ctx ); 69if (embd_raw == nullptr ) { 70throw std::runtime_error ("failed to get embeddings from the model" ); 71 } 72 73LOG_DBG ("pooling_enabled: %s\n" ,pooling ?"true" :"false" ); 74LOG_DBG ("n_embd: %d\n" ,n_embd ); 75LOG_DBG ("n_floats: %d\n" ,n_floats ); 76LOG_DBG ("n_embd_count: %d\n" ,n_embd_count ); 77 78data_ptr = embd_raw ; 79data_size = n_floats ; 80type_suffix = "-embeddings" ; 81 82if (params .embd_normalize >=0 ) { 83embd_norm .resize (n_floats ); 84for (int i = 0 ;i < n_embd_count ;i ++ ) { 85common_embd_normalize (embd_raw + i * n_embd ,embd_norm .data ()+ i * n_embd ,n_embd ,params .embd_normalize ); 86 } 87data_ptr = embd_norm .data (); 88 } 89 }else { 90const float * logits = llama_get_logits_ith (ctx ,tokens .size ()- 1 ); 91const int n_logits = llama_vocab_n_tokens (vocab ); 92 93data_ptr = const_cast < float *> (logits ); 94data_size = n_logits ; 95type_suffix = "" ; 96 } 97 } 98}; 99 100static void save_output_data (const output_data & output ,const std::string & model_name ,const std::string & output_dir ) { 101 std::filesystem::create_directory (output_dir ); 102auto base_path = std::filesystem::path {output_dir } / ("llamacpp-" + model_name + output .type_suffix ); 103 104// Save logits/embeddings to binary file. 105 { 106 std::filesystem::path filepath {base_path .string ()+ ".bin" }; 107 std::ofstream file {filepath , std::ios::binary }; 108if (!file ) { 109throw std::runtime_error ("failed to open binary output file: " + filepath .string ()); 110 } 111file .write (reinterpret_cast < const char *> (output .data_ptr ),output .data_size * sizeof (float )); 112LOG ("Data saved to %s\n" ,filepath .c_str ()); 113 } 114 115// Save logits/embeddings to text file. 116 { 117 std::filesystem::path filepath {base_path .string ()+ ".txt" }; 118 std::ofstream file {filepath }; 119if (!file ) { 120throw std::runtime_error ("failed to open text output file: " + filepath .string ()); 121 } 122for (int i = 0 ;i < output .data_size ;i ++ ) { 123file <<i <<": " <<output .data_ptr [i ] <<'\n' ; 124 } 125LOG ("Data saved to %s\n" ,filepath .c_str ()); 126 } 127 128// Save prompt and tokens to text file. 129 { 130 std::filesystem::path filepath {base_path .string ()+ "-prompt.txt" }; 131 std::ofstream file {filepath }; 132if (!file ) { 133throw std::runtime_error ("failed to open prompt output file: " + filepath .string ()); 134 } 135 136file <<"prompt: " <<output .prompt <<'\n' ; 137file <<"n_tokens: " <<output .tokens .size () <<'\n' ; 138 139file <<"token ids: " ; 140for (size_t i = 0 ;i < output .tokens .size ();i ++ ) { 141file <<output .tokens [i ]; 142if (i + 1 < output .tokens .size ()) { 143file <<", " ; 144 } 145 } 146file <<'\n' ; 147LOG ("Prompt saved to %s\n" ,filepath .c_str ()); 148 } 149 150// Save token ids to binary file. 151 { 152 std::filesystem::path filepath {base_path .string ()+ "-tokens.bin" }; 153 std::ofstream file {filepath , std::ios::binary }; 154if (!file ) { 155throw std::runtime_error ("failed to open tokens binary file: " + filepath .string ()); 156 } 157file .write (reinterpret_cast < const char *> (output .tokens .data ()),output .tokens .size ()* sizeof (llama_token )); 158LOG ("Tokens saved to %s\n" ,filepath .c_str ()); 159 } 160 161} 162 163static void print_tokenized_prompt (llama_context * ctx ,const std::vector < llama_token > & tokens ,const std::string & prompt ) { 164const llama_model * model = llama_get_model (ctx ); 165const llama_vocab * vocab = llama_model_get_vocab (model ); 166 167LOG ("Model add_bos: %s\n" ,llama_vocab_get_add_bos (vocab ) ?"true" :"false" ); 168LOG ("Input prompt: \"%s\"\n" ,prompt .c_str ()); 169LOG ("Token ids (%zu):\n" ,tokens .size ()); 170 171for (auto id :tokens ) { 172 std::string piece (128 ,'\0' ); 173int n = llama_token_to_piece (vocab ,id ,piece .data (),piece .size (),0 , true); 174if (n < 0 ) { 175LOG_ERR ("failed to convert token %d to piece\n" ,id ); 176continue ; 177 } 178piece .resize (n ); 179LOG ("%s(%d) " ,piece .c_str (),id ); 180 } 181LOG ("\n" ); 182} 183 184static bool run (llama_context * ctx ,const common_params & params ) { 185const llama_model * model = llama_get_model (ctx ); 186const llama_vocab * vocab = llama_model_get_vocab (model ); 187 188const bool add_bos = llama_vocab_get_add_bos (vocab ); 189 190 std::vector < llama_token > tokens = common_tokenize (ctx ,params .prompt ,add_bos ); 191 192if (tokens .empty ()) { 193LOG_ERR ("%s : there are not input tokens to process - (try to provide a prompt with '-p')\n" ,__func__ ); 194return false; 195 } 196 197if (llama_decode (ctx ,llama_batch_get_one (tokens .data (),tokens .size ()))) { 198LOG_ERR ("%s : failed to eval\n" ,__func__ ); 199return false; 200 } 201 202print_tokenized_prompt (ctx ,tokens ,params .prompt ); 203 204if (params .save_logits ) { 205try { 206output_data output {ctx ,model ,params }; 207 std::filesystem::path model_path {params .model .path }; 208 std::string model_name {model_path .stem ().string ()}; 209save_output_data (output ,model_name ,params .logits_output_dir ); 210 }catch (const std::exception & e ) { 211LOG_ERR ("%s : error saving logits: %s\n" ,__func__ ,e .what ()); 212 } 213 } 214 215return true; 216} 217 218int main (int argc ,char ** argv ) { 219common_params params ; 220 221common_init (); 222 223if (!common_params_parse (argc ,argv ,params ,LLAMA_EXAMPLE_DEBUG ,print_usage )) { 224return 1 ; 225 } 226 227llama_backend_init (); 228llama_numa_init (params .numa ); 229 230 std::optional < common_debug_cb_user_data > cb_data ; 231if (!params .save_logits ) { 232cb_data .emplace (params ,params .tensor_filter ); 233 } 234 235auto llama_init = common_init_from_params (params ); 236 237auto * model = llama_init -> model (); 238auto * ctx = llama_init -> context (); 239 240if (model == nullptr || ctx == nullptr ) { 241LOG_ERR ("%s : failed to init\n" ,__func__ ); 242return 1 ; 243 } 244 245 { 246LOG_INF ("\n" ); 247LOG_INF ("%s\n" ,common_params_get_system_info (params ).c_str ()); 248LOG_INF ("\n" ); 249 } 250 251if (!run (ctx ,params )) { 252return 1 ; 253 } 254 255LOG ("\n" ); 256llama_perf_context_print (ctx ); 257 258llama_backend_free (); 259 260return 0 ; 261}