okami.mom/strata
git clone https://git.nkp.pet/okami.mom/strata
b2de2641f
main
1#include "llama-context.h" 2 3#include "ggml.h" 4#include "llama-arch.h" 5#include "llama-graph.h" 6#include "llama-impl.h" 7#include "llama-batch.h" 8#include "llama-io.h" 9#include "llama-memory.h" 10#include "llama-mmap.h" 11#include "llama-model.h" 12#include "llama-ext.h" 13#include "llama-sampler.h" 14#include "llama.h" 15 16#include <cinttypes> 17#include <cmath> 18#include <cstring> 19#include <limits> 20#include <stdexcept> 21#include <string> 22 23// 24// llama_context 25// 26 27static llm_graph_type ctx_type_to_graph_type (llama_context_type ctx_type ) { 28switch (ctx_type ) { 29case LLAMA_CONTEXT_TYPE_DEFAULT :return LLM_GRAPH_TYPE_DEFAULT ; 30case LLAMA_CONTEXT_TYPE_MTP :return LLM_GRAPH_TYPE_DECODER_MTP ; 31 } 32throw std::runtime_error ("Unsupported ctx type" ); 33} 34 35struct llm_fused_op_probe { 36llm_fused_op op ; 37const char * name ; 38uint32_t n_tokens_per_seq ; 39}; 40 41static const llm_fused_op_probe llm_fused_op_flash_attn_probe = { 42/*.op =*/ LLM_FUSED_OP_FLASH_ATTN , 43/*.name =*/ "Flash Attention" , 44/*.n_tokens_per_seq =*/ 1 , 45}; 46 47static const llm_fused_op_probe llm_fused_op_gdn_ar_probe = { 48/*.op =*/ LLM_FUSED_OP_GDN_AR , 49/*.name =*/ "fused Gated Delta Net (autoregressive)" , 50/*.n_tokens_per_seq =*/ 1 , 51}; 52 53static const llm_fused_op_probe llm_fused_op_gdn_ch_probe = { 54/*.op =*/ LLM_FUSED_OP_GDN_CH , 55/*.name =*/ "fused Gated Delta Net (chunked)" , 56/*.n_tokens_per_seq =*/ 16 , 57}; 58 59static const llm_fused_op_probe llm_fused_op_lid_probe = { 60/*.op =*/ LLM_FUSED_OP_LIGHTNING_INDEXER , 61/*.name =*/ "Lightning Indexer" , 62/*.n_tokens_per_seq =*/ 1 , 63}; 64 65static const llm_fused_op_probe llm_fused_op_dsv4_hc_pre_probe = { 66/*.op =*/ LLM_FUSED_OP_DSV4_HC_PRE , 67/*.name =*/ "fused DeepSeek V4 HC pre" , 68/*.n_tokens_per_seq =*/ 1 , 69}; 70 71static const llm_fused_op_probe llm_fused_op_dsv4_hc_comb_probe = { 72/*.op =*/ LLM_FUSED_OP_DSV4_HC_COMB , 73/*.name =*/ "fused DeepSeek V4 HC comb" , 74/*.n_tokens_per_seq =*/ 1 , 75}; 76 77static const llm_fused_op_probe llm_fused_op_dsv4_hc_post_probe = { 78/*.op =*/ LLM_FUSED_OP_DSV4_HC_POST , 79/*.name =*/ "fused DeepSeek V4 HC post" , 80/*.n_tokens_per_seq =*/ 1 , 81}; 82 83llama_context::llama_context ( 84const llama_model & model , 85llama_context_params params ) : 86model (model ), 87cvec (std::make_unique < llama_adapter_cvec > ()), 88loras (std::make_unique < llama_adapter_loras > ()), 89balloc (std::make_unique < llama_batch_allocr > (model .hparams .n_pos_per_embd ())) { 90// TODO warning when creating llama_context with awkward ctx size that is not a power of 2, 91// may need to be backend-dependent 92LLAMA_LOG_INFO ("%s: constructing llama_context\n" ,__func__ ); 93 94t_start_us = model .t_start_us ; 95t_load_us = model .t_load_us ; 96 97const auto & hparams = model .hparams ; 98 99cparams .n_seq_max = std::max (1u ,params .n_seq_max ); 100if (cparams .n_seq_max > LLAMA_MAX_SEQ ) { 101throw std::runtime_error ("n_seq_max must be <= " + std::to_string (LLAMA_MAX_SEQ )); 102 } 103 104cparams .n_rs_seq = params .n_rs_seq ; 105if (cparams .n_rs_seq > 0 && !llm_arch_supports_rs_rollback (model .arch )) { 106LLAMA_LOG_DEBUG ("%s: n_rs_seq=%u requested but model does not support recurrent partial rollback; clamping to 0\n" , 107__func__ ,cparams .n_rs_seq ); 108cparams .n_rs_seq = 0 ; 109 } 110 111cparams .n_threads = params .n_threads ; 112cparams .n_threads_batch = params .n_threads_batch ; 113cparams .yarn_ext_factor = params .yarn_ext_factor >=0.0f ?params .yarn_ext_factor :hparams .yarn_ext_factor ; 114cparams .yarn_attn_factor = params .yarn_attn_factor >=0.0f ?params .yarn_attn_factor :hparams .yarn_attn_factor ; 115cparams .yarn_beta_fast = params .yarn_beta_fast >=0.0f ?params .yarn_beta_fast :hparams .yarn_beta_fast ; 116cparams .yarn_beta_slow = params .yarn_beta_slow >=0.0f ?params .yarn_beta_slow :hparams .yarn_beta_slow ; 117cparams .embeddings = params .embeddings ; 118cparams .embeddings_nextn = false; 119cparams .embeddings_nextn_masked = false; 120cparams .offload_kqv = params .offload_kqv ; 121cparams .no_perf = params .no_perf ; 122cparams .warmup = false; 123 124// +1: id n_layer() taps the output of the last layer ("input" of the head) 125cparams .embeddings_layer_inp .resize (hparams .n_layer ()+ 1 , false); 126embd_layer_inp .resize (hparams .n_layer ()+ 1 ); 127 128cparams .ctx_type = params .ctx_type ; 129cparams .rope_scaling_type = params .rope_scaling_type ; 130cparams .pooling_type = params .pooling_type ; 131 132cparams .n_ctx = params .n_ctx == 0 ?hparams .n_ctx_train :params .n_ctx ; 133cparams .rope_freq_base = params .rope_freq_base == 0.0f ?hparams .rope_freq_base_train :params .rope_freq_base ; 134cparams .rope_freq_scale = params .rope_freq_scale == 0.0f ?hparams .rope_freq_scale_train :params .rope_freq_scale ; 135 136cparams .n_ctx_orig_yarn = params .yarn_orig_ctx != 0 ?params .yarn_orig_ctx : 137hparams .n_ctx_orig_yarn != 0 ?hparams .n_ctx_orig_yarn : 138hparams .n_ctx_train ; 139 140cparams .cb_eval = params .cb_eval ; 141cparams .cb_eval_user_data = params .cb_eval_user_data ; 142 143cparams .ctx_other = nullptr ; 144 145// TODO: more generic 146if (model .arch == LLM_ARCH_GEMMA4_ASSISTANT ) { 147if (params .ctx_other == nullptr ) { 148// TODO: change from runtime_error to llama_exception to avoid printing error message 149throw std::runtime_error ("Gemma4Assistant requires ctx_other to be set (this warning is normal during memory fitting)" ); 150 } 151 152cparams .ctx_other = params .ctx_other ; 153 } 154 155if (model .arch == LLM_ARCH_EAGLE3 || model .arch == LLM_ARCH_DFLASH ) { 156if (model .tok_embd == nullptr || model .output == nullptr ) { 157if (params .ctx_other == nullptr ) { 158throw std::runtime_error (model .arch_name ()+ " requires ctx_other to be set (this warning is normal during memory fitting)" ); 159 } 160cparams .ctx_other = params .ctx_other ; 161 } 162 } 163 164if (cparams .rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED ) { 165cparams .rope_scaling_type = hparams .rope_scaling_type_train ; 166 } 167 168if (cparams .rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_NONE ) { 169cparams .rope_freq_scale = 1.0f ;// never scale if scaling type is none 170 } 171 172if (cparams .yarn_ext_factor < 0.0f ) {// negative indicates 'not set' 173cparams .yarn_ext_factor = cparams .rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN ?1.0f :0.0f ; 174 } 175 176if (cparams .yarn_ext_factor != 0 ) { 177static auto get_mscale = [](float scale ,float mscale ) { 178return scale <=1.0f ?1.0f : (0.1f * mscale * logf (scale )+ 1.0f ); 179 }; 180 181const float factor = 1.0f /cparams .rope_freq_scale ; 182 183// ref: https://github.com/huggingface/transformers/blob/6d00f6b0a5679c36510f203e4226e36f517c3032/src/transformers/modeling_rope_utils.py#L336-L348 184if (hparams .rope_yarn_log_mul != 0.0f ) { 185// note: here we assume `mscale == 1.0f` 186// TODO: start reading the actual value of mscale and handle the case where it is not 1.0f 187float mscale = 1.0f ; 188const float mscale_all_dims = hparams .rope_yarn_log_mul ; 189 190// [TAG_DEEPSEEK2_YARN_LOG_MUL_FIX] 191// special-case DEEPSEEK v2: 192// https://huggingface.co/deepseek-ai/DeepSeek-V2-Lite-Chat/blob/main/config.json#L42-L43 193if (model .arch == LLM_ARCH_DEEPSEEK2 && mscale_all_dims != 1.0f ) { 194mscale = mscale_all_dims ; 195 } 196 197cparams .yarn_attn_factor = get_mscale (factor ,mscale ) /get_mscale (factor ,mscale_all_dims ); 198 199LLAMA_LOG_WARN ("%s: setting new yarn_attn_factor = %.4f (mscale == %.1f, mscale_all_dim = %.1f)\n" , 200__func__ ,cparams .yarn_attn_factor ,mscale ,mscale_all_dims ); 201 }else { 202cparams .yarn_attn_factor = get_mscale (factor ,1.0f ); 203 } 204 205// when YARN is applied with yarn_ext_factor != 0.0f, we need to cancel this factor: 206// https://github.com/ggml-org/llama.cpp/blob/a81a569577cc38b32558958b048228150be63eae/ggml/src/ggml-cpu/ops.cpp#L5541-L5544 207// 208// ref: https://github.com/ggml-org/llama.cpp/discussions/7416 209// https://github.com/ggml-org/llama.cpp/pull/17945 210cparams .yarn_attn_factor *=1.0f / (1.0f + 0.1f * logf (factor )); 211 } 212 213cparams .yarn_attn_factor *=hparams .rope_attn_factor ; 214 215if (cparams .pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED ) { 216if (hparams .pooling_type == LLAMA_POOLING_TYPE_UNSPECIFIED ) { 217cparams .pooling_type = LLAMA_POOLING_TYPE_NONE ; 218 }else { 219cparams .pooling_type = hparams .pooling_type ; 220 } 221 } 222 223if (params .attention_type == LLAMA_ATTENTION_TYPE_UNSPECIFIED ) { 224cparams .causal_attn = hparams .causal_attn ; 225 }else { 226cparams .causal_attn = params .attention_type == LLAMA_ATTENTION_TYPE_CAUSAL ; 227 } 228 229cparams .flash_attn = params .flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED ; 230cparams .auto_fa = params .flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO ; 231 232cparams .fused_gdn_ar = true; 233cparams .fused_gdn_ch = true; 234cparams .auto_fgdn = false; 235 236cparams .fused_lid = true; 237cparams .auto_flid = false; 238 239cparams .fused_dsv4_hc_pre = true; 240cparams .fused_dsv4_hc_comb = true; 241cparams .fused_dsv4_hc_post = true; 242cparams .auto_fhc = true; 243 244// with causal attention, the batch size is limited by the context size 245cparams .n_batch = cparams .causal_attn ? std::min (cparams .n_ctx ,params .n_batch ) :params .n_batch ; 246 247cparams .n_ubatch = std::min (cparams .n_batch ,params .n_ubatch == 0 ?params .n_batch :params .n_ubatch ); 248 249cparams .n_outputs_max = params .n_outputs_max == 0 || llama_model_has_encoder (& model ) ?cparams .n_batch :params .n_outputs_max ; 250cparams .n_outputs_max_per_seq = params .n_outputs_max_per_seq == 0 ? 251cparams .n_outputs_max : std::min (params .n_outputs_max_per_seq ,cparams .n_outputs_max ); 252 253// Initialize backend samplers here so they are part of the sampling graph 254// before the reserve passes run later in this function. This avoids a later 255// re-reserve when graph nodes change. 256if (params .samplers != nullptr && params .n_samplers > 0 ) { 257for (size_t i = 0 ;i < params .n_samplers ;++ i ) { 258const auto & config = params .samplers [i ]; 259 260if (llama_sampler_chain_get (config .sampler ,-1 )== nullptr ) { 261throw std::runtime_error ("the backend samplers must be of type llama_sampler_chain" ); 262 } 263 264if (set_sampler (config .seq_id ,config .sampler )) { 265const int n_samplers = llama_sampler_chain_n (config .sampler ); 266 267LLAMA_LOG_INFO ("%s: setting backend sampler for seq_id %d (n = %d)\n" ,__func__ ,config .seq_id ,n_samplers ); 268 } 269 } 270 } 271 272cparams .op_offload = params .op_offload ; 273cparams .kv_unified = params .kv_unified ; 274 275// initialized later 276cparams .pipeline_parallel = false; 277 278 { 279const char * LLAMA_GRAPH_REUSE_DISABLE = getenv ("LLAMA_GRAPH_REUSE_DISABLE" ); 280graph_reuse_disable = LLAMA_GRAPH_REUSE_DISABLE ? (atoi (LLAMA_GRAPH_REUSE_DISABLE )!= 0 ) :graph_reuse_disable ; 281 282if (graph_reuse_disable ) { 283LLAMA_LOG_WARN ("%s: graph reuse disabled\n" ,__func__ ); 284 } 285 } 286 287// ref: https://github.com/ggml-org/llama.cpp/pull/17046#discussion_r2503085732 288cparams .n_ctx = GGML_PAD (cparams .n_ctx ,256 ); 289 290if (cparams .kv_unified ) { 291cparams .n_ctx_seq = cparams .n_ctx ; 292 }else { 293cparams .n_ctx_seq = cparams .n_ctx /cparams .n_seq_max ; 294cparams .n_ctx_seq = GGML_PAD (cparams .n_ctx_seq ,256 ); 295 296if (cparams .n_ctx_seq == 0 ) { 297throw std::runtime_error ("n_ctx_seq == 0" ); 298 } 299 300if (cparams .n_ctx != cparams .n_ctx_seq * cparams .n_seq_max ) { 301cparams .n_ctx = cparams .n_ctx_seq * cparams .n_seq_max ; 302LLAMA_LOG_WARN ("%s: n_ctx is not divisible by n_seq_max - rounding down to %u\n" ,__func__ ,cparams .n_ctx ); 303 } 304 } 305 306LLAMA_LOG_INFO ("%s: n_seq_max = %u\n" ,__func__ ,cparams .n_seq_max ); 307LLAMA_LOG_INFO ("%s: n_ctx = %u\n" ,__func__ ,cparams .n_ctx ); 308LLAMA_LOG_INFO ("%s: n_ctx_seq = %u\n" ,__func__ ,cparams .n_ctx_seq ); 309LLAMA_LOG_INFO ("%s: n_batch = %u\n" ,__func__ ,cparams .n_batch ); 310LLAMA_LOG_INFO ("%s: n_ubatch = %u\n" ,__func__ ,cparams .n_ubatch ); 311LLAMA_LOG_INFO ("%s: causal_attn = %d\n" ,__func__ ,cparams .causal_attn ); 312LLAMA_LOG_INFO ("%s: flash_attn = %s\n" ,__func__ ,llama_flash_attn_type_name (params .flash_attn_type )); 313LLAMA_LOG_INFO ("%s: kv_unified = %s\n" ,__func__ ,cparams .kv_unified ?"true" :"false" ); 314LLAMA_LOG_INFO ("%s: freq_base = %.1f\n" ,__func__ ,cparams .rope_freq_base ); 315LLAMA_LOG_INFO ("%s: freq_scale = %g\n" ,__func__ ,cparams .rope_freq_scale ); 316LLAMA_LOG_INFO ("%s: n_rs_seq = %u\n" ,__func__ ,cparams .n_rs_seq ); 317LLAMA_LOG_INFO ("%s: n_outputs_max = %u\n" ,__func__ ,cparams .n_outputs_max ); 318LLAMA_LOG_INFO ("%s: n_outputs_max_per_seq = %u\n" ,__func__ ,cparams .n_outputs_max_per_seq ); 319 320if (cparams .n_ctx_seq < hparams .n_ctx_train ) { 321LLAMA_LOG_INFO ("%s: n_ctx_seq (%u) < n_ctx_train (%u) -- the full capacity of the model will not be utilized\n" , 322__func__ ,cparams .n_ctx_seq ,hparams .n_ctx_train ); 323 } 324 325if (cparams .n_ctx_seq > hparams .n_ctx_train ) { 326LLAMA_LOG_WARN ("%s: n_ctx_seq (%u) > n_ctx_train (%u) -- possible training context overflow\n" , 327__func__ ,cparams .n_ctx_seq ,hparams .n_ctx_train ); 328 } 329 330if (!hparams .vocab_only ) { 331// GPU backends 332for (const auto & dev :model .devices ) { 333ggml_backend_t backend = ggml_backend_dev_init (dev .dev ,nullptr ); 334if (backend == nullptr ) { 335throw std::runtime_error (format ("failed to initialize %s backend" ,ggml_backend_dev_name (dev .dev ))); 336 } 337backends .emplace_back (backend ); 338 } 339 340// add ACCEL backends (such as BLAS) 341for (size_t i = 0 ;i < ggml_backend_dev_count ();++ i ) { 342ggml_backend_dev_t dev = ggml_backend_dev_get (i ); 343if (ggml_backend_dev_type (dev )== GGML_BACKEND_DEVICE_TYPE_ACCEL ) { 344ggml_backend_t backend = ggml_backend_dev_init (dev ,nullptr ); 345if (backend == nullptr ) { 346throw std::runtime_error (format ("failed to initialize %s backend" ,ggml_backend_dev_name (dev ))); 347 } 348backends .emplace_back (backend ); 349 } 350 } 351 352// add CPU backend 353backend_cpu = ggml_backend_init_by_type (GGML_BACKEND_DEVICE_TYPE_CPU ,nullptr ); 354if (backend_cpu == nullptr ) { 355throw std::runtime_error ("failed to initialize CPU backend" ); 356 } 357backends .emplace_back (backend_cpu ); 358 359// create a list of the set_n_threads functions in the backends 360for (auto & backend :backends ) { 361ggml_backend_dev_t dev = ggml_backend_get_device (backend .get ()); 362ggml_backend_reg_t reg = dev ?ggml_backend_dev_backend_reg (dev ) :nullptr ; 363if (reg ) { 364auto ggml_backend_set_n_threads_fn = (ggml_backend_set_n_threads_t )ggml_backend_reg_get_proc_address (reg ,"ggml_backend_set_n_threads" ); 365if (ggml_backend_set_n_threads_fn ) { 366set_n_threads_fns .emplace_back (backend .get (),ggml_backend_set_n_threads_fn ); 367 } 368 } 369 } 370 371llama_set_abort_callback (this ,params .abort_callback ,params .abort_callback_data ); 372 373// graph outputs buffer 374 { 375if (output_reserve (params .n_seq_max )< params .n_seq_max ) { 376throw std::runtime_error ("failed to reserve initial output buffer" ); 377 } 378 379LLAMA_LOG_INFO ("%s: %10s output buffer size = %8.2f MiB\n" ,__func__ , 380ggml_backend_buffer_name (buf_output .get ()), 381ggml_backend_buffer_get_size (buf_output .get ()) /1024.0 /1024.0 ); 382 } 383 } 384 385// init the memory module 386if (!hparams .vocab_only ) { 387llama_memory_params params_mem = { 388/*.type_k =*/ params .type_k , 389/*.type_v =*/ params .type_v , 390/*.swa_full =*/ params .swa_full , 391/*.ctx_type =*/ cparams .ctx_type , 392/*.mem_other =*/ llama_get_memory (cparams .ctx_other ), 393 }; 394 395memory .reset (model .create_memory (params_mem ,cparams )); 396 } 397 398// init backends 399if (!hparams .vocab_only ) { 400LLAMA_LOG_DEBUG ("%s: enumerating backends\n" ,__func__ ); 401 402backend_buft .clear (); 403backend_ptrs .clear (); 404backend_buf_exp_size .clear (); 405 406for (auto & backend :backends ) { 407auto * buft = ggml_backend_get_default_buffer_type (backend .get ()); 408auto backend_type = ggml_backend_dev_type (ggml_backend_get_device (backend .get ())); 409 410if (backend_type == GGML_BACKEND_DEVICE_TYPE_CPU && !model .devices .empty ()) { 411// use the host buffer of the first device CPU for faster transfer of the intermediate state 412const auto & dev = model .devices [0 ]; 413auto * host_buft = ggml_backend_dev_host_buffer_type (dev .dev ); 414if (host_buft ) { 415buft = host_buft ; 416 } 417 } 418 419backend_buft .push_back (buft ); 420backend_ptrs .push_back (backend .get ()); 421backend_buf_exp_size .push_back (0 ); 422 } 423 424LLAMA_LOG_DEBUG ("%s: backend_ptrs.size() = %zu\n" ,__func__ ,backend_ptrs .size ()); 425 426// TODO: move these checks to ggml_backend_sched 427// enabling pipeline parallelism in the scheduler increases memory usage, so it is only done when necessary 428bool pipeline_parallel = 429model .n_devices ()> 1 && 430model .n_gpu_layers ()> model .hparams .n_layer_all && 431model .split_mode ()== LLAMA_SPLIT_MODE_LAYER && 432cparams .offload_kqv && 433 !model .has_tensor_overrides (); 434 435// pipeline parallelism requires support for async compute and events in all devices 436if (pipeline_parallel ) { 437for (auto & backend :backends ) { 438auto dev_type = ggml_backend_dev_type (ggml_backend_get_device (backend .get ())); 439if (dev_type == GGML_BACKEND_DEVICE_TYPE_CPU ) { 440// ignore CPU backend 441// TODO: should we ignore ACCEL types too? 442continue ; 443 } 444auto * dev = ggml_backend_get_device (backend .get ()); 445ggml_backend_dev_props props ; 446ggml_backend_dev_get_props (dev ,& props ); 447if (!props .caps .async || !props .caps .events ) { 448// device does not support async compute or events 449pipeline_parallel = false; 450break ; 451 } 452 } 453 } 454 455cparams .pipeline_parallel = pipeline_parallel ; 456 457if (cparams .pipeline_parallel ) { 458LLAMA_LOG_INFO ("%s: pipeline parallelism enabled\n" ,__func__ ); 459 } 460 461sched_reserve (); 462 463if (!cparams .flash_attn ) { 464if (ggml_is_quantized (params .type_v )) { 465throw std::runtime_error ("quantized V cache was requested, but this requires Flash Attention" ); 466 } 467 } 468 } 469 470// Initialize the full vocabulary token ids for backend samplers. 471 { 472const int n_vocab = model .vocab .n_tokens (); 473 474sampling .token_ids_full_vocab .resize (n_vocab ); 475for (int i = 0 ;i < n_vocab ;++ i ) { 476sampling .token_ids_full_vocab [i ]= i ; 477 } 478 } 479} 480 481llama_context::~llama_context () { 482// wait for any pending asynchronous copies into the output buffers before they are freed 483synchronize (); 484 485// when training, ggml_opt allocates extra buffers through the scheduler, so the sizes no longer match the expectation 486if (!model .hparams .no_alloc && !opt_ctx ) { 487for (size_t i = 0 ;i < backend_ptrs .size ();++ i ) { 488ggml_backend_t backend = backend_ptrs [i ]; 489ggml_backend_buffer_type_t buft = backend_buft [i ]; 490 491const size_t size_exp = backend_buf_exp_size [i ]; 492const size_t size_act = ggml_backend_sched_get_buffer_size (sched .get (),backend ); 493if (size_exp == size_act ) { 494LLAMA_LOG_DEBUG ("%s: %10s compute buffer size is %8.4f MiB, matches expectation of %8.4f MiB\n" , 495__func__ ,ggml_backend_buft_name (buft ),size_act / (1024.0 * 1024.0 ),size_exp / (1024.0 * 1024.0 )); 496 }else { 497LLAMA_LOG_WARN ("%s: %10s compute buffer size of %8.4f MiB, does not match expectation of %8.4f MiB\n" , 498__func__ ,ggml_backend_buft_name (buft ),size_act / (1024.0 * 1024.0 ),size_exp / (1024.0 * 1024.0 )); 499 } 500 } 501 } 502ggml_opt_free (opt_ctx ); 503} 504 505void llama_context::resolve_fused_ops (const llama_memory_context_i * mctx ,uint32_t n_seqs ) { 506const char * func = __func__ ; 507auto resolve = [& ](const llm_fused_op_probe & probe ,bool & enabled ) { 508if (!enabled ) { 509return ; 510 } 511 512const uint32_t n_tokens_probe = probe .n_tokens_per_seq * n_seqs ; 513 514auto * gf = graph_reserve (n_tokens_probe ,n_seqs ,n_tokens_probe ,mctx , true); 515if (!gf ) { 516throw std::runtime_error (std::string ("failed to reserve graph for " )+ probe .name + " check" ); 517 } 518 519bool device_mismatch = false; 520for (const auto & node :get_gf_res_reserve ()-> get_fused_nodes ()) { 521if (node .op != probe .op ) { 522continue ; 523 } 524 525GGML_ASSERT (node .il >=0 ); 526 527ggml_backend_t backend_fused = ggml_backend_sched_get_tensor_backend (sched .get (),node .tensor ); 528ggml_backend_dev_t device_fused = backend_fused ?ggml_backend_get_device (backend_fused ) :nullptr ; 529 530// TODO: make this descriptor-specific; model.dev_layer() preserves the current behavior, 531// but is still wrong for cases like --no-kv-offload. 532ggml_backend_dev_t device_layer = model .dev_layer (node .il ); 533 534if (device_fused != device_layer ) { 535LLAMA_LOG_WARN ("%s: layer %d is assigned to device %s but %s " 536"is assigned to device %s (usually due to missing support)\n" , 537func ,node .il , 538device_layer ?ggml_backend_dev_name (device_layer ) :"none" , 539probe .name , 540device_fused ?ggml_backend_dev_name (device_fused ) :"none" ); 541device_mismatch = true; 542break ; 543 } 544 } 545 546if (device_mismatch ) { 547enabled = false; 548LLAMA_LOG_WARN ("%s: %s not supported, set to disabled\n" ,func ,probe .name ); 549 }else { 550enabled = true; 551LLAMA_LOG_INFO ("%s: %s enabled\n" ,func ,probe .name ); 552 } 553 }; 554 555if (cparams .auto_fa ) { 556resolve (llm_fused_op_flash_attn_probe ,cparams .flash_attn ); 557cparams .auto_fa = false; 558 } 559 560if (cparams .auto_fgdn ) { 561LLAMA_LOG_INFO ("%s: resolving fused Gated Delta Net support:\n" ,func ); 562resolve (llm_fused_op_gdn_ar_probe ,cparams .fused_gdn_ar ); 563resolve (llm_fused_op_gdn_ch_probe ,cparams .fused_gdn_ch ); 564cparams .auto_fgdn = false; 565 } 566 567if (cparams .auto_flid ) { 568LLAMA_LOG_INFO ("%s: resolving fused Lightning Indexer support:\n" ,func ); 569resolve (llm_fused_op_lid_probe ,cparams .fused_lid ); 570cparams .auto_flid = false; 571 } 572 573if (cparams .auto_fhc ) { 574LLAMA_LOG_INFO ("%s: resolving fused DeepSeek V4 HC support:\n" ,func ); 575resolve (llm_fused_op_dsv4_hc_pre_probe ,cparams .fused_dsv4_hc_pre ); 576resolve (llm_fused_op_dsv4_hc_comb_probe ,cparams .fused_dsv4_hc_comb ); 577resolve (llm_fused_op_dsv4_hc_post_probe ,cparams .fused_dsv4_hc_post ); 578cparams .auto_fhc = false; 579 } 580} 581 582void llama_context::sched_reserve () { 583if (!sched_need_reserve ) { 584return ; 585 } 586 587sched_need_reserve = false; 588 589LLAMA_LOG_INFO ("%s: reserving ...\n" ,__func__ ); 590 591synchronize (); 592 593const int64_t t_start_us = ggml_time_us (); 594 595const uint32_t n_seqs = cparams .n_seq_max ; 596const uint32_t n_tokens = std::min (cparams .n_ctx ,cparams .n_ubatch ); 597 598const size_t max_nodes = this -> graph_max_nodes (n_tokens ); 599 600LLAMA_LOG_DEBUG ("%s: max_nodes = %zu\n" ,__func__ ,max_nodes ); 601 602for (auto & res :gf_res_prev ) { 603res .reset (); 604 } 605gf_res_reserve .reset (new llm_graph_result (max_nodes )); 606gf_res_prev_active = nullptr ; 607 608sched .reset (ggml_backend_sched_new (backend_ptrs .data (),backend_buft .data (),backend_ptrs .size (),max_nodes ,cparams .pipeline_parallel ,cparams .op_offload )); 609 610llama_memory_context_ptr mctx ; 611if (memory ) { 612LLAMA_LOG_DEBUG ("%s: reserving full memory module\n" ,__func__ ); 613mctx = memory -> init_full (); 614if (!mctx ) { 615throw std::runtime_error ("failed to initialize memory module" ); 616 } 617 } 618 619// avoid reserving graphs with zero outputs - assume one output per sequence 620const int n_outputs = n_seqs ; 621 622LLAMA_LOG_DEBUG ("%s: worst-case: n_tokens = %d, n_seqs = %d, n_outputs = %d\n" ,__func__ ,n_tokens ,n_seqs ,n_outputs ); 623 624resolve_fused_ops (mctx .get (),n_seqs ); 625 626// reserve worst-case graph 627int n_splits_pp = -1 ; 628int n_nodes_pp = -1 ; 629 630int n_splits_tg = -1 ; 631int n_nodes_tg = -1 ; 632 633const uint32_t n_outputs_pp = std::min (n_tokens ,cparams .n_outputs_max ); 634 635// reserve pp (prompt processing) graph first so that buffers are only allocated once 636 { 637auto * gf = graph_reserve (n_tokens ,n_seqs ,n_outputs_pp ,mctx .get (), 638model .hparams .no_alloc ,model .hparams .no_alloc ?backend_buf_exp_size .data () :nullptr ); 639if (!gf ) { 640if (cparams .pipeline_parallel ) { 641LLAMA_LOG_WARN ("%s: compute buffer allocation failed, retrying without pipeline parallelism\n" ,__func__ ); 642cparams .pipeline_parallel = false; 643sched .reset (ggml_backend_sched_new (backend_ptrs .data (),backend_buft .data (),backend_ptrs .size (),max_nodes , false,cparams .op_offload )); 644gf = graph_reserve (n_tokens ,n_seqs ,n_outputs_pp ,mctx .get ()); 645 } 646if (!gf ) { 647throw std::runtime_error ("failed to allocate compute pp buffers" ); 648 } 649 } 650 651n_splits_pp = ggml_backend_sched_get_n_splits (sched .get ()); 652n_nodes_pp = ggml_graph_n_nodes (gf ); 653 } 654 655// reserve with tg (token generation) graph to get the number of splits and nodes 656 { 657auto * gf = graph_reserve (n_seqs ,n_seqs ,n_seqs ,mctx .get (),model .hparams .no_alloc ); 658if (!gf ) { 659throw std::runtime_error ("failed to allocate compute tg buffers" ); 660 } 661 662n_splits_tg = ggml_backend_sched_get_n_splits (sched .get ()); 663n_nodes_tg = ggml_graph_n_nodes (gf ); 664 } 665 666// reserve again with pp graph to avoid ggml-alloc reallocations during inference 667 { 668// TODO: the worst case graph is not always reached for `n_seqs > 1` 669// need to implement a more robust mechanism that tries a few different inputs and analyzes the results 670ggml_cgraph * gf = nullptr ; 671switch (model .arch ) { 672case LLM_ARCH_KIMI_LINEAR : 673case LLM_ARCH_MINIMAX_01 : 674// [TAG_RESERVE_DIAG_DECAY] 675// the `inp_diag_decay` tensor size scales with `n_seq_tokens^2` which 676// makes `n_seqs == 1` use more memory for the compute graph compared to `n_seqs > 1` 677gf = graph_reserve (n_tokens ,1 ,n_outputs_pp ,mctx .get (),model .hparams .no_alloc ); 678break ; 679default : 680gf = graph_reserve (n_tokens ,n_seqs ,n_outputs_pp ,mctx .get (),model .hparams .no_alloc ); 681 }; 682 683if (!gf ) { 684throw std::runtime_error ("failed to allocate compute pp buffers" ); 685 } 686 } 687 688for (size_t i = 0 ;i < backend_ptrs .size ();++ i ) { 689ggml_backend_t backend = backend_ptrs [i ]; 690ggml_backend_buffer_type_t buft = backend_buft [i ]; 691if (!model .hparams .no_alloc ) { 692backend_buf_exp_size [i ]= ggml_backend_sched_get_buffer_size (sched .get (),backend ); 693 } 694if (backend_buf_exp_size [i ]> 1 ) { 695LLAMA_LOG_INFO ("%s: %10s compute buffer size = %8.2f MiB\n" ,__func__ , 696ggml_backend_buft_name (buft ), 697backend_buf_exp_size [i ] /1024.0 /1024.0 ); 698 } 699 } 700 701if (n_nodes_pp == n_nodes_tg ) { 702LLAMA_LOG_INFO ("%s: graph nodes = %d\n" ,__func__ ,n_nodes_pp ); 703 }else { 704LLAMA_LOG_INFO ("%s: graph nodes = %d (with bs=%d), %d (with bs=1)\n" ,__func__ ,n_nodes_pp ,n_tokens ,n_nodes_tg ); 705 } 706 707if (n_splits_pp == n_splits_tg ) { 708LLAMA_LOG_INFO ("%s: graph splits = %d\n" ,__func__ ,n_splits_pp ); 709 }else { 710LLAMA_LOG_INFO ("%s: graph splits = %d (with bs=%d), %d (with bs=1)\n" ,__func__ ,n_splits_pp ,n_tokens ,n_splits_tg ); 711 } 712 713const int64_t t_end_us = ggml_time_us (); 714 715LLAMA_LOG_INFO ("%s: reserve took %.2f ms, sched copies = %d\n" , 716__func__ , (t_end_us - t_start_us )/1000.0 ,ggml_backend_sched_get_n_copies (sched .get ())); 717} 718 719void llama_context::synchronize () { 720if (!sched ) { 721return ; 722 } 723 724ggml_backend_sched_synchronize (sched .get ()); 725 726// FIXME: if multiple single tokens are evaluated without a synchronization, 727// the stats will be added to the prompt evaluation stats 728// this should only happen when using batch size 1 to evaluate a batch 729 730// add the evaluation to the stats 731if (n_queued_tokens == 1 ) { 732if (!cparams .no_perf ) { 733t_eval_us += ggml_time_us ()- t_compute_start_us ; 734 } 735n_eval ++ ; 736 }else if (n_queued_tokens > 1 ) { 737if (!cparams .no_perf ) { 738t_p_eval_us += ggml_time_us ()- t_compute_start_us ; 739 } 740n_p_eval += n_queued_tokens ; 741 } 742 743// get a more accurate load time, upon first eval 744if (n_queued_tokens > 0 && !has_evaluated_once ) { 745t_load_us = ggml_time_us ()- t_start_us ; 746has_evaluated_once = true; 747 } 748 749n_queued_tokens = 0 ; 750t_compute_start_us = 0 ; 751} 752 753const llama_model & llama_context::get_model ()const { 754return model ; 755} 756 757const llama_cparams & llama_context::get_cparams ()const { 758return cparams ; 759} 760 761ggml_backend_sched_t llama_context::get_sched ()const { 762return sched .get (); 763} 764 765uint32_t llama_context::n_ctx ()const { 766return cparams .n_ctx ; 767} 768 769uint32_t llama_context::n_ctx_seq ()const { 770return cparams .n_ctx_seq ; 771} 772 773uint32_t llama_context::n_batch ()const { 774return cparams .n_batch ; 775} 776 777uint32_t llama_context::n_ubatch ()const { 778return cparams .n_ubatch ; 779} 780 781uint32_t llama_context::n_seq_max ()const { 782return cparams .n_seq_max ; 783} 784 785uint32_t llama_context::n_threads ()const { 786return cparams .n_threads ; 787} 788 789uint32_t llama_context::n_threads_batch ()const { 790return cparams .n_threads_batch ; 791} 792 793llama_memory_t llama_context::get_memory ()const { 794return memory .get (); 795} 796 797bool llama_context::memory_update (bool optimize ) { 798if (!memory ) { 799return false; 800 } 801 802 { 803const auto mctx = memory -> init_update (this ,optimize ); 804switch (mctx -> get_status ()) { 805case LLAMA_MEMORY_STATUS_SUCCESS : 806 { 807// noop 808 }break ; 809case LLAMA_MEMORY_STATUS_NO_UPDATE : 810 { 811// no updates need to be performed 812return false; 813 } 814case LLAMA_MEMORY_STATUS_FAILED_PREPARE : 815case LLAMA_MEMORY_STATUS_FAILED_COMPUTE : 816 { 817LLAMA_LOG_ERROR ("%s: failed to prepare memory update\n" ,__func__ ); 818return false; 819 } 820 } 821 822// reset the previous graph results to make sure that they won't be reused 823// TODO: make mctx->apply() report if a graph reserve is needed, then reset graph results only if the memory module reset the scheduler 824for (auto & res :gf_res_prev ) { 825if (res ) { 826res -> reset (); 827 } 828 } 829gf_res_prev_active = nullptr ; 830 831if (!mctx -> apply ()) { 832LLAMA_LOG_ERROR ("%s: failed to apply memory update\n" ,__func__ ); 833 } 834 } 835 836// if the memory module did any computation, we have to reserve a new worst-case graph 837 { 838const auto mctx = memory -> init_full (); 839if (!mctx ) { 840throw std::runtime_error ("failed to initialize memory context" ); 841 } 842 843const uint32_t n_seqs = cparams .n_seq_max ; 844const uint32_t n_tokens = std::min (cparams .n_ctx ,cparams .n_ubatch ); 845 846const uint32_t n_outputs_max = std::min (n_tokens ,cparams .n_outputs_max ); 847 848auto * gf = graph_reserve (n_tokens ,n_seqs ,n_outputs_max ,mctx .get ()); 849if (!gf ) { 850LLAMA_LOG_ERROR ("%s: failed to reserve graph after the memory update\n" ,__func__ ); 851 } 852 } 853 854return true; 855} 856 857enum llama_pooling_type llama_context::pooling_type ()const { 858return cparams .pooling_type ; 859} 860 861float * llama_context::get_logits () { 862output_reorder (); 863 864return logits .data ; 865} 866 867int64_t llama_context::output_resolve_row (int32_t i )const { 868int64_t j = -1 ; 869 870// support negative indices (last output row) 871if (i < 0 ) { 872j = n_outputs + i ; 873if (j < 0 ) { 874throw std::runtime_error (format ("negative index out of range [0, %d)" ,n_outputs )); 875 } 876 }else if ((size_t )i >=output_ids .size ()) { 877throw std::runtime_error (format ("out of range [0, %zu)" ,output_ids .size ())); 878 }else { 879// use output_ids to translate the batch token index into a row number 880// that holds this token's data. 881j = output_ids [i ]; 882 } 883 884if (j < 0 ) { 885// the batch token was not configured to output anything 886throw std::runtime_error (format ("batch.logits[%d] != true" ,i )); 887 } 888 889if (j >=n_outputs ) { 890throw std::runtime_error (format ("corrupt output buffer (j=%" PRId64 ", n_outputs=%d)" ,j ,n_outputs )); 891 } 892 893return j ; 894} 895 896float * llama_context::get_logits_ith (int32_t i ) { 897output_reorder (); 898 899try { 900if (logits .data == nullptr ) { 901throw std::runtime_error ("no logits" ); 902 } 903 904const int64_t j = output_resolve_row (i ); 905return logits .data + j * model .vocab .n_tokens (); 906 }catch (const std::exception & err ) { 907LLAMA_LOG_ERROR ("%s: invalid logits id %d, reason: %s\n" ,__func__ ,i ,err .what ()); 908#ifndef NDEBUG 909GGML_ABORT ("fatal error" ); 910#else 911return nullptr ; 912#endif 913 } 914} 915 916float * llama_context::get_embeddings () { 917output_reorder (); 918 919return embd .data ; 920} 921 922llama_token * llama_context::get_sampled_tokens ()const { 923return sampling .sampled .data ; 924} 925 926float * llama_context::get_embeddings_ith (int32_t i ) { 927output_reorder (); 928 929try { 930if (embd .data == nullptr ) { 931throw std::runtime_error ("no embeddings" ); 932 } 933 934const int64_t j = output_resolve_row (i ); 935const uint32_t n_embd_out = model .hparams .n_embd_out (); 936return embd .data + j * n_embd_out ; 937 }catch (const std::exception & err ) { 938LLAMA_LOG_ERROR ("%s: invalid embeddings id %d, reason: %s\n" ,__func__ ,i ,err .what ()); 939#ifndef NDEBUG 940GGML_ABORT ("fatal error" ); 941#else 942return nullptr ; 943#endif 944 } 945} 946 947float * llama_context::get_embeddings_seq (llama_seq_id seq_id ) { 948auto it = embd_seq .find (seq_id ); 949if (it == embd_seq .end ()) { 950return nullptr ; 951 } 952 953return it -> second .data (); 954} 955 956float * llama_context::get_embeddings_nextn () { 957output_reorder (); 958 959return embd_nextn .data ; 960} 961 962float * llama_context::get_embeddings_nextn_ith (int32_t i ) { 963output_reorder (); 964 965try { 966if (embd_nextn .data == nullptr ) { 967throw std::runtime_error ("no nextn embeddings" ); 968 } 969 970const uint32_t n_embd = model .hparams .n_embd_out (); 971 972if (!cparams .embeddings_nextn_masked ) { 973// unmasked: nextn rows are stored densely, indexed by raw token position. 974if (i < 0 || (size_t )(i + 1 )* n_embd > embd_nextn .size ) { 975throw std::runtime_error (format ("out of range [0, %zu)" ,embd_nextn .size /n_embd )); 976 } 977return embd_nextn .data + (size_t )i * n_embd ; 978 } 979 980const int64_t j = output_resolve_row (i ); 981return embd_nextn .data + j * n_embd ; 982 }catch (const std::exception & err ) { 983LLAMA_LOG_ERROR ("%s: invalid nextn embeddings id %d, reason: %s\n" ,__func__ ,i ,err .what ()); 984#ifndef NDEBUG 985GGML_ABORT ("fatal error" ); 986#else 987return nullptr ; 988#endif 989 } 990} 991 992float * llama_context::get_embeddings_layer_inp (uint32_t lid ) { 993output_reorder (); 994 995GGML_ASSERT (lid < embd_layer_inp .size ()&& embd_layer_inp [lid ].has_data ()); 996 997return embd_layer_inp [lid ].data ; 998} 999 1000llama_token llama_context::get_sampled_token_ith (int32_t idx ) { 1001output_reorder (); 1002 1003if (!sampling .sampled .has_data ()) { 1004return LLAMA_TOKEN_NULL ; 1005 } 1006 1007try { 1008const int64_t row = output_resolve_row (idx ); 1009GGML_ASSERT (row < (int64_t )sampling .sampled .size ); 1010return sampling .sampled .data [row ]; 1011 }catch (const std::exception & err ) { 1012LLAMA_LOG_ERROR ("%s: invalid backend sampled token id %d, reason: %s\n" ,__func__ ,idx ,err .what ()); 1013return LLAMA_TOKEN_NULL ; 1014 } 1015} 1016 1017float * llama_context::get_sampled_probs_ith (int32_t idx ) { 1018output_reorder (); 1019 1020if (!sampling .probs .has_data ()) { 1021return nullptr ; 1022 } 1023 1024try { 1025const int64_t row = output_resolve_row (idx ); 1026if ((size_t )row >=sampling .probs_count .size ()|| sampling .probs_count [row ]== 0 ) { 1027return nullptr ; 1028 } 1029return sampling .probs .data + row * model .vocab .n_tokens (); 1030 }catch (const std::exception & err ) { 1031LLAMA_LOG_ERROR ("%s: invalid backend sampled probs id %d, reason: %s\n" ,__func__ ,idx ,err .what ()); 1032return nullptr ; 1033 } 1034} 1035 1036float * llama_context::get_sampled_logits_ith (int32_t idx ) { 1037output_reorder (); 1038 1039if (!sampling .logits .has_data ()) { 1040return nullptr ; 1041 } 1042 1043try { 1044const int64_t row = output_resolve_row (idx ); 1045if ((size_t )row >=sampling .logits_count .size ()|| sampling .logits_count [row ]== 0 ) { 1046return nullptr ; 1047 } 1048return sampling .logits .data + row * model .vocab .n_tokens (); 1049 }catch (const std::exception & err ) { 1050LLAMA_LOG_ERROR ("%s: invalid backend sampled logits id %d, reason: %s\n" ,__func__ ,idx ,err .what ()); 1051return nullptr ; 1052 } 1053} 1054 1055const llama_token * llama_context::get_sampled_candidates_ith (int32_t idx ) { 1056output_reorder (); 1057 1058try { 1059const int64_t row = output_resolve_row (idx ); 1060if (sampling .candidates .has_data ()&& 1061 (size_t )row < sampling .candidates_count .size ()&& 1062sampling .candidates_count [row ]> 0 ) { 1063return sampling .candidates .data + row * model .vocab .n_tokens (); 1064 } 1065 }catch (const std::exception & err ) { 1066// fallback to full vocab list 1067GGML_UNUSED (err ); 1068 } 1069 1070return sampling .token_ids_full_vocab .data (); 1071} 1072 1073size_t llama_context::get_sampled_candidates_count (int32_t idx ) { 1074output_reorder (); 1075 1076if (!sampling .candidates .has_data ()) { 1077return 0 ; 1078 } 1079 1080try { 1081const int64_t row = output_resolve_row (idx ); 1082if ((size_t )row >=sampling .candidates_count .size ()) { 1083return 0 ; 1084 } 1085return sampling .candidates_count [row ]; 1086 }catch (const std::exception & err ) { 1087LLAMA_LOG_ERROR ("%s: invalid backend sampled candidates count id %d, reason: %s\n" ,__func__ ,idx ,err .what ()); 1088return 0 ; 1089 } 1090} 1091 1092size_t llama_context::get_sampled_logits_count (int32_t idx ) { 1093output_reorder (); 1094 1095if (!sampling .logits .has_data ()) { 1096return model .vocab .n_tokens (); 1097 } 1098 1099try { 1100const int64_t row = output_resolve_row (idx ); 1101if ((size_t )row >=sampling .logits_count .size ()) { 1102return 0 ; 1103 } 1104return sampling .logits_count [row ]; 1105 }catch (const std::exception & err ) { 1106LLAMA_LOG_ERROR ("%s: invalid backend sampled logits count id %d, reason: %s\n" ,__func__ ,idx ,err .what ()); 1107return 0 ; 1108 } 1109} 1110 1111size_t llama_context::get_sampled_probs_count (int32_t idx ) { 1112output_reorder (); 1113 1114if (!sampling .probs .has_data ()) { 1115return 0 ; 1116 } 1117 1118try { 1119const int64_t row = output_resolve_row (idx ); 1120if ((size_t )row >=sampling .probs_count .size ()) { 1121return 0 ; 1122 } 1123return sampling .probs_count [row ]; 1124 }catch (const std::exception & err ) { 1125LLAMA_LOG_ERROR ("%s: invalid backend sampled probs count id %d, reason: %s\n" ,__func__ ,idx ,err .what ()); 1126return 0 ; 1127 } 1128} 1129 1130 1131void llama_context::attach_threadpool ( 1132ggml_threadpool_t threadpool , 1133ggml_threadpool_t threadpool_batch ) { 1134LLAMA_LOG_DEBUG ("%s: call\n" ,__func__ ); 1135 1136this -> threadpool = threadpool ; 1137this -> threadpool_batch = threadpool_batch ?threadpool_batch :threadpool ; 1138} 1139 1140void llama_context::detach_threadpool () { 1141LLAMA_LOG_DEBUG ("%s: call\n" ,__func__ ); 1142 1143this -> threadpool = nullptr ; 1144this -> threadpool_batch = nullptr ; 1145} 1146 1147void llama_context::set_n_threads (int32_t n_threads ,int32_t n_threads_batch ) { 1148LLAMA_LOG_DEBUG ("%s: n_threads = %d, n_threads_batch = %d\n" ,__func__ ,n_threads ,n_threads_batch ); 1149 1150cparams .n_threads = n_threads ; 1151cparams .n_threads_batch = n_threads_batch ; 1152} 1153 1154void llama_context::set_abort_callback (bool (* abort_callback )(void * data ),void * abort_callback_data ) { 1155LLAMA_LOG_DEBUG ("%s: call\n" ,__func__ ); 1156 1157this -> abort_callback = abort_callback ; 1158this -> abort_callback_data = abort_callback_data ; 1159 1160for (auto & backend :backends ) { 1161auto * reg = ggml_backend_dev_backend_reg (ggml_backend_get_device (backend .get ())); 1162if (reg ) { 1163auto * set_abort_callback_fn = (ggml_backend_set_abort_callback_t )ggml_backend_reg_get_proc_address (reg ,"ggml_backend_set_abort_callback" ); 1164if (set_abort_callback_fn ) { 1165set_abort_callback_fn (backend .get (),this -> abort_callback ,this -> abort_callback_data ); 1166 } 1167 } 1168 } 1169} 1170 1171void llama_context::set_embeddings (bool value ) { 1172LLAMA_LOG_DEBUG ("%s: value = %d\n" ,__func__ ,value ); 1173 1174cparams .embeddings = value ; 1175 1176// TODO: not sure yet if we want to reserve here 1177//sched_need_reserve = true; 1178} 1179 1180void llama_context::set_embeddings_nextn (bool value ,bool masked ) { 1181LLAMA_LOG_DEBUG ("%s: value = %d, masked = %d\n" ,__func__ ,value ,masked ); 1182 1183cparams .embeddings_nextn = value ; 1184cparams .embeddings_nextn_masked = masked ; 1185} 1186 1187void llama_context::set_embeddings_layer_inp (uint32_t lid ,bool enable ) { 1188LLAMA_LOG_DEBUG ("%s: lid = %d, enable = %d\n" ,__func__ ,lid ,enable ); 1189 1190GGML_ASSERT (lid <=model .hparams .n_layer ()); 1191 1192cparams .embeddings_layer_inp [lid ]= enable ; 1193 1194// note: without this reserve, the draft acceptance drops to zero. not sure why - this is unexpected 1195sched_need_reserve = true; 1196} 1197 1198void llama_context::set_nextn_layer_offset (int32_t offset ) { 1199cparams .nextn_layer_offset = offset ; 1200} 1201 1202void llama_context::set_causal_attn (bool value ) { 1203LLAMA_LOG_DEBUG ("%s: value = %d\n" ,__func__ ,value ); 1204 1205if (cparams .causal_attn == value ) { 1206return ; 1207 } 1208 1209cparams .causal_attn = value ; 1210 1211sched_need_reserve = true; 1212} 1213 1214void llama_context::set_warmup (bool value ) { 1215LLAMA_LOG_DEBUG ("%s: value = %d\n" ,__func__ ,value ); 1216 1217if (cparams .warmup == value ) { 1218return ; 1219 } 1220 1221cparams .warmup = value ; 1222 1223// warmups are usually with small batches, so no need to reserve 1224//sched_need_reserve = true; 1225} 1226 1227bool llama_context::set_sampler (llama_seq_id seq_id ,llama_sampler * sampler ) { 1228if (!sampler && sampling .samplers .count (seq_id )== 0 ) { 1229return true; 1230 } 1231 1232LLAMA_LOG_DEBUG ("%s: seq_id = %d, sampler = %p\n" ,__func__ , (int )seq_id , (void * )sampler ); 1233 1234if (sampler && model .split_mode ()== LLAMA_SPLIT_MODE_TENSOR ) { 1235static bool warned = false; 1236if (!warned ) { 1237LLAMA_LOG_WARN ("%s: backend sampling not supported with SPLIT_MODE_TENSOR; using CPU\n" ,__func__ ); 1238warned = true; 1239 } 1240if (sampling .samplers .count (seq_id )> 0 ) { 1241sched_need_reserve = true; 1242 } 1243sampling .samplers .erase (seq_id ); 1244return false; 1245 } 1246 1247const bool can_offload = 1248sampler && 1249sampler -> iface -> backend_init && 1250sampler -> iface -> backend_apply && 1251llama_sampler_chain_n (sampler )> 0 ; 1252 1253if (sampler && can_offload ) { 1254auto * buft = ggml_backend_dev_buffer_type (model .dev_output ()); 1255 1256sampler -> iface -> backend_init (sampler ,buft ,cparams .n_outputs_max_per_seq ); 1257 1258sampling .samplers [seq_id ]= sampler ; 1259 1260sched_need_reserve = true; 1261 1262return true; 1263 } 1264 1265if (sampler && !can_offload ) { 1266LLAMA_LOG_WARN ("%s: sampler '%s' for seq_id = %d, cannot be offloaded to the backend\n" ,__func__ ,llama_sampler_name (sampler ),seq_id ); 1267 1268if (sampling .samplers .count (seq_id )> 0 ) { 1269sched_need_reserve = true; 1270 } 1271 1272sampling .samplers .erase (seq_id ); 1273 1274return false; 1275 } 1276 1277sampling .samplers .erase (seq_id ); 1278 1279sched_need_reserve = true; 1280 1281return true; 1282} 1283 1284void llama_context::set_adapters_lora (llama_adapter_lora ** adapters ,size_t n_adapters ,float * scales ) { 1285LLAMA_LOG_DEBUG ("%s: adapters = %p\n" ,__func__ , (void * )adapters ); 1286 1287if (adapters_lora_are_same (adapters ,n_adapters ,scales )) { 1288return ; 1289 } 1290 1291loras .reset (new llama_adapter_loras ()); 1292 1293for (size_t i = 0 ;i < n_adapters ;i ++ ) { 1294if (scales [i ]!= 0.0f ) { 1295loras -> insert ({adapters [i ],scales [i ]}); 1296 } 1297 } 1298 1299sched_need_reserve = true; 1300} 1301 1302bool llama_context::adapters_lora_are_same (llama_adapter_lora ** adapters ,size_t n_adapters ,float * scales ) { 1303LLAMA_LOG_DEBUG ("%s: adapters = %p\n" ,__func__ , (void * )adapters ); 1304 1305// Adapters with a zero scale are never added to `loras`, so also ignore them for the comparison. 1306size_t n_non_zero = 0 ; 1307 1308for (size_t i = 0 ;i < n_adapters ;i ++ ) { 1309if (scales [i ]== 0.0f ) { 1310continue ; 1311 } 1312n_non_zero ++ ; 1313 1314auto it = loras -> find (adapters [i ]); 1315 1316if (it == loras -> end ()|| it -> second != scales [i ]) { 1317return false; 1318 } 1319 } 1320 1321if (n_non_zero != loras -> size ()) { 1322return false; 1323 } 1324 1325return true; 1326} 1327 1328bool llama_context::set_adapter_cvec ( 1329const float * data , 1330size_t len , 1331int32_t n_embd , 1332int32_t il_start , 1333int32_t il_end ) { 1334LLAMA_LOG_DEBUG ("%s: il_start = %d, il_end = %d\n" ,__func__ ,il_start ,il_end ); 1335 1336bool res = cvec -> apply (model ,data ,len ,n_embd ,il_start ,il_end ); 1337 1338sched_need_reserve = true; 1339 1340return res ; 1341} 1342 1343llm_graph_result * llama_context::process_ubatch (const llama_ubatch & ubatch ,llm_graph_type gtype ,llama_memory_context_i * mctx ,ggml_status & ret ) { 1344if (mctx && !mctx -> apply ()) { 1345LLAMA_LOG_ERROR ("%s: failed to apply memory context\n" ,__func__ ); 1346ret = GGML_STATUS_FAILED ; 1347return nullptr ; 1348 } 1349 1350auto * res = get_gf_res_prev (); 1351auto * gf = res -> get_gf (); 1352 1353// the new graph parameters 1354// in order to correctly reuse a graph, it's full topology has to be uniquely determined by these parameters 1355const auto gparams = graph_params (res ,ubatch ,mctx ,gtype ); 1356 1357if (!graph_reuse_disable && gf_res_prev_active == res && res -> can_reuse (gparams )) { 1358//LLAMA_LOG_DEBUG("%s: reusing previous graph\n", __func__); 1359 1360// with pipeline parallelism, the previous graph_compute_async may still be running 1361// on the GPU. we must synchronize before set_inputs to avoid overwriting input tensors 1362// that the previous compute is still reading. 1363if (cparams .pipeline_parallel ) { 1364ggml_backend_sched_synchronize (sched .get ()); 1365 } 1366 1367n_reused ++ ; 1368 }else { 1369gf_res_prev_active = nullptr ; 1370res -> reset (); 1371 1372ggml_backend_sched_reset (sched .get ()); 1373ggml_backend_sched_set_eval_callback (sched .get (),cparams .cb_eval ,cparams .cb_eval_user_data ); 1374 1375//const auto t_start_us = ggml_time_us(); 1376 1377gf = model .build_graph (gparams ); 1378 1379//LLAMA_LOG_INFO("graph build time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0); 1380 1381if (!gf ) { 1382LLAMA_LOG_ERROR ("%s: failed to initialize graph\n" ,__func__ ); 1383ret = GGML_STATUS_FAILED ; 1384return nullptr ; 1385 } 1386 1387if (!ggml_backend_sched_alloc_graph (sched .get (),gf )) { 1388LLAMA_LOG_ERROR ("%s: failed to allocate graph\n" ,__func__ ); 1389ret = GGML_STATUS_ALLOC_FAILED ; 1390return nullptr ; 1391 } 1392 1393gf_res_prev_active = res ; 1394 } 1395 1396// set the input data for the input tensors 1397 { 1398//const auto t_start_us = ggml_time_us(); 1399 1400// FIXME this call causes a crash if any model inputs were not used in the graph and were therefore not allocated 1401res -> set_inputs (& ubatch ); 1402 1403//LLAMA_LOG_INFO("graph set inputs time: %.3f ms\n", (ggml_time_us() - t_start_us)/1000.0); 1404 } 1405 1406const auto status = graph_compute (res -> get_gf (),ubatch .n_tokens > 1 ); 1407if (status != GGML_STATUS_SUCCESS ) { 1408LLAMA_LOG_ERROR ("%s: failed to compute graph, compute status: %d\n" ,__func__ ,status ); 1409ret = status ; 1410return nullptr ; 1411 } 1412 1413ret = GGML_STATUS_SUCCESS ; 1414 1415return res ; 1416} 1417 1418int llama_context::encode (const llama_batch & batch_inp ) { 1419// MTP hook batches carry both token (next-token id) and embd (h_nextn row), 1420// so accept either present rather than requiring exactly one. 1421GGML_ASSERT (batch_inp .token || batch_inp .embd ); 1422 1423if (batch_inp .n_tokens == 0 ) { 1424LLAMA_LOG_ERROR ("%s: n_tokens == 0\n" ,__func__ ); 1425return -1 ; 1426 } 1427 1428const auto & hparams = model .hparams ; 1429 1430// eagle3/DFlash: features as encoder input, and non-draft paths fall back to model's input dim 1431const int64_t n_embd = hparams .n_embd_inp_enc (); 1432const int64_t n_vocab = model .vocab .n_tokens (); 1433 1434// note: during encode, we always pass the full sequence starting from pos = 0 1435if (!balloc -> init (batch_inp ,model .vocab ,nullptr ,n_embd ,cparams .kv_unified ?LLAMA_MAX_SEQ :cparams .n_seq_max , true)) { 1436LLAMA_LOG_ERROR ("%s: failed to initialize batch\n" ,__func__ ); 1437return -1 ; 1438 } 1439 1440const uint32_t n_tokens = balloc -> get_n_tokens (); 1441 1442// [TAG_NO_CACHE_PAD] 1443// TODO: add new split mode where we pad the input sequences so that ubatch.equal_seqs == true 1444const llama_ubatch ubatch = balloc -> split_simple (n_tokens ); 1445 1446// micro-batching is not possible for non-causal encoding, so we process the batch in a single shot 1447GGML_ASSERT (cparams .n_ubatch >=n_tokens && "encoder requires n_ubatch >= n_tokens" ); 1448 1449// TODO: this clear of the buffer can easily be forgotten - need something better 1450// sync first so any in-flight async copies into embd_seq complete before it is freed 1451if (!embd_seq .empty ()) { 1452synchronize (); 1453 } 1454embd_seq .clear (); 1455 1456if (t_compute_start_us == 0 ) { 1457t_compute_start_us = ggml_time_us (); 1458 } 1459 1460sched_reserve (); 1461 1462n_queued_tokens += n_tokens ; 1463 1464// reserve output buffer 1465if (output_reserve (n_tokens )< n_tokens ) { 1466LLAMA_LOG_ERROR ("%s: could not reserve space for batch with %u outputs\n" ,__func__ ,n_tokens ); 1467return -2 ; 1468 }; 1469 1470for (uint32_t i = 0 ;i < n_tokens ;++ i ) { 1471output_ids [i ]= i ; 1472 } 1473 1474n_outputs = n_tokens ; 1475 1476const auto causal_attn_org = cparams .causal_attn ; 1477 1478// always use non-causal attention for encoder graphs 1479// TODO: this is a tmp solution until we have a proper way to support enc-dec models 1480// ref: https://github.com/ggml-org/llama.cpp/pull/12181#issuecomment-2730451223 1481cparams .causal_attn = false; 1482 1483ggml_status status ; 1484const auto * res = process_ubatch (ubatch ,LLM_GRAPH_TYPE_ENCODER ,nullptr ,status ); 1485 1486cparams .causal_attn = causal_attn_org ; 1487 1488if (!res ) { 1489switch (status ) { 1490case GGML_STATUS_ABORTED :return 2 ; 1491case GGML_STATUS_ALLOC_FAILED :return -2 ; 1492case GGML_STATUS_FAILED :return -3 ; 1493case GGML_STATUS_SUCCESS :GGML_ABORT ("should not happen" ); 1494 } 1495 } 1496 1497auto * t_logits = res -> get_logits (); 1498auto * t_embd = res -> get_embd_pooled () ?res -> get_embd_pooled () :res -> get_embd (); 1499auto * t_h_nextn = cparams .embeddings_nextn ?res -> get_h_nextn () :nullptr ; 1500 1501// extract logits 1502if (logits .data && t_logits ) { 1503ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend (sched .get (),t_logits ); 1504GGML_ASSERT (backend_res != nullptr ); 1505GGML_ASSERT (logits .data != nullptr ); 1506 1507ggml_backend_tensor_get_async (backend_res ,t_logits ,logits .data ,0 ,n_tokens * n_vocab * sizeof (float )); 1508 } 1509 1510// extract embeddings 1511if (embd .data && t_embd ) { 1512ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend (sched .get (),t_embd ); 1513GGML_ASSERT (backend_embd != nullptr ); 1514 1515switch (cparams .pooling_type ) { 1516case LLAMA_POOLING_TYPE_NONE : 1517 { 1518// extract token embeddings 1519GGML_ASSERT (embd .data != nullptr ); 1520const uint32_t n_embd_out = hparams .n_embd_out (); 1521 1522GGML_ASSERT (n_tokens * n_embd_out <= (int64_t )embd .size ); 1523ggml_backend_tensor_get_async (backend_embd ,t_embd ,embd .data ,0 ,n_tokens * n_embd_out * sizeof (float )); 1524 }break ; 1525case LLAMA_POOLING_TYPE_MEAN : 1526case LLAMA_POOLING_TYPE_CLS : 1527case LLAMA_POOLING_TYPE_LAST : 1528 { 1529// extract sequence embeddings 1530auto & embd_seq_out = embd_seq ; 1531 1532for (uint32_t s = 0 ;s < ubatch .n_seqs_unq ;++ s ) { 1533const llama_seq_id seq_id = ubatch .seq_id_unq [s ]; 1534const int32_t seq_idx = ubatch .seq_idx [seq_id ]; 1535 1536// use n_embd_out (not n_embd_inp) - the pooled embedding has the model's 1537// output dimension, which differs from input dimension for deepstack models (e.g. qwen3vl) 1538const uint32_t n_embd_out = hparams .n_embd_out (); 1539embd_seq_out [seq_id ].resize (n_embd_out ); 1540ggml_backend_tensor_get_async (backend_embd ,t_embd ,embd_seq_out [seq_id ].data (), (n_embd_out * seq_idx )* sizeof (float ),n_embd_out * sizeof (float )); 1541 } 1542 }break ; 1543case LLAMA_POOLING_TYPE_RANK : 1544 { 1545// extract the rerank score - n_cls_out floats per sequence 1546auto & embd_seq_out = embd_seq ; 1547 1548const uint32_t n_cls_out = hparams .n_cls_out ; 1549 1550for (uint32_t s = 0 ;s < ubatch .n_seqs_unq ;++ s ) { 1551const llama_seq_id seq_id = ubatch .seq_id_unq [s ]; 1552const int32_t seq_idx = ubatch .seq_idx [seq_id ]; 1553 1554embd_seq_out [seq_id ].resize (n_cls_out ); 1555ggml_backend_tensor_get_async (backend_embd ,t_embd ,embd_seq_out [seq_id ].data (), (n_cls_out * seq_idx )* sizeof (float ),n_cls_out * sizeof (float )); 1556 } 1557 }break ; 1558case LLAMA_POOLING_TYPE_UNSPECIFIED : 1559 { 1560GGML_ABORT ("unknown pooling type" ); 1561 } 1562 } 1563 } 1564 1565// extract nextn embeddings (hidden state before the final output norm) 1566if (embd_nextn .data && t_h_nextn && cparams .pooling_type == LLAMA_POOLING_TYPE_NONE ) { 1567ggml_backend_t backend_h = ggml_backend_sched_get_tensor_backend (sched .get (),t_h_nextn ); 1568GGML_ASSERT (backend_h != nullptr ); 1569 1570const uint32_t n_embd = hparams .n_embd_out (); 1571GGML_ASSERT (n_tokens * n_embd <= (int64_t )embd_nextn .size ); 1572ggml_backend_tensor_get_async (backend_h ,t_h_nextn ,embd_nextn .data ,0 ,n_tokens * n_embd * sizeof (float )); 1573 } 1574 1575// TODO: hacky solution 1576if (model .arch == LLM_ARCH_T5 && t_embd ) { 1577//cross.t_embd = t_embd; 1578 1579synchronize (); 1580 1581cross .n_embd = t_embd -> ne [0 ]; 1582cross .n_enc = t_embd -> ne [1 ]; 1583cross .v_embd .resize (cross .n_embd * cross .n_enc ); 1584memcpy (cross .v_embd .data (),embd .data ,ggml_nbytes (t_embd )); 1585 1586const auto & batch = balloc -> get_batch (); 1587 1588// remember the sequence ids used during the encoding - needed for cross attention later 1589cross .seq_ids_enc .resize (n_tokens ); 1590for (uint32_t i = 0 ;i < n_tokens ;i ++ ) { 1591cross .seq_ids_enc [i ].clear (); 1592 1593for (int s = 0 ;s < batch .n_seq_id [i ];s ++ ) { 1594const llama_seq_id seq_id = batch .seq_id [i ][s ]; 1595 1596cross .seq_ids_enc [i ].insert (seq_id ); 1597 } 1598 } 1599 } 1600 1601return 0 ; 1602} 1603 1604template < typename T > 1605static void copy_tensor_async_rows ( 1606const std::vector < ggml_tensor *> & tensors , 1607const buffer_view < T > & dst , 1608size_t stride , 1609uint32_t row_offset , 1610ggml_backend_sched_t sched , 1611 std::vector < uint32_t > * counts = nullptr ) { 1612if (!dst .has_data ()) { 1613return ; 1614 } 1615 1616for (size_t i = 0 ;i < tensors .size ();++ i ) { 1617auto * tensor = tensors [i ]; 1618if (tensor == nullptr ) { 1619continue ; 1620 } 1621 1622const uint32_t row = row_offset + i ; 1623const size_t n_elements = ggml_nelements (tensor ); 1624GGML_ASSERT (ggml_is_contiguous (tensor )&& "sampling tensor must be contiguous for async copy" ); 1625GGML_ASSERT (n_elements <=stride ); 1626GGML_ASSERT ((size_t )row * stride + n_elements <=dst .size ); 1627 1628ggml_backend_t backend = ggml_backend_sched_get_tensor_backend (sched ,tensor ); 1629T * row_ptr = dst .data + (size_t )row * stride ; 1630ggml_backend_tensor_get_async (backend ,tensor ,row_ptr ,0 ,ggml_nbytes (tensor )); 1631 1632if (counts ) { 1633GGML_ASSERT (row < counts -> size ()); 1634 (* counts )[row ]= n_elements ; 1635 } 1636 } 1637} 1638 1639static bool needs_raw_logits (const llama_ubatch & ubatch ,const std::map < llama_seq_id ,llama_sampler *> & samplers ) { 1640for (uint32_t i = 0 ;i < ubatch .n_tokens ;i ++ ) { 1641if (!ubatch .output [i ]) { 1642continue ; 1643 } 1644 1645// Check if the output token has at least one sequence without a backend sampler. 1646for (int32_t j = 0 ;j < ubatch .n_seq_id [i ];++ j ) { 1647llama_seq_id seq_id = ubatch .seq_id [i ][j ]; 1648if (samplers .find (seq_id )== samplers .end ()) { 1649return true; 1650 } 1651 } 1652 } 1653return false;// all sequences use backend sampling 1654} 1655 1656int llama_context::decode (const llama_batch & batch_inp ) { 1657// MTP hook batches carry both token (next-token id) and embd (h_nextn row), 1658// so accept either present rather than requiring exactly one. 1659GGML_ASSERT (batch_inp .token || batch_inp .embd ); 1660 1661if (!memory ) { 1662LLAMA_LOG_DEBUG ("%s: cannot decode batches with this context (calling encode() instead)\n" ,__func__ ); 1663return encode (batch_inp ); 1664 } 1665 1666if (batch_inp .n_tokens == 0 ) { 1667LLAMA_LOG_ERROR ("%s: n_tokens == 0\n" ,__func__ ); 1668return -1 ; 1669 } 1670 1671const auto & vocab = model .vocab ; 1672const auto & hparams = model .hparams ; 1673 1674const int64_t n_vocab = vocab .n_tokens (); 1675const bool mtp_embd = cparams .ctx_type == LLAMA_CONTEXT_TYPE_MTP && batch_inp .embd ; 1676// DFlash embd batches carry the fused target features at the encoder input width 1677const bool dflash_embd = model .arch == LLM_ARCH_DFLASH && batch_inp .embd ; 1678const int64_t n_embd = mtp_embd ?hparams .n_embd_out () :dflash_embd ?hparams .n_embd_inp_enc () :hparams .n_embd_inp (); 1679 1680// when computing embeddings, all tokens are output 1681const bool output_all = cparams .embeddings ; 1682const bool has_samplers = !sampling .samplers .empty (); 1683 1684const uint32_t n_seq_max = cparams .kv_unified ?LLAMA_MAX_SEQ :cparams .n_seq_max ; 1685 1686// embedding contexts output every token even when batch.logits is not set 1687if (has_samplers && (output_all || batch_inp .logits )) { 1688 std::vector < int32_t > seq_output_count (n_seq_max ,0 ); 1689 1690for (int32_t i = 0 ;i < batch_inp .n_tokens ;++ i ) { 1691if (!output_all && batch_inp .logits [i ]== 0 ) { 1692continue ; 1693 } 1694 1695const int ns = batch_inp .n_seq_id ?batch_inp .n_seq_id [i ] :1 ; 1696 1697for (int32_t s = 0 ;s < ns ;++ s ) { 1698const llama_seq_id seq_id = batch_inp .seq_id ?batch_inp .seq_id [i ][s ] :0 ; 1699 1700if (seq_id < 0 || (uint32_t )seq_id >=n_seq_max ) { 1701continue ; 1702 } 1703 1704seq_output_count [seq_id ]++ ; 1705auto sampler = sampling .samplers .find (seq_id ); 1706if (sampler != sampling .samplers .end ()&& 1707seq_output_count [seq_id ]> (int32_t )cparams .n_outputs_max_per_seq ) { 1708LLAMA_LOG_ERROR ("%s: backend sampling supports at most %u outputs per sequence " 1709"(seq_id %d had %d)\n" ,__func__ ,cparams .n_outputs_max_per_seq , 1710seq_id ,seq_output_count [seq_id ]); 1711return -1 ; 1712 } 1713 } 1714 } 1715 } 1716 1717if (!balloc -> init (batch_inp ,vocab ,memory .get (),n_embd ,n_seq_max ,output_all )) { 1718LLAMA_LOG_ERROR ("%s: failed to initialize batch\n" ,__func__ ); 1719return -1 ; 1720 } 1721 1722const uint32_t n_tokens_all = balloc -> get_n_tokens (); 1723const uint32_t n_outputs_all = balloc -> get_n_outputs (); 1724 1725if (output_all ) { 1726// require that all tokens are output 1727if (n_outputs_all != n_tokens_all ) { 1728LLAMA_LOG_ERROR ("%s: pooled embedding requires that all tokens are output (n_outputs_all = %d, n_tokens_all = %d)\n" , 1729__func__ ,n_outputs_all ,n_tokens_all ); 1730return -1 ; 1731 } 1732 } 1733 1734GGML_ASSERT (n_tokens_all <=cparams .n_batch ); 1735 1736GGML_ASSERT ((cparams .causal_attn || cparams .n_ubatch >=n_tokens_all )&& "non-causal attention requires n_ubatch >= n_tokens" ); 1737 1738// TODO: this clear of the buffer can easily be forgotten - need something better 1739// sync first so any in-flight async copies into embd_seq complete before it is freed 1740if (!embd_seq .empty ()) { 1741synchronize (); 1742 } 1743embd_seq .clear (); 1744 1745if (t_compute_start_us == 0 ) { 1746t_compute_start_us = ggml_time_us (); 1747 } 1748n_queued_tokens += n_tokens_all ; 1749 1750output_swaps .clear (); 1751 1752sched_reserve (); 1753 1754bool did_optimize = false; 1755 1756// handle any pending shifts/copies 1757memory_update (false); 1758 1759llama_memory_context_ptr mctx ; 1760 1761while (true) { 1762mctx = memory -> init_batch (* balloc ,cparams .n_ubatch ,output_all ); 1763if (!mctx ) { 1764return -2 ; 1765 } 1766 1767switch (mctx -> get_status ()) { 1768case LLAMA_MEMORY_STATUS_SUCCESS : 1769 { 1770 }break ; 1771case LLAMA_MEMORY_STATUS_NO_UPDATE : 1772 { 1773LLAMA_LOG_ERROR ("%s: unexpected memory context status: %d\n" ,__func__ ,mctx -> get_status ()); 1774 1775return -2 ; 1776 } 1777case LLAMA_MEMORY_STATUS_FAILED_PREPARE : 1778 { 1779if (!did_optimize ) { 1780did_optimize = true; 1781 1782if (memory_update (true)) { 1783LLAMA_LOG_DEBUG ("%s: retrying batch size %d after cache optimization\n" ,__func__ ,balloc -> get_n_tokens ()); 1784 1785continue ; 1786 } 1787 } 1788 1789LLAMA_LOG_WARN ("%s: failed to find a memory slot for batch of size %d\n" ,__func__ ,balloc -> get_n_tokens ()); 1790 1791return 1 ; 1792 } 1793case LLAMA_MEMORY_STATUS_FAILED_COMPUTE : 1794 { 1795LLAMA_LOG_ERROR ("%s: compute failed while preparing batch of size %d\n" ,__func__ ,balloc -> get_n_tokens ()); 1796 1797return -2 ; 1798 } 1799 } 1800 1801break ; 1802 } 1803 1804// reserve output buffer 1805if (output_reserve (n_outputs_all )< n_outputs_all ) { 1806LLAMA_LOG_ERROR ("%s: could not reserve space for batch with %d outputs\n" ,__func__ ,n_outputs_all ); 1807return -2 ; 1808 }; 1809 1810// start a new sampling transaction for this logical batch 1811for (const auto & entry :sampling .samplers ) { 1812llama_sampler_backend_begin (entry .second ); 1813 } 1814 1815int64_t n_outputs_prev = 0 ; 1816int64_t n_tokens_prev = 0 ; 1817 1818do { 1819const auto & ubatch = mctx -> get_ubatch (); 1820 1821// count the outputs in this ubatch 1822 { 1823int32_t n_outputs_new = 0 ; 1824 1825if (n_outputs_all == n_tokens_all ) { 1826n_outputs_new = ubatch .n_tokens ; 1827 }else { 1828for (uint32_t i = 0 ;i < ubatch .n_tokens ;i ++ ) { 1829n_outputs_new += (int32_t ) (ubatch .output [i ]!= 0 ); 1830 } 1831 } 1832 1833// needs to happen before the graph is built 1834n_outputs = n_outputs_new ; 1835 } 1836 1837ggml_status status ; 1838 1839const auto * res = process_ubatch (ubatch ,ctx_type_to_graph_type (cparams .ctx_type ),mctx .get (),status ); 1840 1841if (!res ) { 1842// the last ubatch failed or was aborted -> remove all positions of that ubatch from the memory module 1843llama_pos pos_min [LLAMA_MAX_SEQ ]; 1844for (int s = 0 ;s < LLAMA_MAX_SEQ ;++ s ) { 1845pos_min [s ]= std::numeric_limits < llama_pos > ::max (); 1846 } 1847 1848for (uint32_t i = 0 ;i < ubatch .n_tokens ;++ i ) { 1849const auto & seq_id = ubatch .seq_id [i ][0 ]; 1850 1851pos_min [seq_id ]= std::min (pos_min [seq_id ],ubatch .pos [i ]); 1852 } 1853 1854for (int s = 0 ;s < LLAMA_MAX_SEQ ;++ s ) { 1855if (pos_min [s ]== std::numeric_limits < llama_pos > ::max ()) { 1856continue ; 1857 } 1858 1859LLAMA_LOG_WARN ("%s: removing memory module entries for seq_id = %d, pos = [%d, +inf)\n" ,__func__ ,s ,pos_min [s ]); 1860 1861memory -> seq_rm (s ,pos_min [s ],-1 ); 1862 } 1863 1864switch (status ) { 1865case GGML_STATUS_ABORTED :return 2 ; 1866case GGML_STATUS_ALLOC_FAILED :return -2 ; 1867case GGML_STATUS_FAILED :return -3 ; 1868case GGML_STATUS_SUCCESS :GGML_ABORT ("should not happen" ); 1869 } 1870 } 1871 1872// plot the computation graph in dot format (for debugging purposes) 1873//if (n_past%100 == 0) { 1874// ggml_graph_dump_dot(gf, NULL, "llama.dot"); 1875//} 1876 1877auto * t_logits = res -> get_logits (); 1878auto * t_embd = cparams .embeddings ?res -> get_embd () :nullptr ; 1879auto * t_h_nextn = cparams .embeddings_nextn ?res -> get_h_nextn () :nullptr ; 1880 1881if (t_embd && res -> get_embd_pooled ()) { 1882t_embd = res -> get_embd_pooled (); 1883 } 1884 1885// extract logits 1886if (logits .data && t_logits && n_outputs > 0 && needs_raw_logits (ubatch ,sampling .samplers )) { 1887ggml_backend_t backend_res = ggml_backend_sched_get_tensor_backend (sched .get (),t_logits ); 1888GGML_ASSERT (backend_res != nullptr ); 1889GGML_ASSERT (logits .data != nullptr ); 1890 1891float * logits_out = logits .data + n_outputs_prev * n_vocab ; 1892 1893if (n_outputs ) { 1894GGML_ASSERT (n_outputs_prev + n_outputs <=n_outputs_all ); 1895GGML_ASSERT ((n_outputs_prev + n_outputs )* n_vocab <= (int64_t )logits .size ); 1896ggml_backend_tensor_get_async (backend_res ,t_logits ,logits_out ,0 ,n_outputs * n_vocab * sizeof (float )); 1897 } 1898 } 1899 1900// extract embeddings 1901if (embd .data && t_embd && n_outputs > 0 ) { 1902ggml_backend_t backend_embd = ggml_backend_sched_get_tensor_backend (sched .get (),t_embd ); 1903GGML_ASSERT (backend_embd != nullptr ); 1904 1905switch (cparams .pooling_type ) { 1906case LLAMA_POOLING_TYPE_NONE : 1907 { 1908// extract token embeddings 1909GGML_ASSERT (embd .data != nullptr ); 1910const uint32_t n_embd_out = hparams .n_embd_out (); 1911float * embd_out = embd .data + n_outputs_prev * n_embd_out ; 1912 1913if (n_outputs ) { 1914GGML_ASSERT (n_outputs_prev + n_outputs <=n_outputs_all ); 1915GGML_ASSERT ((n_outputs_prev + n_outputs )* n_embd_out <= (int64_t )embd .size ); 1916ggml_backend_tensor_get_async (backend_embd ,t_embd ,embd_out ,0 ,n_outputs * n_embd_out * sizeof (float )); 1917 } 1918 }break ; 1919case LLAMA_POOLING_TYPE_MEAN : 1920case LLAMA_POOLING_TYPE_CLS : 1921case LLAMA_POOLING_TYPE_LAST : 1922 { 1923// extract sequence embeddings (cleared before processing each batch) 1924auto & embd_seq_out = embd_seq ; 1925 1926// use n_embd_out (not n_embd_inp) - the pooled embedding has the model's 1927// output dimension, which differs from input dimension for deepstack models (e.g. qwen3vl) 1928const uint32_t n_embd_out = hparams .n_embd_out (); 1929 1930for (uint32_t s = 0 ;s < ubatch .n_seqs_unq ;++ s ) { 1931const llama_seq_id seq_id = ubatch .seq_id_unq [s ]; 1932const int32_t seq_idx = ubatch .seq_idx [seq_id ]; 1933 1934embd_seq_out [seq_id ].resize (n_embd_out ); 1935ggml_backend_tensor_get_async (backend_embd ,t_embd ,embd_seq_out [seq_id ].data (), (n_embd_out * seq_idx )* sizeof (float ),n_embd_out * sizeof (float )); 1936 } 1937 }break ; 1938case LLAMA_POOLING_TYPE_RANK : 1939 { 1940// extract the rerank score - n_cls_out floats per sequence 1941auto & embd_seq_out = embd_seq ; 1942 1943const uint32_t n_cls_out = hparams .n_cls_out ; 1944 1945for (uint32_t s = 0 ;s < ubatch .n_seqs_unq ;++ s ) { 1946const llama_seq_id seq_id = ubatch .seq_id_unq [s ]; 1947const int32_t seq_idx = ubatch .seq_idx [seq_id ]; 1948 1949embd_seq_out [seq_id ].resize (n_cls_out ); 1950ggml_backend_tensor_get_async (backend_embd ,t_embd ,embd_seq_out [seq_id ].data (), (n_cls_out * seq_idx )* sizeof (float ),n_cls_out * sizeof (float )); 1951 } 1952 }break ; 1953case LLAMA_POOLING_TYPE_UNSPECIFIED : 1954 { 1955GGML_ABORT ("unknown pooling type" ); 1956 } 1957 } 1958 } 1959 1960extract_layer_inputs (res ,n_tokens_prev ,ubatch .n_tokens ); 1961 1962// extract nextn embeddings before 1963// only meaningful in LLAMA_POOLING_TYPE_NONE (per-token); other pooling modes are ignored. 1964 { 1965const bool masked = cparams .embeddings_nextn_masked ; 1966const int64_t n_rows = masked ?n_outputs : (int64_t )ubatch .n_tokens ; 1967const int64_t offset = masked ?n_outputs_prev :n_tokens_prev ; 1968 1969if (embd_nextn .data && t_h_nextn && n_rows > 0 && cparams .pooling_type == LLAMA_POOLING_TYPE_NONE ) { 1970ggml_backend_t backend_h = ggml_backend_sched_get_tensor_backend (sched .get (),t_h_nextn ); 1971GGML_ASSERT (backend_h != nullptr ); 1972 1973const uint32_t n_embd = hparams .n_embd_out (); 1974float * embd_nextn_out = embd_nextn .data + offset * n_embd ; 1975 1976GGML_ASSERT ((offset + n_rows )* n_embd <= (int64_t )embd_nextn .size ); 1977ggml_backend_tensor_get_async (backend_h ,t_h_nextn ,embd_nextn_out ,0 ,n_rows * n_embd * sizeof (float )); 1978 } 1979 } 1980 1981if (has_samplers ) { 1982const auto stride = n_vocab ; 1983 1984// async copy the sampling data from the backend to the host 1985copy_tensor_async_rows (res -> t_sampled ,sampling .sampled ,1 ,n_outputs_prev ,sched .get ()); 1986copy_tensor_async_rows (res -> t_sampled_logits ,sampling .logits ,stride ,n_outputs_prev ,sched .get (),& sampling .logits_count ); 1987copy_tensor_async_rows (res -> t_sampled_probs ,sampling .probs ,stride ,n_outputs_prev ,sched .get (),& sampling .probs_count ); 1988copy_tensor_async_rows (res -> t_candidates ,sampling .candidates ,stride ,n_outputs_prev ,sched .get (),& sampling .candidates_count ); 1989 } 1990 1991n_outputs_prev += n_outputs ; 1992n_tokens_prev += ubatch .n_tokens ; 1993 }while (mctx -> next ()); 1994 1995// set to total number of outputs in the batch, for use in llama_get_logits_ith 1996n_outputs = n_outputs_all ; 1997 1998// set output mappings 1999if (n_outputs > 0 ) { 2000bool sorted_output = true; 2001 2002auto & out_ids = balloc -> get_out_ids (); 2003 2004GGML_ASSERT (out_ids .size ()== (size_t )n_outputs ); 2005 2006for (int64_t i = 0 ;i < n_outputs ;++ i ) { 2007int64_t out_id = out_ids [i ]; 2008output_ids [out_id ]= i ; 2009if (out_id != i ) { 2010sorted_output = false; 2011 } 2012 } 2013 2014// make the outputs have the same order they had in the user-provided batch 2015// note: this is mostly relevant for recurrent models atm 2016if (!sorted_output && n_outputs > 1 ) { 2017GGML_ASSERT ((size_t )n_outputs == out_ids .size ()); 2018 2019// TODO: is there something more efficient which also minimizes swaps? 2020// selection sort, to minimize swaps (from https://en.wikipedia.org/wiki/Selection_sort) 2021for (uint32_t i = 0 ;i < n_outputs - 1 ;++ i ) { 2022uint32_t j_min = i ; 2023for (uint32_t j = i + 1 ;j < n_outputs ;++ j ) { 2024if (out_ids [j ]< out_ids [j_min ]) { 2025j_min = j ; 2026 } 2027 } 2028if (j_min == i ) { 2029continue ; 2030 } 2031 std::swap (out_ids [i ],out_ids [j_min ]); 2032 2033// remember the swaps and apply them lazily upon logits/embeddings access 2034output_swaps .push_back ({i ,j_min }); 2035 } 2036 2037 std::fill (output_ids .begin (),output_ids .end (),-1 ); 2038 2039for (uint32_t i = 0 ;i < n_outputs ;++ i ) { 2040output_ids [out_ids [i ]]= i ; 2041 } 2042 } 2043 } 2044 2045// wait for the computation to finish (automatically done when obtaining the model output) 2046//synchronize(); 2047 2048return 0 ; 2049} 2050 2051// 2052// output 2053// 2054 2055uint32_t llama_context::output_reserve (int32_t n_outputs ) { 2056const auto & hparams = model .hparams ; 2057const auto & vocab = model .vocab ; 2058 2059const int64_t n_outputs_max = std::max < int64_t > (n_outputs ,n_seq_max ()); 2060 2061const auto n_batch = cparams .n_batch ; 2062const auto n_vocab = vocab .n_tokens (); 2063const auto n_embd = hparams .n_embd ; 2064const auto n_embd_out = hparams .n_embd_out (); 2065 2066bool has_logits = true; 2067bool has_embd = cparams .embeddings ; 2068bool has_embd_nextn = cparams .embeddings_nextn ; 2069 2070// TODO: hacky enc-dec support 2071if (model .arch == LLM_ARCH_T5 ) { 2072has_logits = true; 2073has_embd = true; 2074 } 2075 2076size_t backend_float_count = 0 ; 2077size_t backend_token_count = 0 ; 2078size_t embd_layer_inp_float_count = 0 ; 2079 2080logits .size = has_logits ?n_vocab * n_outputs_max :0 ; 2081embd .size = has_embd ?n_embd_out * n_outputs_max :0 ; 2082embd_nextn .size = has_embd_nextn ?n_embd_out * n_outputs_max :0 ; 2083 2084if (has_embd_nextn && !cparams .embeddings_nextn_masked ) { 2085// unmasked: nextn row exists for every token in the batch, not just 2086// those flagged via batch.logits[i] -> size by token count instead. 2087embd_nextn .size = (size_t )n_embd_out * n_batch ; 2088 } 2089 2090for (bool enabled :cparams .embeddings_layer_inp ) { 2091if (enabled ) { 2092embd_layer_inp_float_count += (size_t )n_embd * n_batch ; 2093 } 2094 } 2095 2096// Allocate backend sampling output buffers if there are backend samplers configured. 2097const bool has_sampling = !sampling .samplers .empty (); 2098if (has_sampling ) { 2099backend_float_count = 2 * n_vocab * n_outputs_max ;// logits + probs 2100backend_token_count = (1 + n_vocab )* n_outputs_max ;// sampled + candidates 2101 } 2102 2103if (output_ids .empty ()) { 2104// init, never resized afterwards 2105output_ids .resize (n_batch ); 2106 } 2107 2108const size_t prev_size = buf_output ?ggml_backend_buffer_get_size (buf_output .get ()) :0 ; 2109const size_t new_size = 2110 (logits .size + embd .size + embd_nextn .size + embd_layer_inp_float_count + backend_float_count )* sizeof (float )+ 2111 (backend_token_count )* sizeof (llama_token ); 2112 2113// alloc only when more than the current capacity is required 2114// TODO: also consider shrinking the buffer 2115if (!buf_output || prev_size < new_size ) { 2116if (buf_output ) { 2117#ifndef NDEBUG 2118// This doesn't happen often, but may be annoying in some cases (like the HellaSwag benchmark) 2119LLAMA_LOG_DEBUG ("%s: reallocating output buffer from size %.02f MiB to %.02f MiB\n" ,__func__ ,prev_size /1024.0 /1024.0 ,new_size /1024.0 /1024.0 ); 2120#endif 2121synchronize (); 2122 2123// TODO: not needed? 2124buf_output = nullptr ; 2125logits .data = nullptr ; 2126embd .data = nullptr ; 2127embd_nextn .data = nullptr ; 2128for (auto & layer_inp :embd_layer_inp ) { 2129layer_inp = {nullptr ,0 }; 2130 } 2131 } 2132 2133auto * buft = ggml_backend_cpu_buffer_type (); 2134// try to use the host buffer of the device where the output tensor is allocated for faster transfer to system memory 2135auto * output_dev = model .dev_output (); 2136auto * output_dev_host_buft = output_dev ?ggml_backend_dev_host_buffer_type (output_dev ) :nullptr ; 2137if (output_dev_host_buft ) { 2138buft = output_dev_host_buft ; 2139 } 2140buf_output .reset (ggml_backend_buft_alloc_buffer (buft ,new_size )); 2141if (buf_output == nullptr ) { 2142LLAMA_LOG_ERROR ("%s: failed to allocate output buffer of size %.2f MiB\n" ,__func__ ,new_size / (1024.0 * 1024.0 )); 2143return 0 ; 2144 } 2145ggml_backend_buffer_clear (buf_output .get (),0 ); 2146 } 2147 2148float * output_base = (float * )ggml_backend_buffer_get_base (buf_output .get ()); 2149 2150size_t offset = 0 ; 2151uint8_t * base = (uint8_t * )output_base ; 2152 2153logits = has_logits ?buffer_view < float > {output_base ,logits .size } :buffer_view < float > {nullptr ,0 }; 2154offset += logits .size * sizeof (float ); 2155 2156embd = has_embd ?buffer_view < float > {(float * ) (base + offset ),embd .size } :buffer_view < float > {nullptr ,0 }; 2157offset += embd .size * sizeof (float ); 2158 2159embd_nextn = has_embd_nextn ?buffer_view < float > {(float * ) (base + offset ),embd_nextn .size } :buffer_view < float > {nullptr ,0 }; 2160offset += embd_nextn .size * sizeof (float ); 2161 2162for (uint32_t il = 0 ;il < embd_layer_inp .size ();++ il ) { 2163if (cparams .embeddings_layer_inp [il ]) { 2164embd_layer_inp [il ]= buffer_view < float > {(float * ) (base + offset ), (size_t )n_embd * n_batch }; 2165offset += embd_layer_inp [il ].size * sizeof (float ); 2166 }else { 2167embd_layer_inp [il ]= buffer_view < float > {nullptr ,0 }; 2168 } 2169 } 2170 2171if (has_sampling ) { 2172sampling .logits = {(float * ) (base + offset ), (size_t )(n_vocab * n_outputs_max )}; 2173offset += sampling .logits .size * sizeof (float ); 2174 2175sampling .probs = {(float * ) (base + offset ), (size_t )(n_vocab * n_outputs_max )}; 2176offset += sampling .probs .size * sizeof (float ); 2177 2178sampling .sampled = {(llama_token * ) (base + offset ), (size_t )n_outputs_max }; 2179offset += sampling .sampled .size * sizeof (llama_token ); 2180 2181sampling .candidates = {(llama_token * ) (base + offset ), (size_t )(n_vocab * n_outputs_max )}; 2182offset += sampling .candidates .size * sizeof (llama_token ); 2183 2184// The count vectors keep track of the actual number of logits/probs/candidates 2185// copied from the backend for each output row. 2186 2187sampling .logits_count .resize (n_outputs_max ); 2188sampling .probs_count .resize (n_outputs_max ); 2189sampling .candidates_count .resize (n_outputs_max ); 2190 2191 std::fill (sampling .logits_count .begin (),sampling .logits_count .end (),0 ); 2192 std::fill (sampling .probs_count .begin (),sampling .probs_count .end (),0 ); 2193 std::fill (sampling .candidates_count .begin (),sampling .candidates_count .end (),0 ); 2194 2195 std::fill_n (sampling .sampled .data ,sampling .sampled .size ,LLAMA_TOKEN_NULL ); 2196 }else { 2197sampling .logits = {nullptr ,0 }; 2198sampling .probs = {nullptr ,0 }; 2199sampling .sampled = {nullptr ,0 }; 2200sampling .candidates = {nullptr ,0 }; 2201 2202sampling .logits_count .clear (); 2203sampling .probs_count .clear (); 2204sampling .candidates_count .clear (); 2205 } 2206 2207// set all ids as invalid (negative) 2208 std::fill (output_ids .begin (),output_ids .end (),-1 ); 2209 2210this -> n_outputs = 0 ; 2211 2212GGML_ASSERT (n_outputs_max <=cparams .n_outputs_max ); 2213 2214return n_outputs_max ; 2215} 2216 2217void llama_context::extract_layer_inputs (const llm_graph_result * res ,size_t token_offset ,size_t n_tokens ) { 2218for (uint32_t il = 0 ;il < cparams .embeddings_layer_inp .size ();++ il ) { 2219if (!cparams .embeddings_layer_inp [il ]) { 2220continue ; 2221 } 2222if (!embd_layer_inp [il ].has_data ()) { 2223GGML_ABORT ("output layer input buffer not allocated" ); 2224 } 2225ggml_tensor * t = res -> get_layer_inp ((int )il ); 2226if (!t ) { 2227GGML_ABORT ("layer input tensor not found" ); 2228 } 2229 2230const size_t nbytes = ggml_nbytes (t ); 2231const size_t nfloats = nbytes /sizeof (float ); 2232GGML_ASSERT (n_tokens > 0 ); 2233GGML_ASSERT (nfloats %n_tokens == 0 ); 2234 2235const size_t row_floats = nfloats /n_tokens ; 2236const size_t dst_offset = token_offset * row_floats ; 2237GGML_ASSERT (dst_offset + nfloats <=embd_layer_inp [il ].size ); 2238 2239ggml_backend_t backend = ggml_backend_sched_get_tensor_backend (sched .get (),t ); 2240GGML_ASSERT (backend != nullptr ); 2241ggml_backend_tensor_get_async (backend ,t ,embd_layer_inp [il ].data + dst_offset ,0 ,nbytes ); 2242 } 2243} 2244 2245void llama_context::output_reorder () { 2246const uint64_t n_vocab = model .vocab .n_tokens (); 2247const uint64_t n_embd = model .hparams .n_embd ; 2248const uint64_t n_embd_out = model .hparams .n_embd_out (); 2249 2250for (size_t s = 0 ;s < output_swaps .size ();++ s ) { 2251const uint64_t i0 = output_swaps [s ].i0 ; 2252const uint64_t i1 = output_swaps [s ].i1 ; 2253 2254if (logits .size > 0 ) { 2255for (uint64_t k = 0 ;k < n_vocab ;k ++ ) { 2256 std::swap (logits .data [i0 * n_vocab + k ],logits .data [i1 * n_vocab + k ]); 2257 } 2258 } 2259 2260if (embd .size > 0 ) { 2261for (uint64_t k = 0 ;k < n_embd_out ;k ++ ) { 2262 std::swap (embd .data [i0 * n_embd_out + k ],embd .data [i1 * n_embd_out + k ]); 2263 } 2264 } 2265 2266if (embd_nextn .size > 0 ) { 2267for (uint64_t k = 0 ;k < n_embd_out ;k ++ ) { 2268 std::swap (embd_nextn .data [i0 * n_embd_out + k ],embd_nextn .data [i1 * n_embd_out + k ]); 2269 } 2270 } 2271 2272if (embd_layer_inp .size ()> 0 ) { 2273for (int lid = 0 ;lid < (int )embd_layer_inp .size ();++ lid ) { 2274if (embd_layer_inp [lid ].size > 0 ) { 2275for (uint64_t k = 0 ;k < n_embd ;++ k ) { 2276 std::swap (embd_layer_inp [lid ].data [i0 * n_embd + k ],embd_layer_inp [lid ].data [i1 * n_embd + k ]); 2277 } 2278 } 2279 } 2280 } 2281 2282if (!sampling .samplers .empty ()) { 2283assert (sampling .logits .size > 0 ); 2284assert (sampling .probs .size > 0 ); 2285assert (sampling .candidates .size > 0 ); 2286assert (sampling .sampled .size > 0 ); 2287assert (sampling .logits_count .size ()> 0 ); 2288assert (sampling .probs_count .size ()> 0 ); 2289assert (sampling .candidates_count .size ()> 0 ); 2290 2291for (uint64_t k = 0 ;k < n_vocab ;++ k ) { 2292 std::swap (sampling .logits .data [i0 * n_vocab + k ],sampling .logits .data [i1 * n_vocab + k ]); 2293 } 2294 2295for (uint64_t k = 0 ;k < n_vocab ;++ k ) { 2296 std::swap (sampling .probs .data [i0 * n_vocab + k ],sampling .probs .data [i1 * n_vocab + k ]); 2297 } 2298 2299for (uint64_t k = 0 ;k < n_vocab ;++ k ) { 2300 std::swap (sampling .candidates .data [i0 * n_vocab + k ],sampling .candidates .data [i1 * n_vocab + k ]); 2301 } 2302 2303 std::swap (sampling .sampled .data [i0 ],sampling .sampled .data [i1 ]); 2304 std::swap (sampling .logits_count [i0 ],sampling .logits_count [i1 ]); 2305 std::swap (sampling .probs_count [i0 ],sampling .probs_count [i1 ]); 2306 std::swap (sampling .candidates_count [i0 ],sampling .candidates_count [i1 ]); 2307 } 2308 } 2309 2310output_swaps .clear (); 2311} 2312 2313// 2314// graph 2315// 2316 2317uint32_t llama_context::graph_max_nodes (uint32_t n_tokens )const { 2318uint32_t res ; 2319if (model .arch == LLM_ARCH_KIMI_K3 ) { 2320// the n_tokens*40 budget below is exhausted at ubatch 3840 2321res = std::max < uint32_t > (n_tokens * 160 ,64u * model .n_tensors ()); 2322 }else if (model .arch == LLM_ARCH_HRM_TEXT ) { 2323// the 128-slot looped graph needs roughly one stack per token budget 2324res = std::max < uint32_t > (n_tokens * 80 ,64u * model .n_tensors ()); 2325 }else if (model .arch == LLM_ARCH_QWEN3NEXT || 2326model .arch == LLM_ARCH_KIMI_LINEAR || 2327model .arch == LLM_ARCH_BAILINGMOE3 || 2328model .arch == LLM_ARCH_QWEN35 || 2329model .arch == LLM_ARCH_QWEN35MOE || 2330model .arch == LLM_ARCH_QWEN4EXP || 2331model .arch == LLM_ARCH_DEEPSEEK4 || 2332 (model .arch == LLM_ARCH_DFLASH && model .hparams .dsv4_hc_mult > 0 )|| 2333model .arch == LLM_ARCH_NANBEIGE || 2334model .arch == LLM_ARCH_MINIMAX_01 || 2335model .arch == LLM_ARCH_MINIMAX_M3 || 2336model .arch == LLM_ARCH_HY_V4 ) { 2337res = std::max < uint32_t > (n_tokens * 40 ,32u * model .n_tensors ()); 2338 }else if (model .arch == LLM_ARCH_DFLASH && model .hparams .dflash_selector_rank > 0 ) { 2339// DFlash2's convolutions and selector are shape work rather than matmuls, 2340// so they cost ~8.6 nodes per tensor against ~5.9 for a plain DFlash draft 2341res = std::max < uint32_t > (1024u ,12u * model .n_tensors ()); 2342 }else { 2343res = std::max < uint32_t > (1024u ,8u * model .n_tensors ()); 2344for (const auto & lora :model .loras ) { 2345res += lora -> get_n_nodes (); 2346 } 2347 } 2348 2349uint32_t n_sampling_nodes = 0 ; 2350uint32_t n_sampling_nodes_max = 0 ; 2351for (const auto & [seq_id ,sampler ] :sampling .samplers ) { 2352const uint32_t n_nodes = llama_sampler_backend_n_nodes (sampler ); 2353n_sampling_nodes += n_nodes ; 2354if (cparams .n_outputs_max_per_seq > 1 ) { 2355n_sampling_nodes_max = std::max (n_sampling_nodes_max ,n_nodes ); 2356 } 2357 } 2358 2359const uint32_t n_sampling_outputs_max = std::min < uint64_t > ( 2360 std::min (n_tokens ,cparams .n_outputs_max ), 2361 (uint64_t )cparams .n_seq_max * cparams .n_outputs_max_per_seq ); 2362 2363res += n_sampling_nodes ; 2364if (n_sampling_outputs_max > 1 ) { 2365res += (n_sampling_outputs_max - 1 )* n_sampling_nodes_max ; 2366 } 2367return res ; 2368} 2369 2370llm_graph_result * llama_context::get_gf_res_reserve ()const { 2371return static_cast < llm_graph_result *> (gf_res_reserve .get ()); 2372} 2373 2374llm_graph_result * llama_context::get_gf_res_prev () { 2375auto & res = gf_res_prev [n_outputs > 0 ]; 2376if (!res ) { 2377res .reset (new llm_graph_result (gf_res_reserve -> get_max_nodes ())); 2378 } 2379return res .get (); 2380} 2381 2382// pack sampler outputs into as few sequences as possible before using sequences without samplers 2383static void ubatch_prepare_reserve ( 2384llama_ubatch & ubatch , 2385uint32_t n_outputs , 2386const std::map < llama_seq_id ,llama_sampler *> & samplers , 2387uint32_t n_outputs_max_per_seq ) { 2388const uint32_t n_seqs = ubatch .n_seqs ; 2389const uint32_t n_seq_tokens = ubatch .n_seq_tokens ; 2390 2391for (uint32_t s = 0 ;s < n_seqs ;++ s ) { 2392for (uint32_t t = 0 ;t < n_seq_tokens ;++ t ) { 2393const uint32_t i = s * n_seq_tokens + t ; 2394ubatch .n_seq_id [i ]= 1 ; 2395ubatch .seq_id [i ]= & ubatch .seq_id_unq [s ]; 2396 } 2397 } 2398 2399// sequences with a sampler that fit in this ubatch 2400 std::vector < uint32_t > sampler_seqs ; 2401 std::vector < bool > has_sampler (n_seqs ,false ); 2402for (const auto & entry :samplers ) { 2403const llama_seq_id seq_id = entry .first ; 2404if (seq_id < 0 || (uint32_t )seq_id >=n_seqs ) { 2405continue ; 2406 } 2407 2408sampler_seqs .push_back (seq_id ); 2409has_sampler [seq_id ]= true; 2410 } 2411 2412uint32_t n_outputs_set = 0 ; 2413 2414const uint32_t n_outputs_per_seq = std::min (n_seq_tokens ,n_outputs_max_per_seq ); 2415for (uint32_t s :sampler_seqs ) { 2416if (n_outputs_set >=n_outputs ) { 2417break ; 2418 } 2419 2420for (uint32_t t = 0 ;t < n_outputs_per_seq && n_outputs_set < n_outputs ;++ t ) { 2421ubatch .output [s * n_seq_tokens + t ]= true; 2422++ n_outputs_set ; 2423 } 2424 } 2425 2426// use sequences without samplers for any remaining outputs 2427for (uint32_t t = 0 ;t < n_seq_tokens && n_outputs_set < n_outputs ;++ t ) { 2428for (uint32_t s = 0 ;s < n_seqs && n_outputs_set < n_outputs ;++ s ) { 2429if (has_sampler [s ]) { 2430continue ; 2431 } 2432 2433ubatch .output [s * n_seq_tokens + t ]= true; 2434++ n_outputs_set ; 2435 } 2436 } 2437} 2438 2439ggml_cgraph * llama_context::graph_reserve ( 2440uint32_t n_tokens ,uint32_t n_seqs ,uint32_t n_outputs ,const llama_memory_context_i * mctx ,bool split_only ,size_t * sizes ) { 2441LLAMA_LOG_DEBUG ("%s: reserving a graph for ubatch with n_tokens = %4u, n_seqs = %2u, n_outputs = %4u\n" ,__func__ ,n_tokens ,n_seqs ,n_outputs ); 2442GGML_ASSERT (n_outputs >=1 ); 2443 2444if (n_tokens %n_seqs != 0 ) { 2445n_tokens = ((n_tokens + (n_seqs - 1 )) /n_seqs )* n_seqs ;// round to next multiple of n_seqs 2446LLAMA_LOG_DEBUG ("%s: making n_tokens a multiple of n_seqs - n_tokens = %u, n_seqs = %u, n_outputs = %u\n" ,__func__ ,n_tokens ,n_seqs ,n_outputs ); 2447 } 2448 2449ggml_backend_sched_reset (sched .get ()); 2450 2451// when the scheduler is reset, we cannot reuse old graphs, so we reset the previous graph results 2452for (auto & res :gf_res_prev ) { 2453if (res ) { 2454res -> reset (); 2455 } 2456 } 2457gf_res_prev_active = nullptr ; 2458 2459// store the n_outputs as it is, and restore it afterwards 2460// TODO: not sure if needed, might simplify in the future by removing this 2461const auto save_n_outputs = this -> n_outputs ; 2462 2463this -> n_outputs = n_outputs ; 2464 2465llama_batch_allocr balloc (model .hparams .n_pos_per_embd ()); 2466llama_ubatch ubatch = balloc .ubatch_reserve (n_tokens /n_seqs ,n_seqs ); 2467 2468ubatch_prepare_reserve (ubatch ,n_outputs ,sampling .samplers ,cparams .n_outputs_max_per_seq ); 2469 2470auto * res = gf_res_reserve .get (); 2471 2472const auto gparams = graph_params (res ,ubatch ,mctx ,ctx_type_to_graph_type (cparams .ctx_type )); 2473 2474res -> reset (); 2475 2476auto * gf = model .build_graph (gparams ); 2477 2478this -> n_outputs = save_n_outputs ; 2479 2480// initialize scheduler with the specified graph 2481if (split_only ) { 2482if (sizes ) { 2483ggml_backend_sched_reserve_size (sched .get (),gf ,sizes ); 2484 }else { 2485ggml_backend_sched_split_graph (sched .get (),gf ); 2486 } 2487 }else if (!ggml_backend_sched_reserve (sched .get (),gf )) { 2488GGML_ASSERT (!sizes ); 2489LLAMA_LOG_ERROR ("%s: failed to allocate compute buffers\n" ,__func__ ); 2490return nullptr ; 2491 } 2492 2493return gf ; 2494} 2495 2496llm_graph_params llama_context::graph_params ( 2497llm_graph_result * res , 2498const llama_ubatch & ubatch , 2499const llama_memory_context_i * mctx , 2500llm_graph_type gtype )const { 2501return { 2502/*.arch =*/ model .arch , 2503/*.hparams =*/ model .hparams , 2504/*.cparams =*/ cparams , 2505/*.ubatch =*/ ubatch , 2506/*.gtype =*/ gtype , 2507/*.sched =*/ sched .get (), 2508/*.backend_cpu =*/ backend_cpu , 2509/*.cvec =*/ cvec .get (), 2510/*.loras =*/ loras .get (), 2511/*.mctx =*/ mctx , 2512/*.cross =*/ & cross , 2513/*.samplers =*/ sampling .samplers , 2514/*.n_outputs =*/ n_outputs , 2515/*.cb =*/ graph_get_cb (), 2516/*.res =*/ res , 2517 }; 2518} 2519 2520ggml_status llama_context::graph_compute ( 2521ggml_cgraph * gf , 2522bool batched ) { 2523int n_threads = batched ?cparams .n_threads_batch :cparams .n_threads ; 2524ggml_threadpool_t tp = batched ?threadpool_batch :threadpool ; 2525 2526if (backend_cpu != nullptr ) { 2527auto * reg = ggml_backend_dev_backend_reg (ggml_backend_get_device (backend_cpu )); 2528auto * set_threadpool_fn = (decltype(ggml_backend_cpu_set_threadpool )* )ggml_backend_reg_get_proc_address (reg ,"ggml_backend_cpu_set_threadpool" ); 2529if (set_threadpool_fn ) { 2530set_threadpool_fn (backend_cpu ,tp ); 2531 } 2532 } 2533 2534// set the number of threads for all the backends 2535for (const auto & set_n_threads_fn :set_n_threads_fns ) { 2536set_n_threads_fn .second (set_n_threads_fn .first ,n_threads ); 2537 } 2538 2539auto status = ggml_backend_sched_graph_compute_async (sched .get (),gf ); 2540if (status != GGML_STATUS_SUCCESS ) { 2541LLAMA_LOG_ERROR ("%s: ggml_backend_sched_graph_compute_async failed with error %d\n" ,__func__ ,status ); 2542 } 2543 2544// fprintf(stderr, "splits: %d\n", ggml_backend_sched_get_n_splits(sched)); 2545 2546return status ; 2547} 2548 2549llm_graph_cb llama_context::graph_get_cb ()const { 2550return [& ](const llama_ubatch & ubatch ,ggml_tensor * cur ,const char * name ,int il ) { 2551if (il >=0 ) { 2552ggml_format_name (cur ,"%s-%d" ,name ,il ); 2553 }else { 2554ggml_set_name (cur ,name ); 2555 } 2556 2557// - norm may be automatically assigned to the backend of the previous layer, increasing data transfer between backends 2558// - force the last op of the layer on the specified backend to avoid running it on the backend of the next layer due to scheduling 2559// FIXME: fix in ggml_backend_sched 2560const bool full_offload = model .n_gpu_layers ()> model .hparams .n_layer_all ; 2561if (ubatch .n_tokens < 32 || full_offload ) { 2562if (il != -1 && (strcmp (name ,"norm" )== 0 || strcmp (name ,"l_last" )== 0 )) { 2563const auto & dev_layer = model .dev_layer (il ); 2564for (const auto & backend :backends ) { 2565if (ggml_backend_get_device (backend .get ())== dev_layer ) { 2566if (ggml_backend_supports_op (backend .get (),cur )) { 2567ggml_backend_sched_set_tensor_backend (sched .get (),cur ,backend .get ()); 2568 } 2569 } 2570 } 2571 } 2572 } 2573 }; 2574} 2575 2576// 2577// state save/load 2578// 2579 2580class llama_io_write_dummy :public llama_io_write_i { 2581public : 2582llama_io_write_dummy (bool skip_tensors ) :skip_tensors (skip_tensors ) {} 2583 2584void write (const void * /* src */ ,size_t size )override { 2585size_written += size ; 2586 } 2587 2588void write_tensor (ggml_tensor * /* tensor */ ,size_t /* offset */ ,size_t size )override { 2589if (skip_tensors ) { 2590return ; 2591 } 2592 2593size_written += size ; 2594 } 2595 2596size_t n_bytes ()override { 2597return size_written ; 2598 } 2599 2600private : 2601const bool skip_tensors ; 2602 2603size_t size_written = 0 ; 2604}; 2605 2606class llama_io_write_host :public llama_io_write_i { 2607public : 2608llama_io_write_host ( 2609uint8_t * p ,size_t len ) :ptr (p ),buf_size (len ) {} 2610 2611 ~llama_io_write_host () { 2612// TODO: add backend support to batch tensor_get? or some other way to speed this up 2613for (const auto & winfo :winfos ) { 2614ggml_backend_tensor_get (winfo .tensor ,winfo .ptr ,winfo .offset ,winfo .size ); 2615 } 2616 } 2617 2618void write (const void * src ,size_t size )override { 2619if (size > buf_size ) { 2620throw std::runtime_error ("unexpectedly reached end of buffer" ); 2621 } 2622memcpy (ptr ,src ,size ); 2623ptr += size ; 2624size_written += size ; 2625buf_size -= size ; 2626 } 2627 2628void write_tensor (ggml_tensor * tensor ,size_t offset ,size_t size )override { 2629if (size > buf_size ) { 2630throw std::runtime_error ("unexpectedly reached end of buffer" ); 2631 } 2632 2633// save the write for later during destruction 2634winfos .push_back ({tensor ,ptr ,size ,offset }); 2635 2636ptr += size ; 2637size_written += size ; 2638buf_size -= size ; 2639 } 2640 2641size_t n_bytes ()override { 2642return size_written ; 2643 } 2644 2645private : 2646uint8_t * ptr ; 2647size_t buf_size = 0 ; 2648size_t size_written = 0 ; 2649 2650struct write_info { 2651ggml_tensor * tensor ; 2652uint8_t * ptr ; 2653size_t size ; 2654size_t offset ; 2655 }; 2656 std::vector < write_info > winfos ; 2657}; 2658 2659class llama_io_read_host :public llama_io_read_i { 2660public : 2661llama_io_read_host (const uint8_t * p ,size_t len ) :ptr (p ),buf_size (len ) {} 2662 2663 ~llama_io_read_host () { 2664// flush the reads 2665for (const auto & rinfo :rinfos ) { 2666ggml_backend_tensor_set (rinfo .tensor ,rinfo .ptr ,rinfo .offset ,rinfo .size ); 2667 } 2668 } 2669 2670void read (void * dst ,size_t size )override { 2671if (size > buf_size ) { 2672throw std::runtime_error ("unexpectedly reached end of buffer" ); 2673 } 2674memcpy (dst ,ptr ,size ); 2675ptr += size ; 2676size_read += size ; 2677buf_size -= size ; 2678 } 2679 2680void read_tensor (ggml_tensor * tensor ,size_t offset ,size_t size )override { 2681if (size > buf_size ) { 2682throw std::runtime_error ("unexpectedly reached end of buffer" ); 2683 } 2684 2685// save for later during destruction 2686rinfos .push_back ({tensor ,ptr ,size ,offset }); 2687 2688ptr += size ; 2689size_read += size ; 2690buf_size -= size ; 2691 } 2692 2693size_t n_bytes ()override { 2694return size_read ; 2695 } 2696 2697private : 2698const uint8_t * ptr ; 2699size_t buf_size = 0 ; 2700size_t size_read = 0 ; 2701 2702struct read_info { 2703ggml_tensor * tensor ; 2704const uint8_t * ptr ; 2705size_t size ; 2706size_t offset ; 2707 }; 2708 std::vector < read_info > rinfos ; 2709}; 2710 2711class llama_io_write_file :public llama_io_write_i { 2712public : 2713llama_io_write_file (llama_file * f ) :file (f ) {} 2714 2715void write (const void * src ,size_t size )override { 2716file -> write_raw (src ,size ); 2717size_written += size ; 2718 } 2719 2720void write_tensor (ggml_tensor * tensor ,size_t offset ,size_t size )override { 2721temp_buffer .resize (size ); 2722ggml_backend_tensor_get (tensor ,temp_buffer .data (),offset ,size ); 2723write (temp_buffer .data (),temp_buffer .size ()); 2724 } 2725 2726size_t n_bytes ()override { 2727return size_written ; 2728 } 2729 2730private : 2731llama_file * file ; 2732size_t size_written = 0 ; 2733 std::vector < uint8_t > temp_buffer ; 2734}; 2735 2736class llama_io_read_file :public llama_io_read_i { 2737public : 2738llama_io_read_file (llama_file * f ) :file (f ) {} 2739 2740void read (void * dst ,size_t size )override { 2741file -> read_raw (dst ,size ); 2742size_read += size ; 2743 } 2744 2745void read_tensor (ggml_tensor * tensor ,size_t offset ,size_t size )override { 2746temp_buffer .resize (size ); 2747read (temp_buffer .data (),size ); 2748ggml_backend_tensor_set (tensor ,temp_buffer .data (),offset ,size ); 2749 } 2750 2751size_t n_bytes ()override { 2752return size_read ; 2753 } 2754 2755private : 2756llama_file * file ; 2757size_t size_read = 0 ; 2758 std::vector < uint8_t > temp_buffer ; 2759}; 2760 2761class llama_io_write_device :public llama_io_write_i { 2762public : 2763llama_io_write_device (uint8_t * p ,size_t len ,llama_memory_buffers & mbufs ) :ptr (p ),buf_size (len ),mbufs (mbufs ) { 2764 } 2765 2766 ~llama_io_write_device () { 2767llama_memory_buffers mbufs_new ; 2768 2769for (const auto & winfo :winfos ) { 2770auto * buft = ggml_backend_buffer_get_type (winfo .tensor -> buffer ); 2771 2772mbufs_new [buft ].n_tensors ++ ; 2773mbufs_new [buft ].total_size += winfo .size ; 2774 } 2775 2776for (auto & [buft ,mbuf ] :mbufs_new ) { 2777ggml_init_params params = { 2778/*.mem_size =*/ 2 * mbuf .n_tensors * ggml_tensor_overhead (), 2779/*.mem_buffer =*/ NULL , 2780/*.no_alloc =*/ true, 2781 }; 2782 2783mbuf .ctx .reset (ggml_init (params )); 2784 2785mbuf .org .reserve (mbuf .n_tensors ); 2786mbuf .cpy .reserve (mbuf .n_tensors ); 2787 } 2788 2789for (const auto & winfo :winfos ) { 2790auto * buft = ggml_backend_buffer_get_type (winfo .tensor -> buffer ); 2791 2792const int64_t n = winfo .size /ggml_element_size (winfo .tensor ); 2793 2794auto & mbuf = mbufs_new [buft ]; 2795 2796mbuf .org .push_back (ggml_view_1d (mbuf .ctx .get (),winfo .tensor ,n ,winfo .offset )); 2797mbuf .cpy .push_back (ggml_new_tensor_1d (mbuf .ctx .get (),winfo .tensor -> type ,n )); 2798 } 2799 2800for (auto & [buft ,mbuf ] :mbufs_new ) { 2801auto & mbuf_cur = mbufs [buft ]; 2802 2803bool need_alloc = false; 2804 2805need_alloc = need_alloc || (!mbuf_cur .buf ); 2806need_alloc = need_alloc || (mbuf_cur .org .size ()!= mbuf .org .size ()); 2807need_alloc = need_alloc || (mbuf_cur .total_size != mbuf .total_size ); 2808 2809if (!need_alloc ) { 2810for (size_t i = 0 ;i < mbuf_cur .org .size ();++ i ) { 2811auto * org0 = mbuf_cur .org [i ]; 2812auto * org1 = mbuf .org [i ]; 2813 2814if (!ggml_are_same_shape (org0 ,org1 )) { 2815need_alloc = true; 2816break ; 2817 } 2818 2819if (org0 -> view_src != org1 -> view_src || org0 -> view_offs != org1 -> view_offs ) { 2820need_alloc = true; 2821break ; 2822 } 2823 } 2824 } 2825 2826if (need_alloc ) { 2827if (!mbuf_cur .buf || mbuf_cur .total_size != mbuf .total_size ) { 2828mbuf_cur = std::move (mbuf ); 2829 2830mbuf_cur .buf .reset (ggml_backend_alloc_ctx_tensors_from_buft (mbuf_cur .ctx .get (),buft )); 2831 2832LLAMA_LOG_INFO ("%s: allocated '%s' buffer %.3f MiB\n" ,__func__ ,ggml_backend_buft_name (buft ),mbuf .total_size /1024.0 /1024.0 ); 2833 }else { 2834//LLAMA_LOG_INFO("%s: reallocating tensors in '%s' buffer %.3f MiB\n", __func__, ggml_backend_buft_name(buft), mbuf.total_size/1024.0/1024.0); 2835 2836// save the old buffer and allocate the new tensors in it 2837auto buf = std::move (mbuf_cur .buf ); 2838 2839mbuf_cur = std::move (mbuf ); 2840 2841ggml_tallocr talloc = ggml_tallocr_new (buf .get ()); 2842 2843for (size_t i = 0 ;i < mbuf_cur .org .size ();++ i ) { 2844ggml_backend_view_init (mbuf_cur .org [i ]); 2845ggml_tallocr_alloc (& talloc ,mbuf_cur .cpy [i ]); 2846 } 2847 2848mbuf_cur .buf = std::move (buf ); 2849 } 2850 } 2851 2852for (size_t i = 0 ;i < mbuf_cur .org .size ();++ i ) { 2853ggml_backend_tensor_copy (mbuf_cur .org [i ],mbuf_cur .cpy [i ]); 2854 } 2855 } 2856 } 2857 2858void write (const void * src ,size_t size )override { 2859if (size > buf_size ) { 2860throw std::runtime_error ("unexpectedly reached end of buffer" ); 2861 } 2862memcpy (ptr ,src ,size ); 2863ptr += size ; 2864size_written += size ; 2865buf_size -= size ; 2866 } 2867 2868void write_tensor (ggml_tensor * tensor ,size_t offset ,size_t size )override { 2869// save the write for later during destruction 2870winfos .push_back ({tensor ,ptr ,size ,offset }); 2871 } 2872 2873size_t n_bytes ()override { 2874return size_written ; 2875 } 2876 2877private : 2878uint8_t * ptr ; 2879size_t buf_size = 0 ; 2880size_t size_written = 0 ; 2881 2882struct write_info { 2883ggml_tensor * tensor ; 2884uint8_t * ptr ; 2885size_t size ; 2886size_t offset ; 2887 }; 2888 std::vector < write_info > winfos ; 2889 2890llama_memory_buffers & mbufs ; 2891}; 2892 2893class llama_io_read_device :public llama_io_read_i { 2894public : 2895llama_io_read_device (const uint8_t * p ,size_t len ,const llama_memory_buffers & mbufs ) :ptr (p ),buf_size (len ),mbufs (mbufs ) { 2896 } 2897 2898 ~llama_io_read_device () { 2899llama_memory_buffers mbufs_new ; 2900 2901for (const auto & rinfo :rinfos ) { 2902auto * buft = ggml_backend_buffer_get_type (rinfo .tensor -> buffer ); 2903 2904mbufs_new [buft ].n_tensors ++ ; 2905mbufs_new [buft ].total_size += rinfo .size ; 2906 } 2907 2908for (auto & [buft ,mbuf ] :mbufs_new ) { 2909ggml_init_params params = { 2910/*.mem_size =*/ mbuf .n_tensors * ggml_tensor_overhead (), 2911/*.mem_buffer =*/ NULL , 2912/*.no_alloc =*/ true, 2913 }; 2914 2915mbuf .ctx .reset (ggml_init (params )); 2916 2917mbuf .org .reserve (mbuf .n_tensors ); 2918 } 2919 2920for (const auto & rinfo :rinfos ) { 2921auto * buft = ggml_backend_buffer_get_type (rinfo .tensor -> buffer ); 2922 2923const int64_t n = rinfo .size /ggml_element_size (rinfo .tensor ); 2924 2925auto & mbuf = mbufs_new [buft ]; 2926 2927mbuf .org .push_back (ggml_view_1d (mbuf .ctx .get (),rinfo .tensor ,n ,rinfo .offset )); 2928 2929ggml_backend_view_init (mbuf .org .back ()); 2930 } 2931 2932for (auto & [buft ,mbuf ] :mbufs_new ) { 2933const auto & mbuf_cur = mbufs .at (buft ); 2934 2935if (!mbuf_cur .buf || mbuf_cur .total_size != mbuf .total_size ) { 2936GGML_ABORT ("%s: memory buffer mismatch\n" ,__func__ ); 2937 } 2938 2939if (mbuf_cur .n_tensors == mbuf .n_tensors ) { 2940// an equal tensor count does not imply the same chunking, e.g. save ranges [2,1] vs restore runs [1,2] 2941bool same_chunking = true; 2942for (size_t i = 0 ;i < mbuf_cur .org .size ();++ i ) { 2943if (ggml_nbytes (mbuf_cur .cpy [i ])!= ggml_nbytes (mbuf .org [i ])) { 2944same_chunking = false; 2945break ; 2946 } 2947 } 2948 2949if (same_chunking ) { 2950// same chunking: copy 1:1 by index 2951for (size_t i = 0 ;i < mbuf_cur .org .size ();++ i ) { 2952ggml_backend_tensor_copy (mbuf_cur .cpy [i ],mbuf .org [i ]); 2953 } 2954continue ; 2955 } 2956 } 2957 2958// different chunking: copy the write-side data (mbuf_cur.cpy) into the read-side targets (mbuf.org) 2959// with a byte cursor. Write and read enumerate the same logical data in the same order but may chunk 2960// it differently (even with an equal number of tensors), so copy across tensor boundaries rather than 2961// 1:1 by index. 2962const size_t total = mbuf_cur .total_size ; 2963 2964ggml_init_params params_scratch = { 2965/*.mem_size =*/ 2 * (mbuf_cur .cpy .size ()+ mbuf .org .size ())* ggml_tensor_overhead (), 2966/*.mem_buffer =*/ NULL , 2967/*.no_alloc =*/ true, 2968 }; 2969ggml_context * ctx_scratch = ggml_init (params_scratch ); 2970 2971size_t src_pos = 0 ; 2972size_t dst_pos = 0 ; 2973size_t src_j = 0 ; 2974size_t dst_i = 0 ; 2975size_t src_base = 0 ; 2976size_t dst_base = 0 ; 2977 2978while (src_pos < total ) { 2979const auto & src_t = mbuf_cur .cpy [src_j ]; 2980const auto & dst_t = mbuf .org [dst_i ]; 2981 2982const size_t src_size = ggml_nbytes (src_t ); 2983const size_t dst_size = ggml_nbytes (dst_t ); 2984 2985const size_t src_off = src_pos - src_base ; 2986const size_t dst_off = dst_pos - dst_base ; 2987 2988const size_t n_copy = std::min (src_size - src_off ,dst_size - dst_off ); 2989 2990const size_t el = ggml_element_size (src_t ); 2991const int64_t n_el = (int64_t ) (n_copy /el ); 2992 2993auto * src_v = ggml_view_1d (ctx_scratch ,src_t ,n_el ,src_off ); 2994ggml_backend_view_init (src_v ); 2995auto * dst_v = ggml_view_1d (ctx_scratch ,dst_t ,n_el ,dst_off ); 2996ggml_backend_view_init (dst_v ); 2997 2998ggml_backend_tensor_copy (src_v ,dst_v ); 2999 3000src_pos += n_copy ; 3001dst_pos += n_copy ; 3002 3003if (src_pos - src_base == src_size ) { 3004src_base = src_pos ; 3005++ src_j ; 3006 } 3007if (dst_pos - dst_base == dst_size ) { 3008dst_base = dst_pos ; 3009++ dst_i ; 3010 } 3011 } 3012 3013GGML_ASSERT (src_pos == total && dst_pos == total ); 3014// any tensors left unvisited hold no data 3015for (size_t i = src_j ;i < mbuf_cur .cpy .size ();++ i ) { 3016GGML_ASSERT (ggml_nbytes (mbuf_cur .cpy [i ])== 0 ); 3017 } 3018for (size_t i = dst_i ;i < mbuf .org .size ();++ i ) { 3019GGML_ASSERT (ggml_nbytes (mbuf .org [i ])== 0 ); 3020 } 3021 3022ggml_free (ctx_scratch ); 3023 } 3024 3025GGML_ASSERT (buf_size == 0 ); 3026 } 3027 3028void read (void * dst ,size_t size )override { 3029if (size > buf_size ) { 3030throw std::runtime_error ("unexpectedly reached end of buffer" ); 3031 } 3032memcpy (dst ,ptr ,size ); 3033ptr += size ; 3034size_read += size ; 3035buf_size -= size ; 3036 } 3037 3038void read_tensor (ggml_tensor * tensor ,size_t offset ,size_t size )override { 3039// save for later during destruction 3040rinfos .push_back ({tensor ,ptr ,size ,offset }); 3041 } 3042 3043size_t n_bytes ()override { 3044return size_read ; 3045 } 3046 3047private : 3048const uint8_t * ptr ; 3049size_t buf_size = 0 ; 3050size_t size_read = 0 ; 3051 3052struct read_info { 3053ggml_tensor * tensor ; 3054const uint8_t * ptr ; 3055size_t size ; 3056size_t offset ; 3057 }; 3058 std::vector < read_info > rinfos ; 3059 3060const llama_memory_buffers & mbufs ; 3061}; 3062 3063size_t llama_context::state_get_size () { 3064llama_io_write_dummy io (false); 3065try { 3066return state_write_data (io ); 3067 }catch (const std::exception & err ) { 3068LLAMA_LOG_ERROR ("%s: error getting state size: %s\n" ,__func__ ,err .what ()); 3069return 0 ; 3070 } 3071} 3072 3073size_t llama_context::state_get_data (uint8_t * dst ,size_t size ) { 3074llama_io_write_host io (dst ,size ); 3075try { 3076return state_write_data (io ); 3077 }catch (const std::exception & err ) { 3078LLAMA_LOG_ERROR ("%s: error saving state: %s\n" ,__func__ ,err .what ()); 3079return 0 ; 3080 } 3081} 3082 3083size_t llama_context::state_set_data (const uint8_t * src ,size_t size ) { 3084llama_io_read_host io (src ,size ); 3085try { 3086return state_read_data (io ); 3087 }catch (const std::exception & err ) { 3088LLAMA_LOG_ERROR ("%s: error loading state: %s\n" ,__func__ ,err .what ()); 3089return 0 ; 3090 } 3091} 3092 3093static constexpr uint32_t io_magic = 0xaf143cd8 ; 3094 3095size_t llama_context::state_seq_get_size (llama_seq_id seq_id ,llama_state_seq_flags flags ) { 3096llama_io_write_dummy io (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE ); 3097try { 3098io .write (& io_magic ,sizeof (io_magic )); 3099io .write (& seq_id ,sizeof (seq_id )); 3100 3101return state_seq_write_data (io ,seq_id ,flags ); 3102 }catch (const std::exception & err ) { 3103LLAMA_LOG_ERROR ("%s: error getting state size: %s\n" ,__func__ ,err .what ()); 3104return 0 ; 3105 } 3106} 3107 3108size_t llama_context::state_seq_get_data (llama_seq_id seq_id ,uint8_t * dst ,size_t size ,llama_state_seq_flags flags ) { 3109 std::unique_ptr < llama_io_write_i > io ; 3110if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE ) { 3111io = std::make_unique < llama_io_write_device > (dst ,size ,mem_storage [seq_id ]); 3112 }else { 3113io = std::make_unique < llama_io_write_host > (dst ,size ); 3114 } 3115 3116try { 3117io -> write (& io_magic ,sizeof (io_magic )); 3118io -> write (& seq_id ,sizeof (seq_id )); 3119 3120return state_seq_write_data (* io ,seq_id ,flags ); 3121 }catch (const std::exception & err ) { 3122LLAMA_LOG_ERROR ("%s: error saving state: %s\n" ,__func__ ,err .what ()); 3123return 0 ; 3124 } 3125} 3126 3127size_t llama_context::state_seq_set_data (llama_seq_id seq_id ,const uint8_t * src ,size_t size ,llama_state_seq_flags flags ) { 3128 std::unique_ptr < llama_io_read_i > io ; 3129if (flags & LLAMA_STATE_SEQ_FLAGS_ON_DEVICE ) { 3130// create a temporary io to read the magic and the src seq_id 3131io = std::make_unique < llama_io_read_host > (src ,size ); 3132 3133uint32_t magic_read ; 3134io -> read (& magic_read ,sizeof (magic_read )); 3135if (io_magic != magic_read ) { 3136throw std::runtime_error ("wrong sequence state magic" ); 3137 } 3138 3139llama_seq_id seq_id_read ; 3140io -> read (& seq_id_read ,sizeof (seq_id_read )); 3141 3142GGML_ASSERT (mem_storage .find (seq_id_read )!= mem_storage .end ()); 3143 3144io = std::make_unique < llama_io_read_device > (src ,size ,mem_storage [seq_id_read ]); 3145 }else { 3146io = std::make_unique < llama_io_read_host > (src ,size ); 3147 } 3148 3149try { 3150uint32_t magic_read ; 3151io -> read (& magic_read ,sizeof (magic_read )); 3152if (io_magic != magic_read ) { 3153throw std::runtime_error ("wrong sequence state magic" ); 3154 } 3155 3156llama_seq_id seq_id_read ; 3157io -> read (& seq_id_read ,sizeof (seq_id_read )); 3158 3159return state_seq_read_data (* io ,seq_id ,flags ); 3160 }catch (const std::exception & err ) { 3161LLAMA_LOG_ERROR ("%s: error loading state: %s\n" ,__func__ ,err .what ()); 3162return 0 ; 3163 } 3164} 3165 3166bool llama_context::state_load_file (const char * filepath ,llama_token * tokens_out ,size_t n_token_capacity ,size_t * n_token_count_out ) { 3167llama_file file (filepath ,"rb" ); 3168 3169// sanity checks 3170 { 3171const uint32_t magic = file .read_u32 (); 3172const uint32_t version = file .read_u32 (); 3173 3174if (magic != LLAMA_SESSION_MAGIC || version != LLAMA_SESSION_VERSION ) { 3175LLAMA_LOG_ERROR ("%s: unknown (magic, version) for session file: %08x, %08x\n" ,__func__ ,magic ,version ); 3176return false; 3177 } 3178 } 3179 3180// load the prompt 3181 { 3182const uint32_t n_token_count = file .read_u32 (); 3183 3184if (n_token_count > n_token_capacity ) { 3185LLAMA_LOG_ERROR ("%s: token count in session file exceeded capacity! %u > %zu\n" ,__func__ ,n_token_count ,n_token_capacity ); 3186return false; 3187 } 3188 3189file .read_raw (tokens_out ,sizeof (llama_token )* n_token_count ); 3190* n_token_count_out = n_token_count ; 3191 } 3192 3193// restore the context state 3194 { 3195const size_t n_state_size_cur = file .size ()- file .tell (); 3196 3197llama_io_read_file io (& file ); 3198const size_t n_read = state_read_data (io ); 3199 3200if (n_read != n_state_size_cur ) { 3201LLAMA_LOG_ERROR ("%s: did not read all of the session file data! size %zu, got %zu\n" ,__func__ ,n_state_size_cur ,n_read ); 3202return false; 3203 } 3204 } 3205 3206return true; 3207} 3208 3209bool llama_context::state_save_file (const char * filepath ,const llama_token * tokens ,size_t n_token_count ) { 3210llama_file file (filepath ,"wb" ); 3211 3212file .write_u32 (LLAMA_SESSION_MAGIC ); 3213file .write_u32 (LLAMA_SESSION_VERSION ); 3214 3215// save the prompt 3216file .write_u32 ((uint32_t )n_token_count ); 3217file .write_raw (tokens ,sizeof (llama_token )* n_token_count ); 3218 3219// save the context state using stream saving 3220llama_io_write_file io (& file ); 3221state_write_data (io ); 3222 3223return true; 3224} 3225 3226size_t llama_context::state_seq_load_file (llama_seq_id seq_id ,const char * filepath ,llama_token * tokens_out ,size_t n_token_capacity ,size_t * n_token_count_out ) { 3227llama_file file (filepath ,"rb" ); 3228 3229// version checks 3230 { 3231const uint32_t magic = file .read_u32 (); 3232const uint32_t version = file .read_u32 (); 3233 3234if (magic != LLAMA_STATE_SEQ_MAGIC || version != LLAMA_STATE_SEQ_VERSION ) { 3235LLAMA_LOG_ERROR ("%s: unknown (magic, version) for sequence state file: %08x, %08x\n" ,__func__ ,magic ,version ); 3236return 0 ; 3237 } 3238 } 3239 3240// load the prompt 3241 { 3242const uint32_t n_token_count = file .read_u32 (); 3243 3244if (tokens_out == nullptr ) { 3245const size_t n_token_max = (file .size ()- file .tell ()) /sizeof (llama_token ); 3246if (n_token_count > n_token_max ) { 3247LLAMA_LOG_ERROR ("%s: token count in sequence state file exceeds the file size! %u > %zu\n" ,__func__ ,n_token_count ,n_token_max ); 3248return 0 ; 3249 } 3250 3251* n_token_count_out = n_token_count ; 3252return file .tell (); 3253 } 3254 3255if (n_token_count > n_token_capacity ) { 3256LLAMA_LOG_ERROR ("%s: token count in sequence state file exceeded capacity! %u > %zu\n" ,__func__ ,n_token_count ,n_token_capacity ); 3257return 0 ; 3258 } 3259 3260file .read_raw (tokens_out ,sizeof (llama_token )* n_token_count ); 3261* n_token_count_out = n_token_count ; 3262 } 3263 3264// restore the context state 3265 { 3266const size_t state_size = file .size ()- file .tell (); 3267llama_io_read_file io (& file ); 3268const size_t nread = state_seq_read_data (io ,seq_id ,0 ); 3269if (!nread ) { 3270LLAMA_LOG_ERROR ("%s: failed to restore sequence state\n" ,__func__ ); 3271return 0 ; 3272 } 3273GGML_ASSERT (nread <=state_size ); 3274GGML_ASSERT (nread + sizeof (uint32_t )* 3 + sizeof (llama_token )* * n_token_count_out == file .tell ()); 3275 } 3276 3277return file .tell (); 3278} 3279 3280size_t llama_context::state_seq_save_file (llama_seq_id seq_id ,const char * filepath ,const llama_token * tokens ,size_t n_token_count ) { 3281llama_file file (filepath ,"wb" ); 3282 3283file .write_u32 (LLAMA_STATE_SEQ_MAGIC ); 3284file .write_u32 (LLAMA_STATE_SEQ_VERSION ); 3285 3286// save the prompt 3287file .write_u32 ((uint32_t )n_token_count ); 3288file .write_raw (tokens ,sizeof (llama_token )* n_token_count ); 3289 3290// save the context state using stream saving 3291llama_io_write_file io (& file ); 3292state_seq_write_data (io ,seq_id ,0 ); 3293 3294const size_t res = file .tell (); 3295GGML_ASSERT (res == sizeof (uint32_t )* 3 + sizeof (llama_token )* n_token_count + io .n_bytes ()); 3296 3297return res ; 3298} 3299 3300size_t llama_context::state_write_data (llama_io_write_i & io ) { 3301LLAMA_LOG_DEBUG ("%s: writing state\n" ,__func__ ); 3302 3303// write model info 3304 { 3305LLAMA_LOG_DEBUG ("%s: - writing model info\n" ,__func__ ); 3306 3307const std::string arch_str = llm_arch_name (model .arch ); 3308io .write_string (arch_str ); 3309// TODO: add more model-specific info which should prevent loading the session file if not identical 3310 } 3311 3312if (memory != nullptr ) { 3313LLAMA_LOG_DEBUG ("%s: - writing memory module\n" ,__func__ ); 3314memory -> state_write (io ); 3315 } 3316 3317return io .n_bytes (); 3318} 3319 3320size_t llama_context::state_read_data (llama_io_read_i & io ) { 3321LLAMA_LOG_DEBUG ("%s: reading state\n" ,__func__ ); 3322 3323// read model info 3324 { 3325LLAMA_LOG_DEBUG ("%s: - reading model info\n" ,__func__ ); 3326 3327const std::string cur_arch_str = llm_arch_name (model .arch ); 3328 3329 std::string arch_str ; 3330io .read_string (arch_str ); 3331if (cur_arch_str != arch_str ) { 3332throw std::runtime_error (format ("wrong model arch: '%s' instead of '%s'" ,arch_str .c_str (),cur_arch_str .c_str ())); 3333 } 3334// TODO: add more info which needs to be identical but which is not verified otherwise 3335 } 3336 3337if (memory ) { 3338LLAMA_LOG_DEBUG ("%s: - reading memory module\n" ,__func__ ); 3339 3340memory -> state_read (io ); 3341 } 3342 3343return io .n_bytes (); 3344} 3345 3346size_t llama_context::state_seq_write_data (llama_io_write_i & io ,llama_seq_id seq_id ,llama_state_seq_flags flags ) { 3347if (memory ) { 3348memory -> state_write (io ,seq_id ,flags ); 3349 } 3350 3351return io .n_bytes (); 3352} 3353 3354size_t llama_context::state_seq_read_data (llama_io_read_i & io ,llama_seq_id seq_id ,llama_state_seq_flags flags ) { 3355if (memory ) { 3356memory -> state_read (io ,seq_id ,flags ); 3357 } 3358 3359return io .n_bytes (); 3360} 3361 3362// 3363// perf 3364// 3365 3366llama_perf_context_data llama_context::perf_get_data ()const { 3367llama_perf_context_data data = {}; 3368 3369data .t_start_ms = 1e-3 * t_start_us ; 3370data .t_load_ms = 1e-3 * t_load_us ; 3371data .t_p_eval_ms = 1e-3 * t_p_eval_us ; 3372data .t_eval_ms = 1e-3 * t_eval_us ; 3373data .n_p_eval = std::max (1 ,n_p_eval ); 3374data .n_eval = std::max (1 ,n_eval ); 3375data .n_reused = std::max (0 ,n_reused ); 3376 3377return data ; 3378} 3379 3380void llama_context::perf_reset () { 3381t_start_us = ggml_time_us (); 3382t_eval_us = n_eval = 0 ; 3383t_p_eval_us = n_p_eval = 0 ; 3384n_reused = 0 ; 3385} 3386 3387llama_memory_breakdown llama_context::memory_breakdown ()const { 3388 std::map < ggml_backend_buffer_type_t ,llama_memory_breakdown_data > ret ; 3389for (const auto & [buft ,size ] :model .memory_breakdown ()) { 3390ret [buft ].model += size ; 3391 } 3392if (memory ) { 3393for (const auto & [buft ,size ] :memory -> memory_breakdown ()) { 3394ret [buft ].context += size ; 3395 } 3396 } 3397if (model .hparams .no_alloc ) { 3398for (size_t i = 0 ;i < backends .size ();++ i ) { 3399ggml_backend_t backend = backends [i ].get (); 3400ggml_backend_buffer_type_t buft = ggml_backend_sched_get_buffer_type (sched .get (),backend ); 3401ret [buft ].compute += backend_buf_exp_size [i ]; 3402 } 3403 }else { 3404for (const auto & backend_ptr :backends ) { 3405ggml_backend_t backend = backend_ptr .get (); 3406ggml_backend_buffer_type_t buft = ggml_backend_sched_get_buffer_type (sched .get (),backend ); 3407ret [buft ].compute += ggml_backend_sched_get_buffer_size (sched .get (),backend ); 3408 } 3409 } 3410return ret ; 3411} 3412 3413// 3414// training 3415// 3416 3417static void llama_set_param (struct ggml_tensor * tensor ,llama_opt_param_filter param_filter ,void * userdata ) { 3418if (!tensor || tensor -> type != GGML_TYPE_F32 ) { 3419return ; 3420 } 3421if (!param_filter (tensor ,userdata )) { 3422return ; 3423 } 3424if (strcmp (tensor -> name ,"token_embd.weight" )== 0 ) { 3425return ;// FIXME 3426 } 3427if (strcmp (tensor -> name ,"rope_freqs.weight" )== 0 ) { 3428return ;// FIXME 3429 } 3430ggml_set_param (tensor ); 3431} 3432 3433void llama_context::opt_init (struct llama_model * model ,struct llama_opt_params lopt_params ) { 3434GGML_ASSERT (!opt_ctx ); 3435model -> hparams .n_ctx_train = lopt_params .n_ctx_train > 0 ?lopt_params .n_ctx_train :n_ctx (); 3436const uint32_t n_batch = std::min (this -> n_batch (),model -> hparams .n_ctx_train ); 3437const uint32_t n_ubatch = std::min (this -> n_ubatch (),n_batch ); 3438GGML_ASSERT (model -> hparams .n_ctx_train %n_batch == 0 ); 3439GGML_ASSERT (n_batch %n_ubatch == 0 ); 3440 3441if (cparams .flash_attn ) { 3442LLAMA_LOG_INFO ("%s: disabling flash attention, FLASH_ATTN_EXT has no backward pass\n" ,__func__ ); 3443cparams .flash_attn = false; 3444 3445// the graph changes without flash attention, need to reserve again 3446sched_need_reserve = true; 3447sched_reserve (); 3448 } 3449 3450ggml_opt_params opt_params = ggml_opt_default_params (sched .get (),GGML_OPT_LOSS_TYPE_CROSS_ENTROPY ); 3451opt_params .opt_period = n_batch /n_ubatch ; 3452opt_params .get_opt_pars = lopt_params .get_opt_pars ; 3453opt_params .get_opt_pars_ud = lopt_params .get_opt_pars_ud ; 3454opt_params .optimizer = lopt_params .optimizer_type ; 3455opt_ctx = ggml_opt_init (opt_params ); 3456 3457llama_opt_param_filter param_filter = lopt_params .param_filter ; 3458void * param_filter_ud = lopt_params .param_filter_ud ; 3459 3460//llama_set_param(model->tok_embd, param_filter, param_filter_ud); // FIXME 3461llama_set_param (model -> type_embd ,param_filter ,param_filter_ud ); 3462llama_set_param (model -> pos_embd ,param_filter ,param_filter_ud ); 3463llama_set_param (model -> tok_norm ,param_filter ,param_filter_ud ); 3464llama_set_param (model -> tok_norm_b ,param_filter ,param_filter_ud ); 3465llama_set_param (model -> output_norm ,param_filter ,param_filter_ud ); 3466llama_set_param (model -> output_norm_b ,param_filter ,param_filter_ud ); 3467llama_set_param (model -> output ,param_filter ,param_filter_ud ); 3468llama_set_param (model -> output_b ,param_filter ,param_filter_ud ); 3469llama_set_param (model -> output_norm_enc ,param_filter ,param_filter_ud ); 3470llama_set_param (model -> cls ,param_filter ,param_filter_ud ); 3471llama_set_param (model -> cls_b ,param_filter ,param_filter_ud ); 3472llama_set_param (model -> cls_out ,param_filter ,param_filter_ud ); 3473llama_set_param (model -> cls_out_b ,param_filter ,param_filter_ud ); 3474llama_set_param (model -> cls_norm ,param_filter ,param_filter_ud ); 3475 3476for (struct llama_layer & layer :model -> layers ) { 3477for (size_t i = 0 ;i < sizeof (layer )/sizeof (struct ggml_tensor * );++ i ) { 3478llama_set_param (reinterpret_cast < struct ggml_tensor **> (& layer )[i ],param_filter ,param_filter_ud ); 3479 } 3480 } 3481} 3482 3483void llama_context::opt_epoch_iter ( 3484ggml_opt_dataset_t dataset , 3485ggml_opt_result_t result , 3486const std::vector < llama_token > & tokens , 3487const std::vector < llama_token > & labels_sparse , 3488llama_batch & batch , 3489ggml_opt_epoch_callback callback , 3490bool train , 3491int64_t idata_in_loop , 3492int64_t ndata_in_loop , 3493int64_t t_loop_start ) { 3494GGML_ASSERT (opt_ctx ); 3495const uint32_t n_ctx = llama_model_n_ctx_train (& model ); 3496const uint32_t n_batch = std::min (this -> n_batch (),n_ctx ); 3497const uint32_t n_ubatch = std::min (this -> n_ubatch (),n_batch ); 3498 3499memory -> clear (true); 3500 3501for (uint32_t pos_ctx = 0 ;pos_ctx < n_ctx ;pos_ctx += n_batch ) { 3502batch .n_tokens = n_batch ; 3503for (uint32_t pos_batch = 0 ;pos_batch < n_batch ;++ pos_batch ) { 3504batch .token [pos_batch ]= tokens [pos_ctx + pos_batch ]; 3505batch .pos [pos_batch ]= pos_ctx + pos_batch ; 3506batch .n_seq_id [pos_batch ]= 1 ; 3507batch .seq_id [pos_batch ][0 ]= 0 ; 3508batch .logits [pos_batch ]= true; 3509 } 3510 3511if (!balloc -> init (batch ,model .vocab ,nullptr ,model .hparams .n_embd_inp (),cparams .kv_unified ?LLAMA_MAX_SEQ :cparams .n_seq_max , true)) { 3512LLAMA_LOG_ERROR ("%s: failed to initialize batch\n" ,__func__ ); 3513return ; 3514 } 3515 3516const uint32_t n_tokens_all = balloc -> get_n_tokens (); 3517 3518n_queued_tokens += n_tokens_all ; 3519 3520embd_seq .clear (); 3521 3522uint32_t n_outputs_all = n_tokens_all ; 3523 3524auto mctx = memory -> init_batch (* balloc ,cparams .n_ubatch , true); 3525if (!mctx || mctx -> get_status ()!= LLAMA_MEMORY_STATUS_SUCCESS ) { 3526LLAMA_LOG_ERROR ("%s: could not initialize batch\n" ,__func__ ); 3527break ; 3528 } 3529 3530// reserve output buffer 3531if (output_reserve (n_outputs_all )< n_outputs_all ) { 3532LLAMA_LOG_ERROR ("%s: could not reserve space for batch with %d outputs\n" ,__func__ ,n_outputs_all ); 3533GGML_ABORT ("TODO: handle this error" ); 3534 }; 3535 3536uint32_t pos_batch = 0 ; 3537do { 3538const auto & ubatch = mctx -> get_ubatch (); 3539 3540n_outputs = ubatch .n_tokens ; 3541 3542if (!mctx -> apply ()) { 3543LLAMA_LOG_ERROR ("%s: failed to update the memory context\n" ,__func__ ); 3544break ; 3545 } 3546 3547auto * res = get_gf_res_prev (); 3548 3549const auto gparams = graph_params (res ,ubatch ,mctx .get (),ctx_type_to_graph_type (cparams .ctx_type )); 3550 3551// the optimizer graph is allocated outside sched, so the next decode must rebuild 3552gf_res_prev_active = nullptr ; 3553res -> reset (); 3554 3555auto * gf = model .build_graph (gparams ); 3556 3557struct ggml_context * ctx_compute_opt ; 3558 { 3559const size_t size_gf = ggml_graph_size (gf ); 3560const size_t size_meta = 4 * size_gf * ggml_tensor_overhead ()+ 2 * ggml_graph_overhead_custom (size_gf ,/*grads = */ true); 3561struct ggml_init_params params = { 3562/*.mem_size =*/ size_meta , 3563/*.mem_buffer =*/ nullptr , 3564/*.no_alloc =*/ true, 3565 }; 3566ctx_compute_opt = ggml_init (params ); 3567 } 3568ggml_opt_prepare_alloc (opt_ctx ,ctx_compute_opt ,gf ,res -> get_inp_tokens (),res -> get_logits ()); 3569ggml_opt_alloc (opt_ctx ,train ); 3570 3571res -> set_inputs (& ubatch ); 3572 { 3573struct ggml_tensor * labels = ggml_opt_labels (opt_ctx ); 3574GGML_ASSERT (labels -> ne [1 ]== n_ubatch ); 3575ggml_set_zero (labels ); 3576const float onef = 1.0f ; 3577for (uint32_t pos_ubatch = 0 ;pos_ubatch < n_ubatch ;++ pos_ubatch ) { 3578const uint32_t ilabel = pos_ctx + pos_batch + pos_ubatch ; 3579GGML_ASSERT (labels_sparse [ilabel ]< labels -> ne [0 ]); 3580ggml_backend_tensor_set (labels ,& onef , (pos_ubatch * labels -> ne [0 ]+ labels_sparse [ilabel ])* sizeof (float ),sizeof (float )); 3581 } 3582 } 3583ggml_opt_eval (opt_ctx ,result ); 3584if (callback ) { 3585callback (train ,opt_ctx ,dataset ,result ,idata_in_loop + (pos_ctx + pos_batch )/n_ubatch + 1 ,ndata_in_loop ,t_loop_start ); 3586 } 3587ggml_free (ctx_compute_opt ); 3588 3589pos_batch += ubatch .n_tokens ; 3590 }while (mctx -> next ()); 3591 } 3592} 3593 3594void llama_context::opt_epoch ( 3595ggml_opt_dataset_t dataset , 3596ggml_opt_result_t result_train , 3597ggml_opt_result_t result_eval , 3598int64_t idata_split , 3599ggml_opt_epoch_callback callback_train , 3600ggml_opt_epoch_callback callback_eval ) { 3601const uint32_t n_ctx = this -> n_ctx (); 3602const uint32_t n_batch = std::min (cparams .n_batch ,n_ctx ); 3603const uint32_t n_ubatch = std::min (cparams .n_ubatch ,n_batch ); 3604const int64_t ndata = ggml_opt_dataset_ndata (dataset ); 3605 3606GGML_ASSERT (idata_split >=0 ); 3607GGML_ASSERT (idata_split <=ndata ); 3608 3609const uint32_t ubatch_per_ctx = n_ctx /n_ubatch ; 3610 3611struct llama_batch batch = llama_batch_init (n_batch ,0 ,1 ); 3612 std::vector < llama_token > tokens (n_ctx ); 3613 std::vector < llama_token > labels_sparse (n_ctx ); 3614 3615int64_t idata = 0 ; 3616 3617int64_t t_loop_start = ggml_time_us (); 3618int64_t ndata_in_loop = idata_split * ubatch_per_ctx ; 3619for (;idata < idata_split ;++ idata ) { 3620constexpr bool train = true; 3621const int64_t idata_in_loop = idata * ubatch_per_ctx ; 3622 3623ggml_opt_dataset_get_batch_host (dataset ,tokens .data (),n_ctx * sizeof (llama_token ),labels_sparse .data (),idata ); 3624opt_epoch_iter (dataset ,result_train ,tokens ,labels_sparse ,batch , 3625callback_train ,train ,idata_in_loop ,ndata_in_loop ,t_loop_start ); 3626 } 3627 3628t_loop_start = ggml_time_us (); 3629ndata_in_loop = (ndata - idata_split )* ubatch_per_ctx ; 3630for (;idata < ndata ;++ idata ) { 3631constexpr bool train = false; 3632const int64_t idata_in_loop = (idata - idata_split )* ubatch_per_ctx ; 3633 3634ggml_opt_dataset_get_batch_host (dataset ,tokens .data (),n_ctx * sizeof (llama_token ),labels_sparse .data (),idata ); 3635opt_epoch_iter (dataset ,result_eval ,tokens ,labels_sparse ,batch , 3636callback_eval ,train ,idata_in_loop ,ndata_in_loop ,t_loop_start ); 3637 } 3638 3639llama_batch_free (batch ); 3640} 3641 3642// 3643// interface implementation 3644// 3645 3646llama_context_params llama_context_default_params () { 3647llama_context_params result = { 3648/*.n_ctx =*/ 512 , 3649/*.n_batch =*/ 2048 , 3650/*.n_ubatch =*/ 512 , 3651/*.n_seq_max =*/ 1 , 3652/*.n_rs_seq =*/ 0 , 3653/*.n_outputs_max =*/ 0 , 3654/*.n_outputs_max_per_seq =*/ 1 , 3655/*.n_threads =*/ GGML_DEFAULT_N_THREADS ,// TODO: better default 3656/*.n_threads_batch =*/ GGML_DEFAULT_N_THREADS , 3657/*.ctx_type =*/ LLAMA_CONTEXT_TYPE_DEFAULT , 3658/*.rope_scaling_type =*/ LLAMA_ROPE_SCALING_TYPE_UNSPECIFIED , 3659/*.pooling_type =*/ LLAMA_POOLING_TYPE_UNSPECIFIED , 3660/*.attention_type =*/ LLAMA_ATTENTION_TYPE_UNSPECIFIED , 3661/*.flash_attn_type =*/ LLAMA_FLASH_ATTN_TYPE_AUTO , 3662/*.rope_freq_base =*/ 0.0f , 3663/*.rope_freq_scale =*/ 0.0f , 3664/*.yarn_ext_factor =*/ -1.0f , 3665/*.yarn_attn_factor =*/ -1.0f , 3666/*.yarn_beta_fast =*/ -1.0f , 3667/*.yarn_beta_slow =*/ -1.0f , 3668/*.yarn_orig_ctx =*/ 0 , 3669/*.defrag_thold =*/ -1.0f , 3670/*.cb_eval =*/ nullptr , 3671/*.cb_eval_user_data =*/ nullptr , 3672/*.type_k =*/ GGML_TYPE_F16 , 3673/*.type_v =*/ GGML_TYPE_F16 , 3674/*.abort_callback =*/ nullptr , 3675/*.abort_callback_data =*/ nullptr , 3676/*.embeddings =*/ false, 3677/*.offload_kqv =*/ true, 3678/*.no_perf =*/ true, 3679/*.op_offload =*/ true, 3680/*.swa_full =*/ true, 3681/*.kv_unified =*/ false, 3682/*.sampler =*/ nullptr , 3683/*.n_sampler =*/ 0 , 3684/*.ctx_other =*/ nullptr , 3685 }; 3686 3687return result ; 3688} 3689 3690llama_context * llama_init_from_model ( 3691llama_model * model , 3692llama_context_params params ) { 3693if (!model ) { 3694LLAMA_LOG_ERROR ("%s: model cannot be NULL\n" ,__func__ ); 3695return nullptr ; 3696 } 3697 3698if (params .n_batch == 0 && params .n_ubatch == 0 ) { 3699LLAMA_LOG_ERROR ("%s: n_batch and n_ubatch cannot both be zero\n" ,__func__ ); 3700return nullptr ; 3701 } 3702 3703if (params .n_ctx == 0 && model -> hparams .n_ctx_train == 0 ) { 3704LLAMA_LOG_ERROR ("%s: n_ctx and model->hparams.n_ctx_train cannot both be zero\n" ,__func__ ); 3705return nullptr ; 3706 } 3707 3708if (params .flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED && model -> arch == LLM_ARCH_GROK ) { 3709LLAMA_LOG_WARN ("%s: flash_attn is not compatible with Grok - forcing off\n" ,__func__ ); 3710params .flash_attn_type = LLAMA_FLASH_ATTN_TYPE_DISABLED ; 3711 } 3712 3713if (model -> split_mode ()== LLAMA_SPLIT_MODE_TENSOR ) { 3714if (params .flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO ) { 3715LLAMA_LOG_INFO ("%s: enabling flash_attn since it is required for SPLIT_MODE_TENSOR\n" ,__func__ ); 3716params .flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED ; 3717 } 3718if (params .flash_attn_type != LLAMA_FLASH_ATTN_TYPE_ENABLED ) { 3719LLAMA_LOG_ERROR ("%s: SPLIT_MODE_TENSOR requires flash_attn to be enabled\n" ,__func__ ); 3720return nullptr ; 3721 } 3722if (model -> get_split_state_ud .n_devices == 1 ) { 3723LLAMA_LOG_WARN ("%s: SPLIT_MODE_TENSOR being used for a single device is not recommended\n" ,__func__ ); 3724 } 3725 } 3726 3727if ((model -> hparams .is_mla ()|| model -> arch == LLM_ARCH_DEEPSEEK4 )&& params .type_k != params .type_v ) { 3728LLAMA_LOG_ERROR ("%s: model does not support different K (%s) and V (%s) cache types\n" ,__func__ ,ggml_type_name (params .type_k ),ggml_type_name (params .type_v )); 3729return nullptr ; 3730 } 3731 3732if (ggml_is_quantized (params .type_v )&& params .flash_attn_type != LLAMA_FLASH_ATTN_TYPE_ENABLED ) { 3733if (params .flash_attn_type == LLAMA_FLASH_ATTN_TYPE_AUTO ) { 3734LLAMA_LOG_INFO ("%s: enabling flash_attn since it is required for quantized V cache\n" ,__func__ ); 3735params .flash_attn_type = LLAMA_FLASH_ATTN_TYPE_ENABLED ; 3736 } 3737if (params .flash_attn_type == LLAMA_FLASH_ATTN_TYPE_DISABLED ) { 3738LLAMA_LOG_ERROR ("%s: quantized V cache requires flash_attn to be enabled\n" ,__func__ ); 3739return nullptr ; 3740 } 3741 } 3742 3743if (params .flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED && ggml_is_quantized (params .type_k )) { 3744const uint32_t blck_size = ggml_blck_size (params .type_k ); 3745for (uint32_t il = 0 ;il < model -> hparams .n_layer ();++ il ) { 3746if (model -> hparams .n_embd_head_k (il ) %blck_size != 0 ) { 3747LLAMA_LOG_ERROR ("%s: K cache type %s with block size %u does not divide n_embd_head_k=%u\n" , 3748__func__ ,ggml_type_name (params .type_k ),blck_size ,model -> hparams .n_embd_head_k (il )); 3749return nullptr ; 3750 } 3751 } 3752 } 3753 3754if (params .flash_attn_type != LLAMA_FLASH_ATTN_TYPE_DISABLED && ggml_is_quantized (params .type_v )) { 3755const uint32_t blck_size = ggml_blck_size (params .type_v ); 3756for (uint32_t il = 0 ;il < model -> hparams .n_layer ();++ il ) { 3757if (model -> hparams .n_embd_head_v (il ) %blck_size != 0 ) { 3758LLAMA_LOG_ERROR ("%s: V cache type %s with block size %u does not divide n_embd_head_v=%u\n" , 3759__func__ ,ggml_type_name (params .type_v ),blck_size ,model -> hparams .n_embd_head_v (il )); 3760return nullptr ; 3761 } 3762 } 3763 } 3764 3765if (params .pooling_type != LLAMA_POOLING_TYPE_UNSPECIFIED && 3766params .pooling_type != model -> hparams .pooling_type ) { 3767//user-specified pooling-type is different from the model default 3768LLAMA_LOG_WARN ("%s: model default pooling_type is [%d], but [%d] was specified\n" ,__func__ , 3769model -> hparams .pooling_type ,params .pooling_type ); 3770 } 3771 3772// router_layer >= 0 means n_layer_nextn is repurposed for a router layer, not real MTP 3773if (params .ctx_type == LLAMA_CONTEXT_TYPE_MTP && 3774 (model -> hparams .n_layer_nextn == 0 || model -> hparams .router_layer >=0 )) { 3775LLAMA_LOG_WARN ("%s: context type MTP requested but model doesn't contain MTP layers\n" ,__func__ ); 3776return nullptr ; 3777 } 3778 3779try { 3780auto * ctx = new llama_context (* model ,params ); 3781const auto & cparams = ctx -> get_cparams (); 3782 3783if (cparams .rope_scaling_type == LLAMA_ROPE_SCALING_TYPE_YARN && cparams .rope_freq_scale != model -> hparams .rope_freq_scale_train ) { 3784LLAMA_LOG_INFO ("%s: custom YaRN scaling detected, re-adjusting n_ctx_train(%u)...\n" ,__func__ ,model -> hparams .n_ctx_train ); 3785model -> hparams .n_ctx_train = cparams .n_ctx_orig_yarn /cparams .rope_freq_scale ; 3786LLAMA_LOG_INFO ("%s: n_ctx_train adjusted to %u\n" ,__func__ ,model -> hparams .n_ctx_train ); 3787 } 3788 3789return ctx ; 3790 }catch (const std::exception & err ) { 3791LLAMA_LOG_ERROR ("%s: failed to initialize the context: %s\n" ,__func__ ,err .what ()); 3792 } 3793 3794return nullptr ; 3795} 3796 3797// deprecated 3798llama_context * llama_new_context_with_model ( 3799llama_model * model , 3800llama_context_params params ) { 3801return llama_init_from_model (model ,params ); 3802} 3803 3804void llama_free (llama_context * ctx ) { 3805delete ctx ; 3806} 3807 3808uint32_t llama_n_ctx (const llama_context * ctx ) { 3809return ctx -> n_ctx (); 3810} 3811 3812uint32_t llama_n_ctx_seq (const llama_context * ctx ) { 3813return ctx -> n_ctx_seq (); 3814} 3815 3816uint32_t llama_n_batch (const llama_context * ctx ) { 3817return ctx -> n_batch (); 3818} 3819 3820uint32_t llama_n_ubatch (const llama_context * ctx ) { 3821return ctx -> n_ubatch (); 3822} 3823 3824uint32_t llama_n_seq_max (const llama_context * ctx ) { 3825return ctx -> n_seq_max (); 3826} 3827 3828uint32_t llama_n_rs_seq (const llama_context * ctx ) { 3829return ctx -> get_cparams ().n_rs_seq ; 3830} 3831 3832const llama_model * llama_get_model (const llama_context * ctx ) { 3833return & ctx -> get_model (); 3834} 3835 3836enum llama_pooling_type llama_pooling_type (const llama_context * ctx ) { 3837return ctx -> pooling_type (); 3838} 3839 3840void llama_attach_threadpool ( 3841llama_context * ctx , 3842ggml_threadpool_t threadpool , 3843ggml_threadpool_t threadpool_batch ) { 3844ctx -> attach_threadpool (threadpool ,threadpool_batch ); 3845} 3846 3847void llama_detach_threadpool (llama_context * ctx ) { 3848ctx -> detach_threadpool (); 3849} 3850 3851void llama_set_n_threads (llama_context * ctx ,int32_t n_threads ,int32_t n_threads_batch ) { 3852ctx -> set_n_threads (n_threads ,n_threads_batch ); 3853} 3854 3855int32_t llama_n_threads (llama_context * ctx ) { 3856return ctx -> n_threads (); 3857} 3858 3859int32_t llama_n_threads_batch (llama_context * ctx ) { 3860return ctx -> n_threads_batch (); 3861} 3862 3863void llama_set_abort_callback (llama_context * ctx ,bool (* abort_callback )(void * data ),void * abort_callback_data ) { 3864ctx -> set_abort_callback (abort_callback ,abort_callback_data ); 3865} 3866 3867void llama_set_embeddings (llama_context * ctx ,bool embeddings ) { 3868ctx -> set_embeddings (embeddings ); 3869} 3870 3871void llama_set_causal_attn (llama_context * ctx ,bool causal_attn ) { 3872ctx -> set_causal_attn (causal_attn ); 3873} 3874 3875void llama_set_warmup (llama_context * ctx ,bool warmup ) { 3876ctx -> set_warmup (warmup ); 3877} 3878 3879void llama_synchronize (llama_context * ctx ) { 3880ctx -> synchronize (); 3881} 3882 3883float * llama_get_logits (llama_context * ctx ) { 3884ctx -> synchronize (); 3885 3886return ctx -> get_logits (); 3887} 3888 3889float * llama_get_logits_ith (llama_context * ctx ,int32_t i ) { 3890ctx -> synchronize (); 3891 3892float * res = nullptr ; 3893 3894res = ctx -> get_sampled_logits_ith (i ); 3895 3896if (!res ) { 3897res = ctx -> get_logits_ith (i ); 3898 } 3899 3900return res ; 3901} 3902 3903float * llama_get_embeddings (llama_context * ctx ) { 3904ctx -> synchronize (); 3905 3906return ctx -> get_embeddings (); 3907} 3908 3909float * llama_get_embeddings_ith (llama_context * ctx ,int32_t i ) { 3910ctx -> synchronize (); 3911 3912return ctx -> get_embeddings_ith (i ); 3913} 3914 3915float * llama_get_embeddings_seq (llama_context * ctx ,llama_seq_id seq_id ) { 3916ctx -> synchronize (); 3917 3918return ctx -> get_embeddings_seq (seq_id ); 3919} 3920 3921void llama_set_embeddings_nextn (llama_context * ctx ,bool value ,bool masked ) { 3922ctx -> set_embeddings_nextn (value ,masked ); 3923} 3924 3925void llama_set_embeddings_layer_inp (llama_context * ctx ,uint32_t lid ,bool value ) { 3926ctx -> set_embeddings_layer_inp (lid ,value ); 3927} 3928 3929void llama_set_nextn_layer_offset (llama_context * ctx ,int32_t offset ) { 3930ctx -> set_nextn_layer_offset (offset ); 3931} 3932 3933llama_memory_t llama_get_memory (const struct llama_context * ctx ) { 3934if (!ctx ) { 3935return nullptr ; 3936 } 3937 3938return ctx -> get_memory (); 3939} 3940 3941float * llama_get_embeddings_nextn (llama_context * ctx ) { 3942ctx -> synchronize (); 3943 3944return ctx -> get_embeddings_nextn (); 3945} 3946 3947float * llama_get_embeddings_nextn_ith (llama_context * ctx ,int32_t i ) { 3948ctx -> synchronize (); 3949 3950return ctx -> get_embeddings_nextn_ith (i ); 3951} 3952 3953float * llama_get_embeddings_layer_inp (llama_context * ctx ,uint32_t lid ) { 3954ctx -> synchronize (); 3955 3956return ctx -> get_embeddings_layer_inp (lid ); 3957} 3958 3959bool llama_set_sampler (llama_context * ctx ,llama_seq_id seq_id ,llama_sampler * smpl ) { 3960return ctx -> set_sampler (seq_id ,smpl ); 3961} 3962 3963llama_token llama_get_sampled_token_ith (llama_context * ctx ,int32_t i ) { 3964ctx -> synchronize (); 3965 3966return ctx -> get_sampled_token_ith (i ); 3967} 3968 3969float * llama_get_sampled_probs_ith (llama_context * ctx ,int32_t i ) { 3970ctx -> synchronize (); 3971 3972return ctx -> get_sampled_probs_ith (i ); 3973} 3974 3975float * llama_get_sampled_logits_ith (llama_context * ctx ,int32_t i ) { 3976ctx -> synchronize (); 3977 3978return ctx -> get_sampled_logits_ith (i ); 3979} 3980 3981llama_token * llama_get_sampled_candidates_ith (llama_context * ctx ,int32_t i ) { 3982ctx -> synchronize (); 3983 3984return const_cast < llama_token *> (ctx -> get_sampled_candidates_ith (i )); 3985} 3986 3987uint32_t llama_get_sampled_candidates_count_ith (llama_context * ctx ,int32_t i ) { 3988ctx -> synchronize (); 3989 3990return static_cast < uint32_t > (ctx -> get_sampled_candidates_count (i )); 3991} 3992 3993uint32_t llama_get_sampled_logits_count_ith (llama_context * ctx ,int32_t i ) { 3994ctx -> synchronize (); 3995 3996return static_cast < uint32_t > (ctx -> get_sampled_logits_count (i )); 3997} 3998 3999uint32_t llama_get_sampled_probs_count_ith (llama_context * ctx ,int32_t i ) { 4000ctx -> synchronize (); 4001 4002return static_cast < uint32_t > (ctx -> get_sampled_probs_count (i )); 4003} 4004 4005struct ggml_cgraph * llama_graph_reserve ( 4006struct llama_context * ctx , 4007uint32_t n_tokens , 4008uint32_t n_seqs , 4009uint32_t n_outputs ) { 4010auto memory = ctx -> get_memory (); 4011llama_memory_context_ptr mctx ; 4012if (memory ) { 4013mctx = memory -> init_full (); 4014 } 4015return ctx -> graph_reserve (n_tokens ,n_seqs ,n_outputs ,mctx .get ()); 4016} 4017 4018// llama adapter API 4019 4020int32_t llama_set_adapters_lora ( 4021llama_context * ctx , 4022llama_adapter_lora ** adapters , 4023size_t n_adapters , 4024float * scales ) { 4025if (adapters == nullptr || scales == nullptr ) { 4026GGML_ASSERT (n_adapters == 0 && "invalid llama_set_adapters_lora call" ); 4027 } 4028 4029ctx -> set_adapters_lora (adapters ,n_adapters ,scales ); 4030 4031return 0 ; 4032} 4033 4034int32_t llama_set_adapter_cvec ( 4035llama_context * ctx , 4036const float * data , 4037size_t len , 4038int32_t n_embd , 4039int32_t il_start , 4040int32_t il_end ) { 4041bool res = ctx -> set_adapter_cvec (data ,len ,n_embd ,il_start ,il_end ); 4042 4043return res ?0 :-1 ; 4044} 4045 4046// 4047// memory 4048// 4049 4050void llama_memory_clear (llama_memory_t mem ,bool data ) { 4051if (!mem ) { 4052return ; 4053 } 4054 4055mem -> clear (data ); 4056} 4057 4058bool llama_memory_seq_rm ( 4059llama_memory_t mem , 4060llama_seq_id seq_id , 4061llama_pos p0 , 4062llama_pos p1 ) { 4063if (!mem ) { 4064return true; 4065 } 4066 4067return mem -> seq_rm (seq_id ,p0 ,p1 ); 4068} 4069 4070void llama_memory_seq_cp ( 4071llama_memory_t mem , 4072llama_seq_id seq_id_src , 4073llama_seq_id seq_id_dst , 4074llama_pos p0 , 4075llama_pos p1 ) { 4076if (!mem ) { 4077return ; 4078 } 4079 4080mem -> seq_cp (seq_id_src ,seq_id_dst ,p0 ,p1 ); 4081} 4082 4083void llama_memory_seq_keep ( 4084llama_memory_t mem , 4085llama_seq_id seq_id ) { 4086if (!mem ) { 4087return ; 4088 } 4089 4090mem -> seq_keep (seq_id ); 4091} 4092 4093void llama_memory_seq_add ( 4094llama_memory_t mem , 4095llama_seq_id seq_id , 4096llama_pos p0 , 4097llama_pos p1 , 4098llama_pos delta ) { 4099if (!mem ) { 4100return ; 4101 } 4102 4103mem -> seq_add (seq_id ,p0 ,p1 ,delta ); 4104} 4105 4106void llama_memory_seq_div ( 4107llama_memory_t mem , 4108llama_seq_id seq_id , 4109llama_pos p0 , 4110llama_pos p1 , 4111int d ) { 4112if (!mem ) { 4113return ; 4114 } 4115 4116mem -> seq_div (seq_id ,p0 ,p1 ,d ); 4117} 4118 4119llama_pos llama_memory_seq_pos_min ( 4120llama_memory_t mem , 4121llama_seq_id seq_id ) { 4122if (!mem ) { 4123return -1 ; 4124 } 4125 4126return mem -> seq_pos_min (seq_id ); 4127} 4128 4129llama_pos llama_memory_seq_pos_max ( 4130llama_memory_t mem , 4131llama_seq_id seq_id ) { 4132if (!mem ) { 4133return -1 ; 4134 } 4135 4136return mem -> seq_pos_max (seq_id ); 4137} 4138 4139bool llama_memory_can_shift (llama_memory_t mem ) { 4140if (!mem ) { 4141return false; 4142 } 4143 4144return mem -> get_can_shift (); 4145} 4146 4147// llama state API 4148 4149// deprecated 4150size_t llama_get_state_size (llama_context * ctx ) { 4151return llama_state_get_size (ctx ); 4152} 4153 4154// deprecated 4155size_t llama_copy_state_data (llama_context * ctx ,uint8_t * dst ) { 4156return llama_state_get_data (ctx ,dst ,-1 ); 4157} 4158 4159// deprecated 4160size_t llama_set_state_data (llama_context * ctx ,const uint8_t * src ) { 4161return llama_state_set_data (ctx ,src ,-1 ); 4162} 4163 4164// deprecated 4165bool llama_load_session_file (llama_context * ctx ,const char * path_session ,llama_token * tokens_out ,size_t n_token_capacity ,size_t * n_token_count_out ) { 4166return llama_state_load_file (ctx ,path_session ,tokens_out ,n_token_capacity ,n_token_count_out ); 4167} 4168 4169// deprecated 4170bool llama_save_session_file (llama_context * ctx ,const char * path_session ,const llama_token * tokens ,size_t n_token_count ) { 4171return llama_state_save_file (ctx ,path_session ,tokens ,n_token_count ); 4172} 4173 4174// Returns the *actual* size of the state. 4175// Intended to be used when saving to state to a buffer. 4176size_t llama_state_get_size (llama_context * ctx ) { 4177return ctx -> state_get_size (); 4178} 4179 4180size_t llama_state_get_data (llama_context * ctx ,uint8_t * dst ,size_t size ) { 4181ctx -> synchronize (); 4182 4183return ctx -> state_get_data (dst ,size ); 4184} 4185 4186// Sets the state reading from the specified source address 4187size_t llama_state_set_data (llama_context * ctx ,const uint8_t * src ,size_t size ) { 4188ctx -> synchronize (); 4189 4190return ctx -> state_set_data (src ,size ); 4191} 4192 4193bool llama_state_load_file (llama_context * ctx ,const char * path_session ,llama_token * tokens_out ,size_t n_token_capacity ,size_t * n_token_count_out ) { 4194ctx -> synchronize (); 4195 4196try { 4197return ctx -> state_load_file (path_session ,tokens_out ,n_token_capacity ,n_token_count_out ); 4198 }catch (const std::exception & err ) { 4199LLAMA_LOG_ERROR ("%s: error loading session file: %s\n" ,__func__ ,err .what ()); 4200return false; 4201 } 4202} 4203 4204bool llama_state_save_file (llama_context * ctx ,const char * path_session ,const llama_token * tokens ,size_t n_token_count ) { 4205ctx -> synchronize (); 4206 4207try { 4208return ctx -> state_save_file (path_session ,tokens ,n_token_count ); 4209 }catch (const std::exception & err ) { 4210LLAMA_LOG_ERROR ("%s: error saving session file: %s\n" ,__func__ ,err .what ()); 4211return false; 4212 } 4213} 4214 4215size_t llama_state_seq_get_size (llama_context * ctx ,llama_seq_id seq_id ) { 4216return llama_state_seq_get_size_ext (ctx ,seq_id ,0 ); 4217} 4218 4219size_t llama_state_seq_get_data (llama_context * ctx ,uint8_t * dst ,size_t size ,llama_seq_id seq_id ) { 4220return llama_state_seq_get_data_ext (ctx ,dst ,size ,seq_id ,0 ); 4221} 4222 4223size_t llama_state_seq_set_data (llama_context * ctx ,const uint8_t * src ,size_t size ,llama_seq_id seq_id ) { 4224return llama_state_seq_set_data_ext (ctx ,src ,size ,seq_id ,0 ); 4225} 4226 4227size_t llama_state_seq_get_size_ext (llama_context * ctx ,llama_seq_id seq_id ,llama_state_seq_flags flags ) { 4228return ctx -> state_seq_get_size (seq_id ,flags ); 4229} 4230 4231size_t llama_state_seq_get_data_ext (llama_context * ctx ,uint8_t * dst ,size_t size ,llama_seq_id seq_id ,llama_state_seq_flags flags ) { 4232ctx -> synchronize (); 4233 4234return ctx -> state_seq_get_data (seq_id ,dst ,size ,flags ); 4235} 4236size_t llama_state_seq_set_data_ext (llama_context * ctx ,const uint8_t * src ,size_t size ,llama_seq_id seq_id ,llama_state_seq_flags flags ) { 4237ctx -> synchronize (); 4238 4239return ctx -> state_seq_set_data (seq_id ,src ,size ,flags ); 4240} 4241 4242size_t llama_state_seq_save_file (llama_context * ctx ,const char * filepath ,llama_seq_id seq_id ,const llama_token * tokens ,size_t n_token_count ) { 4243ctx -> synchronize (); 4244 4245try { 4246return ctx -> state_seq_save_file (seq_id ,filepath ,tokens ,n_token_count ); 4247 }catch (const std::exception & err ) { 4248LLAMA_LOG_ERROR ("%s: error saving sequence state file: %s\n" ,__func__ ,err .what ()); 4249return 0 ; 4250 } 4251} 4252 4253size_t llama_state_seq_load_file (llama_context * ctx ,const char * filepath ,llama_seq_id dest_seq_id ,llama_token * tokens_out ,size_t n_token_capacity ,size_t * n_token_count_out ) { 4254ctx -> synchronize (); 4255 4256try { 4257return ctx -> state_seq_load_file (dest_seq_id ,filepath ,tokens_out ,n_token_capacity ,n_token_count_out ); 4258 }catch (const std::exception & err ) { 4259LLAMA_LOG_ERROR ("%s: error loading sequence state file: %s\n" ,__func__ ,err .what ()); 4260return 0 ; 4261 } 4262} 4263 4264/// 4265 4266int32_t llama_encode ( 4267llama_context * ctx , 4268llama_batch batch ) { 4269const int ret = ctx -> encode (batch ); 4270if (ret != 0 ) { 4271LLAMA_LOG_ERROR ("%s: failed to encode, ret = %d\n" ,__func__ ,ret ); 4272 } 4273 4274return ret ; 4275} 4276 4277int32_t llama_decode ( 4278llama_context * ctx , 4279llama_batch batch ) { 4280const int ret = ctx -> decode (batch ); 4281if (ret != 0 && ret != 1 ) { 4282LLAMA_LOG_ERROR ("%s: failed to decode, ret = %d\n" ,__func__ ,ret ); 4283 } 4284 4285return ret ; 4286} 4287 4288// 4289// perf 4290// 4291 4292llama_perf_context_data llama_perf_context (const llama_context * ctx ) { 4293llama_perf_context_data data = {}; 4294 4295if (ctx == nullptr ) { 4296return data ; 4297 } 4298 4299data = ctx -> perf_get_data (); 4300 4301return data ; 4302} 4303 4304void llama_perf_context_print (const llama_context * ctx ) { 4305const auto data = llama_perf_context (ctx ); 4306 4307const double t_end_ms = 1e-3 * ggml_time_us (); 4308 4309LLAMA_LOG_INFO ("%s: load time = %10.2f ms\n" ,__func__ ,data .t_load_ms ); 4310LLAMA_LOG_INFO ("%s: prompt eval time = %10.2f ms / %5d tokens (%8.2f ms per token, %8.2f tokens per second)\n" , 4311__func__ ,data .t_p_eval_ms ,data .n_p_eval ,data .t_p_eval_ms /data .n_p_eval ,1e3 /data .t_p_eval_ms * data .n_p_eval ); 4312LLAMA_LOG_INFO ("%s: eval time = %10.2f ms / %5d runs (%8.2f ms per token, %8.2f tokens per second)\n" , 4313__func__ ,data .t_eval_ms ,data .n_eval ,data .t_eval_ms /data .n_eval ,1e3 /data .t_eval_ms * data .n_eval ); 4314LLAMA_LOG_INFO ("%s: total time = %10.2f ms / %5d tokens\n" ,__func__ , (t_end_ms - data .t_start_ms ), (data .n_p_eval + data .n_eval )); 4315LLAMA_LOG_INFO ("%s: graphs reused = %10d\n" ,__func__ ,data .n_reused ); 4316} 4317 4318void llama_perf_context_reset (llama_context * ctx ) { 4319ctx -> perf_reset (); 4320} 4321 4322// 4323// training 4324// 4325 4326bool llama_opt_param_filter_all (const struct ggml_tensor * tensor ,void * userdata ) { 4327GGML_UNUSED (tensor ); 4328GGML_UNUSED (userdata ); 4329return true; 4330} 4331 4332void llama_opt_init (struct llama_context * ctx ,struct llama_model * model ,struct llama_opt_params lopt_params ) { 4333ctx -> opt_init (model ,lopt_params ); 4334} 4335 4336void llama_opt_epoch ( 4337struct llama_context * ctx , 4338ggml_opt_dataset_t dataset , 4339ggml_opt_result_t result_train , 4340ggml_opt_result_t result_eval , 4341int64_t idata_split , 4342ggml_opt_epoch_callback callback_train , 4343ggml_opt_epoch_callback callback_eval ) { 4344ctx -> opt_epoch ( 4345dataset , 4346result_train , 4347result_eval , 4348idata_split , 4349callback_train , 4350callback_eval ); 4351} 4352 4353// 4354// ext 4355// 4356 4357llama_memory_breakdown llama_get_memory_breakdown (const struct llama_context * ctx ) { 4358return ctx -> memory_breakdown (); 4359} 4360 4361llama_context * llama_get_ctx_other (struct llama_context * ctx ) { 4362return ctx -> get_cparams ().ctx_other ; 4363}