okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b2de2641f
main
1#include "llama.h" 2 3#include "llama-impl.h" 4#include "llama-version.h" 5 6#include "llama-chat.h" 7#include "llama-context.h" 8#include "llama-mmap.h" 9#include "llama-vocab.h" 10#include "llama-model-loader.h" 11#include "llama-model-saver.h" 12#include "llama-model.h" 13 14#include "ggml.h" 15#include "ggml-cpp.h" 16#include "ggml-backend.h" 17#include "gguf.h" 18 19#include <algorithm> 20#include <cassert> 21#include <cinttypes> 22#include <cstddef> 23#include <cstdint> 24#include <cstdio> 25#include <cstring> 26#include <ctime> 27#include <stdexcept> 28#include <vector> 29 30#if defined(_MSC_VER ) 31#pragma warning(disable: 4244 4267) // possible loss of data 32#endif 33 34// 35// interface implementation 36// 37 38const char * llama_flash_attn_type_name (enum llama_flash_attn_type flash_attn_type ) { 39switch (flash_attn_type ) { 40case LLAMA_FLASH_ATTN_TYPE_AUTO : 41return "auto" ; 42case LLAMA_FLASH_ATTN_TYPE_DISABLED : 43return "disabled" ; 44case LLAMA_FLASH_ATTN_TYPE_ENABLED : 45return "enabled" ; 46 } 47GGML_ABORT ("fatal error" ); 48} 49 50const char * llama_load_mode_name (enum llama_load_mode load_mode ) { 51switch (load_mode ) { 52case LLAMA_LOAD_MODE_AUTO : 53return "auto" ; 54case LLAMA_LOAD_MODE_NONE : 55return "none" ; 56case LLAMA_LOAD_MODE_MMAP : 57return "mmap" ; 58case LLAMA_LOAD_MODE_MLOCK : 59return "mlock" ; 60case LLAMA_LOAD_MODE_MMAP_MLOCK : 61return "mmap+mlock" ; 62case LLAMA_LOAD_MODE_DIRECT_IO : 63return "dio" ; 64 } 65GGML_ABORT ("fatal error" ); 66} 67 68enum llama_load_mode llama_load_mode_from_str (const char * str ) { 69if (std::strcmp (str ,"auto" )== 0 ) {return LLAMA_LOAD_MODE_AUTO ; } 70if (std::strcmp (str ,"none" )== 0 ) {return LLAMA_LOAD_MODE_NONE ; } 71if (std::strcmp (str ,"mmap" )== 0 ) {return LLAMA_LOAD_MODE_MMAP ; } 72if (std::strcmp (str ,"mlock" )== 0 ) {return LLAMA_LOAD_MODE_MLOCK ; } 73if (std::strcmp (str ,"mmap+mlock" )== 0 ) {return LLAMA_LOAD_MODE_MMAP_MLOCK ; } 74if (std::strcmp (str ,"dio" )== 0 ) {return LLAMA_LOAD_MODE_DIRECT_IO ; } 75throw std::invalid_argument (std::string ("unknown load mode: " )+ str ); 76} 77 78struct llama_sampler_chain_params llama_sampler_chain_default_params () { 79struct llama_sampler_chain_params result = { 80/*.no_perf =*/ true, 81 }; 82 83return result ; 84} 85 86size_t llama_max_devices (void ) { 87return 16 ; 88} 89 90size_t llama_max_tensor_buft_overrides () { 91return 4096 ; 92} 93 94bool llama_supports_mmap (void ) { 95return llama_mmap::SUPPORTED ; 96} 97 98bool llama_supports_mlock (void ) { 99return llama_mlock::SUPPORTED ; 100} 101 102bool llama_supports_gpu_offload (void ) { 103if (!ggml_backend_reg_count ()) { 104ggml_backend_load_all (); 105 } 106return ggml_backend_dev_by_type (GGML_BACKEND_DEVICE_TYPE_GPU )!= nullptr || 107ggml_backend_dev_by_type (GGML_BACKEND_DEVICE_TYPE_IGPU )!= nullptr || 108llama_supports_rpc (); 109} 110 111bool llama_supports_rpc (void ) { 112if (!ggml_backend_reg_count ()) { 113ggml_backend_load_all (); 114 } 115return ggml_backend_reg_by_name ("RPC" )!= nullptr ; 116} 117 118const char * llama_version (void ) { 119return LLAMA_VERSION ; 120} 121 122void llama_backend_init (void ) { 123ggml_time_init (); 124 125// needed to initialize f16 tables 126 { 127struct ggml_init_params params = {0 ,NULL , false }; 128struct ggml_context * ctx = ggml_init (params ); 129ggml_free (ctx ); 130 } 131 132if (!ggml_backend_reg_count ()) { 133ggml_backend_load_all (); 134 } 135} 136 137void llama_numa_init (enum ggml_numa_strategy numa ) { 138if (numa != GGML_NUMA_STRATEGY_DISABLED ) { 139auto * dev = ggml_backend_dev_by_type (GGML_BACKEND_DEVICE_TYPE_CPU ); 140GGML_ASSERT (dev && "CPU backend is not loaded" ); 141auto * reg = ggml_backend_dev_backend_reg (dev ); 142auto * numa_init_fn = (decltype(ggml_numa_init )* )ggml_backend_reg_get_proc_address (reg ,"ggml_backend_cpu_numa_init" ); 143if (numa_init_fn ) { 144numa_init_fn (numa ); 145 } 146 } 147} 148 149void llama_backend_free (void ) { 150ggml_quantize_free (); 151} 152 153int64_t llama_time_us (void ) { 154return ggml_time_us (); 155} 156 157// returns true on success 158static bool llama_prepare_model_devices (const llama_model_params & params ,llama_model * model ) { 159// create list of devices to use with this model 160if (params .devices ) { 161if (params .split_mode == LLAMA_SPLIT_MODE_TENSOR ) { 162size_t n_devs = 0 ; 163while (params .devices [n_devs ]) { 164n_devs ++ ; 165 } 166if (n_devs == 0 ) { 167LLAMA_LOG_ERROR ("%s: LLAMA_SPLIT_MODE_TENSOR needs >= 1 devices\n" ,__func__ ); 168return false; 169 } 170LLAMA_LOG_INFO ("%s: creating a Meta device with %zu devices\n" ,__func__ ,n_devs ); 171for (size_t i = 0 ;i < n_devs ;++ i ) { 172LLAMA_LOG_INFO ("%s: - device %zu: %s\n" ,__func__ ,i ,ggml_backend_dev_name (params .devices [i ])); 173 } 174model -> get_split_state_ud .n_devices = n_devs ; 175model -> get_split_state_ud .model = model ; 176model -> devices .push_back ({ 177 true,ggml_backend_meta_device ( 178params .devices ,n_devs ,llama_meta_device_get_split_state ,& model -> get_split_state_ud ) 179 }); 180 }else { 181for (ggml_backend_dev_t * dev = params .devices ;* dev ;++ dev ) { 182model -> devices .push_back ({false,* dev }); 183 } 184 } 185 }else { 186// default device selection 187 188// build list of available devices 189 std::vector < llama_device > gpus ; 190 std::vector < llama_device > igpus ; 191 std::vector < llama_device > rpc_servers ; 192 193if (params .split_mode == LLAMA_SPLIT_MODE_TENSOR ) { 194 std::vector < ggml_backend_dev_t > devs ; 195devs .reserve (ggml_backend_dev_count ()); 196for (size_t i = 0 ;i < ggml_backend_dev_count ();++ i ) { 197auto * dev = ggml_backend_dev_get (i ); 198if (ggml_backend_dev_buffer_type (dev )== ggml_backend_cpu_buffer_type ()) { 199LLAMA_LOG_INFO ("%s: skipping %s (%s) for tensor parallelism\n" ,__func__ ,ggml_backend_dev_name (dev ),ggml_backend_dev_description (dev )); 200continue ; 201 } 202devs .push_back (dev ); 203 } 204if (devs .empty ()) { 205LLAMA_LOG_ERROR ("%s: LLAMA_SPLIT_MODE_TENSOR needs >= 1 devices\n" ,__func__ ); 206return false; 207 } 208 209LLAMA_LOG_INFO ("%s: creating a Meta device for tensor parallelism from %zu devices:\n" ,__func__ ,devs .size ()); 210for (size_t i = 0 ;i < devs .size ();++ i ) { 211LLAMA_LOG_INFO ("%s: - device %zu: %s (%s)\n" ,__func__ ,i ,ggml_backend_dev_name (devs [i ]),ggml_backend_dev_description (devs [i ])); 212 } 213 214GGML_ASSERT (!devs .empty ()); 215model -> get_split_state_ud .n_devices = devs .size (); 216model -> get_split_state_ud .model = model ; 217gpus .push_back ({ 218 true,ggml_backend_meta_device ( 219devs .data (),devs .size (),llama_meta_device_get_split_state ,& model -> get_split_state_ud ) 220 }); 221 }else { 222for (size_t i = 0 ;i < ggml_backend_dev_count ();++ i ) { 223ggml_backend_dev_t dev = ggml_backend_dev_get (i ); 224switch (ggml_backend_dev_type (dev )) { 225case GGML_BACKEND_DEVICE_TYPE_CPU : 226case GGML_BACKEND_DEVICE_TYPE_ACCEL : 227// skip CPU backends since they are handled separately 228break ; 229 230case GGML_BACKEND_DEVICE_TYPE_GPU : { 231ggml_backend_reg_t reg = ggml_backend_dev_backend_reg (dev ); 232if (ggml_backend_reg_name (reg )== std::string ("RPC" )) { 233rpc_servers .push_back ({false,dev }); 234 }else { 235// check if there is already a GPU with the same device id 236ggml_backend_dev_props props ; 237ggml_backend_dev_get_props (dev ,& props ); 238auto it = std::find_if (gpus .begin (),gpus .end (), [& props ](const llama_device & d ) { 239ggml_backend_dev_props d_props ; 240ggml_backend_dev_get_props (d .dev ,& d_props ); 241if (props .device_id && d_props .device_id ) { 242return strcmp (props .device_id ,d_props .device_id )== 0 ; 243 } 244return false; 245 }); 246 247if (it != gpus .end ()) { 248LLAMA_LOG_INFO ("%s: skipping device %s (%s) with id %s - already using device %s (%s) with the same id\n" , 249__func__ , 250ggml_backend_dev_name (dev ),ggml_backend_dev_description (dev ), 251props .device_id ?props .device_id :"unknown id" , 252ggml_backend_dev_name (it -> dev ),ggml_backend_dev_description (it -> dev )); 253 }else { 254gpus .push_back ({false,dev }); 255 } 256 } 257break ; 258 } 259 260case GGML_BACKEND_DEVICE_TYPE_IGPU : 261// igpus.empty() - workaround for integrated devices seen by multiple backends 262// ref: https://github.com/ggml-org/llama.cpp/pull/23897 263// ggml_backend_dev_backend_reg - allow devices of the same backend regardless if integrated 264// ref: https://github.com/ggml-org/llama.cpp/pull/23897#issuecomment-5264222997 265if (igpus .empty ()|| ggml_backend_dev_backend_reg (dev )== ggml_backend_dev_backend_reg (igpus .back ().dev )) { 266igpus .push_back ({false,dev }); 267 } 268break ; 269case GGML_BACKEND_DEVICE_TYPE_META : 270GGML_ABORT ("fatal error" ); 271 } 272 } 273 } 274 275// add RPC servers at the front of the list to minimize network transfers 276model -> devices .insert (model -> devices .begin (),rpc_servers .begin (),rpc_servers .end ()); 277 278// add GPUs 279model -> devices .insert (model -> devices .end (),gpus .begin (),gpus .end ()); 280 281// add integrated GPUs only if no discrete GPUs were found 282// (RPC servers do not count, otherwise the local iGPU would be dropped on iGPU+RPC setups) 283if (gpus .empty ()) { 284model -> devices .insert (model -> devices .end (),igpus .begin (),igpus .end ()); 285 } 286 } 287 288// if using single GPU mode, remove all except the main GPU 289if (params .split_mode == LLAMA_SPLIT_MODE_NONE && !model -> devices .empty ()) { 290if (params .main_gpu < 0 ) { 291model -> devices .clear (); 292 }else { 293if (params .main_gpu >= (int )model -> devices .size ()) { 294LLAMA_LOG_ERROR ("%s: invalid value for main_gpu: %d (available devices: %zu)\n" ,__func__ ,params .main_gpu ,model -> devices .size ()); 295return false; 296 } 297llama_device main_gpu = model -> devices [params .main_gpu ]; 298model -> devices .clear (); 299model -> devices .push_back (main_gpu ); 300 } 301 } 302 303for (const auto & dev :model -> devices ) { 304ggml_backend_dev_props props ; 305ggml_backend_dev_get_props (dev .dev ,& props ); 306LLAMA_LOG_INFO ("%s: using device %s (%s) (%s) - %zu MiB free\n" ,__func__ , 307ggml_backend_dev_name (dev .dev ),ggml_backend_dev_description (dev .dev ), 308props .device_id ?props .device_id :"unknown id" , 309props .memory_free /1024 /1024 ); 310 } 311 312return true; 313} 314 315// Returns 0 on success, -1 on error, and -2 on cancellation via llama_progress_callback 316static std::pair < int ,llama_model *> llama_model_load (struct gguf_context * metadata ,llama_model_set_tensor_data_t set_tensor_data ,void * set_tensor_data_ud , 317const std::string & fname , std::vector < std::string > & splits ,FILE * file ,llama_model_params & params ) { 318try { 319llama_model_loader ml (metadata ,set_tensor_data ,set_tensor_data_ud ,fname ,splits ,file ,params .load_mode , 320params .check_tensors ,params .no_alloc ,params .load_mtp ,params .kv_overrides ,params .tensor_buft_overrides ); 321 322ml .lazy .mode = params .lazy_mode ; 323 324ml .print_info (); 325 std::unique_ptr < llama_model > model_ptr (llama_model_create (ml ,params )); 326 327bool ok = llama_prepare_model_devices (params ,model_ptr .get ()); 328if (!ok ) { 329return {-1 ,nullptr }; 330 } 331 332auto * model = dynamic_cast < llama_model_base *> (model_ptr .get ()); 333if (model == nullptr ) { 334GGML_ABORT ("fatal error: model does not implement llama_model_base" ); 335 } 336 337// loading time will be recalculated after the first eval, so 338// we take page faults deferred by mmap() into consideration 339model -> t_load_us = 0 ; 340time_meas tm (model -> t_load_us ); 341 342model -> t_start_us = tm .t_start_us ; 343 344model -> hparams .vocab_only = params .vocab_only ; 345model -> hparams .no_alloc = params .no_alloc ; 346 347try { 348model -> load_hparams (ml ); 349 }catch (const std::exception & e ) { 350throw std::runtime_error ("error loading model hyperparameters: " + std::string (e .what ())); 351 } 352if (model -> arch == LLM_ARCH_CLIP ) { 353throw std::runtime_error ("CLIP cannot be used as main model, use it with --mmproj instead" ); 354 } 355try { 356model -> load_vocab (ml ); 357 }catch (const std::exception & e ) { 358throw std::runtime_error ("error loading model vocabulary: " + std::string (e .what ())); 359 } 360 361model -> load_stats (ml ); 362model -> print_info (); 363 364if (params .vocab_only ) { 365LLAMA_LOG_INFO ("%s: vocab only - skipping tensors\n" ,__func__ ); 366return {0 ,model_ptr .release ()}; 367 } 368 369if (!model -> load_tensors (ml )) { 370return {-2 ,nullptr }; 371 } 372 373return {0 ,model_ptr .release ()}; 374 }catch (const std::exception & err ) { 375LLAMA_LOG_ERROR ("%s: error loading model: %s\n" ,__func__ ,err .what ()); 376return {-1 ,nullptr }; 377 } 378} 379 380static struct llama_model * llama_model_load_from_file_impl ( 381struct gguf_context * metadata , 382llama_model_set_tensor_data_t set_tensor_data , 383void * set_tensor_data_ud , 384const std::string & path_model , 385 std::vector < std::string > & splits , 386FILE * file , 387struct llama_model_params params ) { 388 { 389int n_sources_defined = 0 ; 390if (metadata != nullptr ) { 391n_sources_defined ++ ; 392 } 393if (!path_model .empty ()) { 394n_sources_defined ++ ; 395 } 396if (file != nullptr ) { 397n_sources_defined ++ ; 398 } 399if (n_sources_defined != 1 ) { 400LLAMA_LOG_ERROR ("%s: exactly one out metadata, path_model, and file must be defined\n" ,__func__ ); 401return nullptr ; 402 } 403 } 404ggml_time_init (); 405 406if (!params .vocab_only && ggml_backend_reg_count ()== 0 ) { 407LLAMA_LOG_ERROR ("%s: no backends are loaded. hint: use ggml_backend_load() or ggml_backend_load_all() to load a backend before calling this function\n" ,__func__ ); 408return nullptr ; 409 } 410 411unsigned cur_percentage = 0 ; 412if (params .progress_callback == NULL ) { 413params .progress_callback_user_data = & cur_percentage ; 414params .progress_callback = [](float progress ,void * ctx ) { 415unsigned * cur_percentage_p = (unsigned * )ctx ; 416unsigned percentage = (unsigned ) (100 * progress ); 417while (percentage > * cur_percentage_p ) { 418* cur_percentage_p = percentage ; 419LLAMA_LOG_CONT ("." ); 420if (percentage >=100 ) { 421LLAMA_LOG_CONT ("\n" ); 422 } 423 } 424return true; 425 }; 426 } 427 428const auto [status ,model ]= llama_model_load (metadata ,set_tensor_data ,set_tensor_data_ud ,path_model ,splits ,file ,params ); 429GGML_ASSERT (status <=0 ); 430if (status < 0 ) { 431if (status == -1 ) { 432LLAMA_LOG_ERROR ("%s: failed to load model\n" ,__func__ ); 433 }else if (status == -2 ) { 434LLAMA_LOG_INFO ("%s: cancelled model load\n" ,__func__ ); 435 } 436 437if (model ) { 438llama_model_free (model ); 439 } 440return nullptr ; 441 } 442 443return model ; 444} 445 446struct llama_model * llama_model_init_from_user ( 447struct gguf_context * metadata , 448llama_model_set_tensor_data_t set_tensor_data , 449void * set_tensor_data_ud , 450struct llama_model_params params ) { 451GGML_ASSERT (metadata != nullptr ); 452 std::string path_model ; 453 std::vector < std::string > splits = {}; 454params .load_mode = LLAMA_LOAD_MODE_NONE ; 455params .use_extra_bufts = false; 456return llama_model_load_from_file_impl (metadata ,set_tensor_data ,set_tensor_data_ud ,path_model ,splits ,/*file*/ nullptr ,params ); 457} 458// deprecated 459struct llama_model * llama_load_model_from_file ( 460const char * path_model , 461struct llama_model_params params ) { 462return llama_model_load_from_file (path_model ,params ); 463} 464 465struct llama_model * llama_model_load_from_file ( 466const char * path_model , 467struct llama_model_params params ) { 468 std::vector < std::string > splits = {}; 469return llama_model_load_from_file_impl (nullptr ,nullptr ,nullptr ,path_model ,splits ,/*file*/ nullptr ,params ); 470} 471 472struct llama_model * llama_model_load_from_splits ( 473const char ** paths , 474size_t n_paths , 475struct llama_model_params params ) { 476 std::vector < std::string > splits ; 477if (n_paths == 0 ) { 478LLAMA_LOG_ERROR ("%s: list of splits is empty\n" ,__func__ ); 479return nullptr ; 480 } 481splits .reserve (n_paths ); 482for (size_t i = 0 ;i < n_paths ;++ i ) { 483splits .push_back (paths [i ]); 484 } 485return llama_model_load_from_file_impl (nullptr ,nullptr ,nullptr ,splits .front (),splits ,/*file*/ nullptr ,params ); 486} 487 488struct llama_model * llama_model_load_from_file_ptr (FILE * file ,struct llama_model_params params ) { 489if (!file ) { 490LLAMA_LOG_ERROR ("%s: file is NULL\n" ,__func__ ); 491return nullptr ; 492 } 493 std::string path_model ; 494 std::vector < std::string > splits = {}; 495return llama_model_load_from_file_impl (nullptr ,nullptr ,nullptr ,path_model ,splits ,file ,params ); 496} 497 498void llama_model_save_to_file (const struct llama_model * model ,const char * path_model ) { 499llama_model_saver ms (model ); 500ms .add_kv_from_model (); 501ms .add_tensors_from_model (); 502ms .save (path_model ); 503} 504 505// 506// chat templates 507// 508 509int32_t llama_chat_apply_template ( 510const char * tmpl , 511const struct llama_chat_message * chat , 512size_t n_msg , 513bool add_ass , 514char * buf , 515int32_t length ) { 516const std::string curr_tmpl (tmpl == nullptr ?"chatml" :tmpl ); 517 518// format the chat to string 519 std::vector < const llama_chat_message *> chat_vec ; 520chat_vec .resize (n_msg ); 521for (size_t i = 0 ;i < n_msg ;i ++ ) { 522chat_vec [i ]= & chat [i ]; 523 } 524 525 std::string formatted_chat ; 526llm_chat_template detected_tmpl = llm_chat_detect_template (curr_tmpl ); 527if (detected_tmpl == LLM_CHAT_TEMPLATE_UNKNOWN ) { 528return -1 ; 529 } 530int32_t res = llm_chat_apply_template (detected_tmpl ,chat_vec ,formatted_chat ,add_ass ); 531if (res < 0 ) { 532return res ; 533 } 534if (buf && length > 0 ) { 535strncpy (buf ,formatted_chat .c_str (),length ); 536 } 537return res ; 538} 539 540// 541// model split 542// 543 544int32_t llama_split_path ( 545char * split_path , 546size_t maxlen , 547const char * path_prefix , 548int32_t split_no , 549int32_t split_count ) { 550 551static const char * const SPLIT_PATH_FORMAT = "%s-%05d-of-%05d.gguf" ; 552 553const int written = snprintf ( 554split_path , 555maxlen , 556SPLIT_PATH_FORMAT , 557path_prefix , 558split_no + 1 , 559split_count 560 ); 561 562if (written < 0 || (size_t )written >=maxlen ) { 563return 0 ; 564 } 565 566return (int32_t )written ; 567} 568 569int32_t llama_split_prefix ( 570char * split_prefix , 571size_t maxlen , 572const char * split_path , 573int32_t split_no , 574int32_t split_count ) { 575 576const std::string str_split_path (split_path ); 577 578char postfix [32 ]; 579snprintf (postfix ,sizeof (postfix ),"-%05d-of-%05d.gguf" ,split_no + 1 ,split_count ); 580 581const std::string str_postfix (postfix ); 582if (str_split_path .size () <=str_postfix .size ()) { 583return 0 ; 584 } 585 586const size_t size_prefix = str_split_path .size ()- str_postfix .size (); 587 588if (str_split_path .compare (size_prefix , std::string::npos ,str_postfix )== 0 ) { 589const size_t copy_len = std::min (size_prefix + 1 ,maxlen ); 590snprintf (split_prefix ,copy_len ,"%s" ,split_path ); 591 592return (int32_t )size_prefix ; 593 } 594 595return 0 ; 596} 597 598const char * llama_print_system_info (void ) { 599static std::string s ; 600s .clear ();// Clear the string, since it's static, otherwise it will accumulate data from previous calls. 601 602for (size_t i = 0 ;i < ggml_backend_reg_count ();i ++ ) { 603auto * reg = ggml_backend_reg_get (i ); 604auto * get_features_fn = (ggml_backend_get_features_t )ggml_backend_reg_get_proc_address (reg ,"ggml_backend_get_features" ); 605if (get_features_fn ) { 606ggml_backend_feature * features = get_features_fn (reg ); 607s += ggml_backend_reg_name (reg ); 608s += " : " ; 609for (;features -> name ;features ++ ) { 610s += features -> name ; 611s += " = " ; 612s += features -> value ; 613s += " | " ; 614 } 615 } 616 } 617 618return s .c_str (); 619} 620