ember.cpp 0.1.0
C++ inference engine for Llama-family and paperkiln models (CPU, CUDA, WebAssembly)
Loading...
Searching...
No Matches
model.h
Go to the documentation of this file.
1#ifndef MODEL_H
2#define MODEL_H
3
4#include <cstdint>
5#include <functional>
6#include <nlohmann/json.hpp>
7#include <map>
8#include <string>
9#include <unordered_map>
10#include <vector>
11
12#include "safetensors_loader.h"
13#ifdef HAS_CUDA
14// Use safe headers only for Windows CUDA 12.1+ workaround, normal headers everywhere else
15#if defined(WINDOWS_CUDA_12_1_WORKAROUND) && defined(_WIN32)
16#include "cuda_safe_headers.h"
17#else
18// Normal CUDA header inclusion for non-problematic platforms (Ubuntu, etc.)
19#include <cuda_runtime.h>
20#include <cublas_v2.h>
21#include <cuda_fp16.h>
22#include <cuda_bf16.h>
23#endif
24
25#include "cuda_kernels.h"
26#include "verify_kernels.h"
27#endif
28#include <memory>
29
30#include "quantization.h"
31
38enum class TensorName {
39 Q_PROJ,
40 K_PROJ,
41 V_PROJ,
42 O_PROJ,
43 GATE_PROJ,
44 UP_PROJ,
45 DOWN_PROJ,
47 LM_HEAD,
48 UNKNOWN
49};
50
51static std::string tensor_name_to_string(TensorName tn) {
52 switch (tn) {
54 return "Q_PROJ";
56 return "K_PROJ";
58 return "V_PROJ";
60 return "O_PROJ";
62 return "GATE_PROJ";
64 return "UP_PROJ";
66 return "DOWN_PROJ";
68 return "TOKEN_EMBD";
70 return "LM_HEAD";
71 default:
72 return "UNKNOWN";
73 }
74}
75
91 float rope_theta;
92 std::string hidden_act;
93 std::string torch_dtype;
96 int unk_token_id = -1;
97 int pad_token_id = -1;
98 std::string architecture;
99 std::string model_name;
100 std::string chat_template_type;
101 std::string pre_tokenizer_type;
104 bool use_mmap_for_gguf = true; // Whether to use mmap for GGUF files, defaults to true
107 int num_experts = 0;
110 // Memory management: Enable layer-wise weight eviction to prevent OOM
114 bool use_optimized_cuda_kernels = true; // Re-enabled: fixed performance issues with simpler implementations
115
116 enum class TokenizerFamily {
117 UNKNOWN,
118 LLAMA_SENTENCEPIECE, // For Llama 2 and similar SentencePiece BPE
119 LLAMA3_TIKTOKEN, // For Llama 3's Tiktoken-based BPE
120 WORD_LEVEL // transformer_cpp GGUFs (tokenizer.ggml.model=="word"):
121 // whitespace split, lowercase, whole-word lookup, <unk> fallback
122 };
124};
125
126struct GGUFData;
127struct ModelConfig;
129
137 std::vector<float> k; // Key cache (CPU)
138 std::vector<float> v; // Value cache (CPU)
139#ifdef HAS_CUDA
140 float* k_dev_fp32 = nullptr; // Original FP32 Key cache (GPU device pointer)
141 float* v_dev_fp32 = nullptr; // Original FP32 Value cache (GPU device pointer)
142
143 int8_t* k_dev_quantized = nullptr; // Quantized INT8 Key cache (GPU device pointer)
144 int8_t* v_dev_quantized = nullptr; // Quantized INT8 Value cache (GPU device pointer)
145 float* k_dev_scales = nullptr; // Scales for K cache (GPU device pointer)
146 float* v_dev_scales = nullptr; // Scales for V cache (GPU device pointer)
147#endif
148};
149
157struct KVCache {
158 std::vector<KVCacheLayer> layers;
160 // Single-sequence mode (legacy compatibility)
161 int seq_len = 0;
163 // Multi-sequence mode (new batch functionality)
164 std::vector<int> batch_seq_lens;
181 void initialize(const ModelConfig& config,
184 int max_batch_size_arg = 1);
185
186 void clear_data() {
187 // Single-sequence mode (legacy compatibility)
188 seq_len = 0;
189
190 // Multi-sequence mode
192 batch_seq_lens.clear();
193
194 // For batch processing, we MUST clear the actual KV data to prevent cross-sequence contamination.
195 // Only layers that run on the CPU read these host vectors. The GPU
196 // layers (the top allocated_num_layers) keep their KV on the device,
197 // where prefill writes positions 0..n-1 before attention reads them.
198 // Zero-filling their unused host copies cost a constant 26 ms per
199 // request on the TTFT timing model (docs/TTFT.md).
200 size_t host_layers = layers.size();
201#ifdef HAS_CUDA
202 host_layers -= std::min(host_layers, static_cast<size_t>(std::max(allocated_num_layers, 0)));
203#endif
204 for (size_t i = 0; i < host_layers; ++i) {
205 std::fill(layers[i].k.begin(), layers[i].k.end(), 0.0f);
206 std::fill(layers[i].v.begin(), layers[i].v.end(), 0.0f);
207 }
208
209 // Logger::debug("[KVCache] clear_data() called. seq_len reset to 0. K/V vectors cleared for batch processing.");
210 }
211
218 Logger::warning("Requested batch size " + std::to_string(batch_size) +
219 " exceeds max batch size " + std::to_string(max_batch_size) +
220 ". Using max batch size.");
222 }
224 batch_seq_lens.resize(batch_size, 0);
225 }
226
227 void destroy_gpu_resources(); // Implementation moved to kv_cache.cpp
228
229#ifdef HAS_CUDA
230 int allocated_num_layers = 0;
231 int allocated_max_seq_len = 0;
232 int allocated_num_kv_heads = 0;
233 int allocated_head_dim = 0;
235 ~KVCache() {
237 }
238#else
242#endif
243};
244
245using ForwardDiagCallback = std::function<void(
246 int layer, const std::string& name, const std::vector<float>& v)>;
247
254 std::vector<uint16_t> input_layernorm;
255 std::vector<uint16_t> post_attention_layernorm;
256
257 std::vector<uint16_t> q_proj;
258 std::vector<uint16_t> k_proj;
259 std::vector<uint16_t> v_proj;
260 std::vector<uint16_t> o_proj;
261
262 std::vector<uint16_t> gate_proj;
263 std::vector<uint16_t> up_proj;
264 std::vector<uint16_t> down_proj;
265
266 std::vector<float> input_layernorm_f32;
270 std::vector<block_q4_K> q_proj_q4k, k_proj_q4k, v_proj_q4k, o_proj_q4k;
271 std::vector<block_q4_K> gate_proj_q4k, up_proj_q4k, down_proj_q4k;
272 // Q5_K: kept in its blocks, dequantised to the f32 copy before use (no Q5_K kernels).
273 std::vector<block_q5_K> q_proj_q5k, k_proj_q5k, v_proj_q5k, o_proj_q5k;
274 std::vector<block_q5_K> gate_proj_q5k, up_proj_q5k, down_proj_q5k;
275 std::vector<block_q6_K> q_proj_q6k, k_proj_q6k, v_proj_q6k, o_proj_q6k;
276 std::vector<block_q6_K> gate_proj_q6k, up_proj_q6k, down_proj_q6k;
277 std::vector<block_q8_0> q_proj_q8_0, k_proj_q8_0, v_proj_q8_0, o_proj_q8_0;
278 std::vector<block_q8_0> gate_proj_q8_0, up_proj_q8_0, down_proj_q8_0;
279 // Mixture-of-experts FFN (llama.cpp layout): router [E][d] (ffn_gate_inp),
280 // and per expert e a contiguous [d_ff][d] gate/up block and [d][d_ff] down
281 // block (ffn_{gate,up,down}_exps). Empty for dense models.
282 std::vector<float> moe_router_f32;
283 std::vector<block_q8_0> moe_router_q8_0;
285 std::vector<block_q8_K> q_proj_q8k, k_proj_q8k, v_proj_q8k, o_proj_q8k;
286 std::vector<block_q8_K> gate_proj_q8k, up_proj_q8k, down_proj_q8k;
287
288#ifdef HAS_CUDA
289
290 float* input_layernorm_dev = nullptr;
291 float* post_attention_layernorm_dev = nullptr;
292
293 // Individual layer device pointers for JIT weight loading
294 float* q_proj_f32_dev = nullptr;
295 float* k_proj_f32_dev = nullptr;
296 float* v_proj_f32_dev = nullptr;
297 float* o_proj_f32_dev = nullptr;
298 float* gate_proj_f32_dev = nullptr;
299 float* up_proj_f32_dev = nullptr;
300 float* down_proj_f32_dev = nullptr;
301#endif
302};
303
310 public:
317
323 TinyLlamaModel(const ModelConfig& initial_config, const std::string& model_path);
324
331 std::unique_ptr<GGUFData> gguf_data_from_session);
332
337
346 std::vector<float> forward(
347 std::vector<float>& input,
349 const std::vector<int>* attention_mask);
350
365
366 // BF16 Tensor Core weight management
369
370#ifdef HAS_CUDA
371 // Smart GEMM wrapper that chooses between BF16 Tensor Cores and FP32 based on batch size
373 int m_user, int n_user, int k_user,
374 const float* alpha_user,
375 const float* A_f32_user, int lda_user,
376 const float* B_f32_user, int ldb_user,
377 const float* beta_user,
378 float* C_f32_user, int ldc_user,
380 const char* operation_name = "GEMM");
381#endif // HAS_CUDA
382 // While set, smart_gemm_batch_cuda runs FP32 math only: no BF16 tensor cores, no TF32 (whatever
383 // EMBER_GEMM_TF32 says). POST /score sets it for its forwards (score.cpp): mtstudio score's
384 // log-probabilities are FP32 arithmetic. Off by default; nothing else sets it.
386 bool gemm_fp32_only() const { return gemm_fp32_only_; }
387
388#ifdef HAS_CUDA
398 std::vector<float> forward_device(
399 float* x_input_dev,
400 int pos,
401 KVCache* cache,
402 const std::vector<int>* attention_mask = nullptr,
403 cudaStream_t stream = 0);
404
405 float* get_x_dev() { return x_dev_; }
406 // Graph decode (EMBER_DECODE_GRAPH, on by default): one decode step
407 // captured once as a CUDA graph and replayed per token. Returns the logits,
408 // or an empty vector when the graph path does not apply (CPU layers,
409 // quantized KV cache, no FP32 LM head, capture failure); the caller then
410 // uses forward_device().
411 std::vector<float> forward_device_graph(int token_id, int pos, KVCache* kv_cache);
412 // Speculative verification: n tokens at positions pos..pos+n-1 (all layers
413 // on the GPU, n <= 33), logits for every row ([n][vocab]): FP32 GEMMs and
414 // the decode-attention kernel launched once per row, per launch (1.2-5.1
415 // decode steps on an L4, experiments/verify_2026-10-27; the fallback of
416 // forward_device_verify_graph). Empty if unavailable.
417 std::vector<float> forward_device_verify(const std::vector<int>& tokens, int pos, KVCache* kv_cache);
418 // Speculative verification as one CUDA graph per row count (speculative_verify.cpp, EMBER_SPEC on CUDA): the
419 // same n rows at positions pos..pos+n-1 (n <= ember_verify::kMaxRows), every layer replayed from a captured
420 // graph, each row through the graph decode's kernels (verify_kernels.h), and a greedy pick per row computed on
421 // the device. Fills picks[0..n-1]; the rows' logits stay on the device (verify_row_logits). False when the path
422 // does not apply (CPU layers, a quantised KV cache, MoE, the decode graph off, a shape the decode attention
423 // kernel refuses); the caller then uses forward_device_verify.
424 bool forward_device_verify_graph(const std::vector<int>& tokens, int pos, KVCache* kv_cache,
425 std::vector<ember_verify::RowPick>* picks);
426 // Logits of row r of the last forward_device_verify_graph pass (one device-to-host copy).
427 std::vector<float> verify_row_logits(int r);
428 // Measurement knobs of forward_device_verify_graph, read from the environment on first use
429 // (EMBER_VERIFY_LINEAR = smallm | gemm | gemvb | rows | fixed; unset, under EMBER_DETERMINISTIC=1 the decode
430 // step's own linear (rows, or fixed with EMBER_DECODE_LINEAR=fixed), else smallm;
431 // EMBER_VERIFY_GRAPH=0, EMBER_VERIFY_ATTN=perrow,
432 // EMBER_VERIFY_TIMING=1: per-stage synchronised timing, graph off). Changing them drops the captured graphs.
433 struct VerifyOptions {
434 int linear = 0; // ember_verify::VerifyLinear
435 bool graph = true;
436 bool batched_attention = true;
437 bool timing = false;
438 };
440 std::map<std::string, double>& verify_stage_ms() { return verify_stage_ms_; }
441 // The FP32 linear layers of the decode step (forward_device and forward_device_graph, dense llama path):
442 // cuBLAS's Sgemm with one column, or ember_verify::fixed_linear with n = 1, whose rows the verification pass
443 // computes for n rows at once with the same arithmetic (experiments/spec_r1_2026-10-28). EMBER_DECODE_LINEAR =
444 // cublas | fixed, read on first use; unset (or empty), cublas (fixed is opt-in until its on-device ROUNDING gate).
445 bool decode_linear_fixed();
446 void decode_matvec(const float* W, const float* x, float* y, int O, int I, cudaStream_t st);
447 // Per-op GPU time of the last batched prefill, filled only when
448 // EMBER_OP_TIMING=1 (docs/TTFT.md); empty otherwise.
449 const std::map<std::string, double>& last_prefill_op_ms() const { return last_prefill_op_ms_; }
450 // Wall time per phase of the single-token GPU forward, summed over the
451 // decode steps since the last reset, filled only when
452 // EMBER_DECODE_TIMING=1 (each phase boundary syncs the stream, so the
453 // timed run is slower than an untimed one; read the shares, not the sum).
454 std::map<std::string, double>& decode_phase_ms() { return decode_phase_ms_; }
455
456 void forward_device(int token_id, int pos, KVCache* kv_cache,
457 cudaStream_t stream = 0);
458 void forward_device_token(int token_id, int pos, KVCache* kv_cache, cudaStream_t stream = 0);
459
460 std::vector<float> forward_device_batch_prefill(
461 float* d_batch_input_hidden_states, // Device pointer to [num_tokens_in_batch, config_.hidden_size]
463 int start_pos_in_kv_cache, // Typically 0 for prefill
466 bool all_logits = false // logits for every token ([n][vocab]), not only the last
467 );
468
469 std::vector<std::vector<float>> forward_device_batch_generation(
470 float* d_batch_input_hidden_states, // Device pointer to [num_tokens_in_batch, config_.hidden_size]
471 const std::vector<int>& token_positions, // Position of each token in its respective sequence
472 const std::vector<int>& original_sequence_indices, // Original sequence index for each token
476 );
477
478 // Memory management for layer-wise weight eviction
479
480 // GPU workspace buffers
481
482 // Persistent batch processing buffers to eliminate per-forward-pass allocations
483 std::map<std::string, double> last_prefill_op_ms_; // see last_prefill_op_ms()
484 std::map<std::string, double> decode_phase_ms_; // see decode_phase_ms()
485 static constexpr int MAX_BATCH_TOKENS = 2048; // Initial capacity of the batch buffers (they grow on demand)
486 int persistent_batch_capacity_ = 0; // tokens the batch buffers currently hold
487
488 // Persistent GPU buffers for batch processing (allocated once, reused)
489 float* d_persistent_batch_input_ = nullptr; // [MAX_BATCH_TOKENS, hidden_size]
490 float* d_persistent_batch_norm_out_ = nullptr; // [MAX_BATCH_TOKENS, hidden_size]
491 float* d_persistent_batch_residual_ = nullptr; // [MAX_BATCH_TOKENS, hidden_size]
492 float* d_persistent_q_batch_ = nullptr; // [MAX_BATCH_TOKENS, hidden_size]
493 float* d_persistent_k_batch_ = nullptr; // [MAX_BATCH_TOKENS, n_kv_heads * head_dim]
494 float* d_persistent_v_batch_ = nullptr; // [MAX_BATCH_TOKENS, n_kv_heads * head_dim]
495 float* d_persistent_attn_output_ = nullptr; // [MAX_BATCH_TOKENS, hidden_size]
496 float* d_persistent_attn_proj_out_ = nullptr; // [MAX_BATCH_TOKENS, hidden_size]
497 float* d_persistent_gate_proj_out_ = nullptr; // [MAX_BATCH_TOKENS, intermediate_size]
498 float* d_persistent_up_proj_out_ = nullptr; // [MAX_BATCH_TOKENS, intermediate_size]
499 float* d_persistent_swiglu_out_ = nullptr; // [MAX_BATCH_TOKENS, intermediate_size]
500 float* d_persistent_mlp_down_out_ = nullptr; // [MAX_BATCH_TOKENS, hidden_size]
501
502 // Buffer management functions
506
507#endif // HAS_CUDA
508
509 const ModelConfig& get_config() const { return config_; }
510 // Dequantise every quantised weight to its f32 copy once, if the model
511 // has at most max_params parameters. The CPU forward prefers the f32
512 // copies, so a quantised file then runs at f32 speed on the quantised
513 // values (the download stays small). Returns true if it dequantised.
515
516 const std::vector<uint16_t>& get_lm_head() const { return lm_head; }
517
518 const std::vector<uint16_t>& get_embed_tokens() const { return embed_tokens; }
519
520 std::vector<LayerWeights>& get_layers() { return layers; }
521
527 std::vector<float> lookup_embedding(int token_id);
528 // True when the GGUF is served only by the paperkiln IR interpreter (an IR
529 // whose family is not llama, or EMBER_IR_ONLY=1): no llama weights or GPU
530 // state are loaded, and config_ comes from the IR.
531 bool ir_only() const { return ir_only_; }
532
537 int get_vocab_size() const;
538
539 const GGUFData* get_gguf_data() const {
540 return gguf_data_ ? gguf_data_.get() : nullptr;
541 }
542
544
546
547 std::vector<float> forward_cpu_batch(
548 const std::vector<float>& batch_input_activations,
553 const std::vector<int>& prompt_lengths = {}
554 );
555
556 std::vector<float> forward_cpu_logits_batch(
557 const std::vector<float>& final_batch_activations,
559 );
560
561 std::vector<std::vector<float>> forward_cpu_batch_generation(
562 const std::vector<float>& batch_input_activations,
563 const std::vector<int>& token_positions,
564 const std::vector<int>& original_sequence_indices,
567 );
568
569 friend void map_gguf_weights(const GGUFData& gguf, TinyLlamaModel& model);
570 friend class CPUBatchProcessor;
571
572 private:
575 bool bf16_batch_gemm_failed_ = false; // latched by smart_gemm_batch_cuda on the first BF16 failure
576 bool gemm_fp32_only_ = false; // see set_gemm_fp32_only()
577
578 std::vector<uint16_t> embed_tokens;
579 std::vector<uint16_t> lm_head;
580 std::vector<uint16_t> final_norm;
582 std::vector<block_q4_K> embed_tokens_q4k, lm_head_q4k, final_norm_q4k;
583 std::vector<block_q5_K> embed_tokens_q5k, lm_head_q5k;
584 std::vector<block_q6_K> embed_tokens_q6k, lm_head_q6k, final_norm_q6k;
585 std::vector<block_q8_0> embed_tokens_q8_0, lm_head_q8_0;
586 std::vector<block_q8_K> embed_tokens_q8k, lm_head_q8k;
587 std::vector<LayerWeights> layers;
588
589#ifdef HAS_CUDA
590 float* final_norm_dev = nullptr;
591 float* all_freqs_cis_dev = nullptr;
593 uint16_t* w_q_dev_ = nullptr;
594 uint16_t* w_k_dev_ = nullptr;
595 uint16_t* w_v_dev_ = nullptr;
596 uint16_t* w_o_dev_ = nullptr;
597 uint16_t* w_gate_dev_ = nullptr;
598 uint16_t* w_up_dev_ = nullptr;
599 uint16_t* w_down_dev_ = nullptr;
600 uint16_t* lm_head_dev_ = nullptr;
601 float* token_embedding_table_f32_dev_ = nullptr;
602 float* w_q_f32_dev_ = nullptr;
603 float* w_k_f32_dev_ = nullptr;
604 float* w_v_f32_dev_ = nullptr;
605 float* w_o_f32_dev_ = nullptr;
606 float* w_gate_f32_dev_ = nullptr;
607 float* w_up_f32_dev_ = nullptr;
608 float* w_down_f32_dev_ = nullptr;
609 // Mixture of experts on the GPU: router [L][E][d], expert stacks
610 // [L][E][d_ff][d] (gate, up) and [L][E][d][d_ff] (down), f32, and the
611 // scratch of moe_ffn_cuda (a fixed one for decode, captured in the graph,
612 // and a growable one for prefill).
613 float* w_moe_router_dev_ = nullptr;
614 float* w_moe_gate_dev_ = nullptr;
615 float* w_moe_up_dev_ = nullptr;
616 float* w_moe_down_dev_ = nullptr;
617 float* moe_scratch_decode_dev_ = nullptr;
618 float* moe_scratch_batch_dev_ = nullptr;
619 size_t moe_scratch_batch_floats_ = 0;
620 float* moe_scratch(int T); // T == 1: the decode scratch
621 float* verify_buf_dev_ = nullptr; // forward_device_verify's rows (allocated once)
622 // forward_device_verify_graph state (speculative_verify.cpp; allocated on first use, kept for the session).
624 bool verify_opts_read_ = false;
625 int decode_linear_ = -1; // decode_linear_fixed(): -1 not read yet, 0 cublas, 1 fixed
626 bool verify_graph_disabled_ = false;
627 std::map<int, cudaGraphExec_t> verify_graphs_; // per row count
628 const void* verify_graph_key_ = nullptr; // KV cache base the graphs were captured for
629 int verify_graph_opts_key_ = -1;
630 int* verify_step_dev_ = nullptr; // [pos, ids...]
631 int* verify_step_host_ = nullptr; // pinned
632 float* verify_rows_dev_ = nullptr; // the rows' activations and logits
633 float* verify_logits_dev_ = nullptr; // inside verify_rows_dev_: [kMaxRows][vocab]
634 float* verify_attn_scratch_dev_ = nullptr;
636 ember_verify::RowPick* verify_picks_dev_ = nullptr;
637 ember_verify::RowPick* verify_picks_host_ = nullptr; // pinned
638 int verify_last_n_ = 0;
639 std::map<std::string, double> verify_stage_ms_;
642 void moe_ffn_layer_cuda(int l_gpu_idx, const float* x, int T, float* out, cudaStream_t stream);
643 float* lm_head_f32_dev_ = nullptr;
645 // Graph decode state (see forward_device_graph).
648 const void* decode_graph_key_ = nullptr; // KV cache base the graph was captured for
649 int* decode_step_dev_ = nullptr; // [token id, pos]
650 int* decode_step_host_ = nullptr; // pinned
651 float* decode_logits_host_ = nullptr; // pinned, vocab_size
652 float* decode_embed_f32_dev_ = nullptr; // FP32 embedding table (host lookup values)
653 void* decode_cublas_ws_ = nullptr;
654 bool decode_graph_disabled_ = false;
655
656 float* x_dev_ = nullptr;
657 float* x_norm_dev_ = nullptr;
658 float* x_resid1_dev_ = nullptr;
659 float* x_resid2_dev_ = nullptr;
660 float* q_dev_ = nullptr;
661 float* k_dev_ = nullptr;
662 float* v_dev_ = nullptr;
663 float* attn_out_dev_ = nullptr;
664 float* attn_proj_dev_ = nullptr;
665 float* gate_vec_dev_ = nullptr;
666 float* up_vec_dev_ = nullptr;
667 float* swiglu_vec_dev_ = nullptr;
668 float* mlp_down_dev_ = nullptr;
669 float* logits_dev_ = nullptr;
670
671 // Temporary buffers for KVCache dequantization
672 float* dequant_k_cache_buffer_dev_ = nullptr; // For KVCache dequantization (full cache size)
673 float* dequant_v_cache_buffer_dev_ = nullptr; // For KVCache dequantization (full cache size)
674
675 // Selective KVCache dequantization buffers (much smaller - only per head per token)
676 float* selective_k_dequant_buffer_dev_ = nullptr; // Small buffer for selective K dequantization
677 float* selective_v_dequant_buffer_dev_ = nullptr; // Small buffer for selective V dequantization
678 size_t selective_dequant_buffer_size_ = 0; // Size of selective buffers in elements
679
680 // GPU workspace buffers
681
682 // BF16 weight device pointers for Tensor Core acceleration
683 uint16_t* w_q_bf16_dev_ = nullptr;
684 uint16_t* w_k_bf16_dev_ = nullptr;
685 uint16_t* w_v_bf16_dev_ = nullptr;
686 uint16_t* w_o_bf16_dev_ = nullptr;
687 uint16_t* w_gate_bf16_dev_ = nullptr;
688 uint16_t* w_up_bf16_dev_ = nullptr;
689 uint16_t* w_down_bf16_dev_ = nullptr;
691
692#endif
693
694 std::vector<std::pair<float, float>> precomputed_freqs_cis_;
695
696 std::unique_ptr<GGUFData> gguf_data_;
697 bool ir_only_ = false;
698 std::string model_path_;
700
701 std::unique_ptr<class CPUBatchProcessor> cpu_batch_processor_;
702
704 const GGUFData* gguf);
705
706};
707
708ModelConfig parse_model_config(const nlohmann::json& json);
709
710int argmax(const std::vector<float>& v);
711
713
714void rmsnorm(const std::vector<float>& x, const std::vector<uint16_t>& weight,
715 float eps, std::vector<float>& out);
716
717void matvec_bf16_f32(const std::vector<uint16_t>& mat,
718 const std::vector<float>& vec, std::vector<float>& out,
719 int M, int N);
720
721void softmax(std::vector<float>& x);
722
723struct KVCache;
724
726std::vector<uint16_t> uint8_vector_to_uint16_vector(
727 const std::vector<uint8_t>& bytes, size_t numel);
728
729void log_vector_summary(const std::string& name, const std::vector<float>& v,
730 int head_count = 5);
731
732void log_vector_summary_batch(const std::string& name, const std::vector<float>& batch_vector,
734 int head_count = 5);
735
736#endif
static void warning(const std::string &message)
Definition logger.cpp:139
Main class for loading tensors from SafeTensors format files (single or sharded)
Main transformer model class for TinyLlama.
Definition model.h:309
const GGUFData * get_gguf_data() const
Definition model.h:539
bool use_bf16_tensor_cores_
Definition model.h:574
void free_layer_gpu_weights(int layer_idx)
~TinyLlamaModel()
Destructor. Cleans up all allocated resources.
Definition model.cpp:386
bool f32_concatenated_weights_loaded_
Definition model.h:699
std::vector< LayerWeights > & get_layers()
Definition model.h:520
std::vector< block_q6_K > embed_tokens_q6k
Definition model.h:584
bool dequantize_all_if_small(size_t max_params)
std::vector< float > lookup_embedding(int token_id)
Lookup the embedding vector for a given token ID.
const ModelConfig & get_config() const
Definition model.h:509
void ensure_up_proj_dequantized(int layer_idx)
std::vector< float > final_norm_f32
Definition model.h:581
void free_bf16_concatenated_weights()
std::vector< block_q4_K > final_norm_q4k
Definition model.h:582
void initialize_rope_freqs()
std::vector< uint16_t > final_norm
Definition model.h:580
int get_vocab_size() const
Get the vocabulary size for the model.
bool ir_only_
Definition model.h:697
void ensure_v_proj_dequantized(int layer_idx)
std::vector< block_q6_K > final_norm_q6k
Definition model.h:584
std::vector< block_q4_K > lm_head_q4k
Definition model.h:582
std::vector< float > forward_cpu_logits_batch(const std::vector< float > &final_batch_activations, int num_tokens_in_batch)
Definition model.cpp:1329
friend void map_gguf_weights(const GGUFData &gguf, TinyLlamaModel &model)
std::vector< block_q6_K > lm_head_q6k
Definition model.h:584
void set_gemm_fp32_only(bool on)
Definition model.h:385
void ensure_layer_weights_on_gpu(int layer_idx)
bool gemm_fp32_only() const
Definition model.h:386
const std::vector< uint16_t > & get_embed_tokens() const
Definition model.h:518
std::vector< std::pair< float, float > > precomputed_freqs_cis_
Definition model.h:694
bool bf16_batch_gemm_failed_
Definition model.h:575
bool gemm_fp32_only_
Definition model.h:576
std::vector< block_q5_K > lm_head_q5k
Definition model.h:583
std::string model_path_
Definition model.h:698
void ensure_embed_tokens_dequantized()
std::vector< LayerWeights > layers
Definition model.h:587
std::vector< block_q8_0 > embed_tokens_q8_0
Definition model.h:585
ModelConfig config_
Definition model.h:573
void ensure_o_proj_dequantized(int layer_idx)
void clear_layer_dequantized_weights(int layer_idx)
std::vector< block_q4_K > embed_tokens_q4k
Definition model.h:582
void ensure_k_proj_dequantized(int layer_idx)
const std::vector< uint16_t > & get_lm_head() const
Definition model.h:516
std::unique_ptr< class CPUBatchProcessor > cpu_batch_processor_
Definition model.h:701
std::vector< block_q8_0 > lm_head_q8_0
Definition model.h:585
std::vector< uint16_t > lm_head
Definition model.h:579
void ensure_f32_concatenated_weights_loaded()
std::vector< block_q5_K > embed_tokens_q5k
Definition model.h:583
std::vector< std::vector< float > > forward_cpu_batch_generation(const std::vector< float > &batch_input_activations, const std::vector< int > &token_positions, const std::vector< int > &original_sequence_indices, int num_tokens_in_batch, KVCache *kv_cache)
Definition model.cpp:1395
std::vector< uint16_t > embed_tokens
Definition model.h:578
std::vector< block_q8_K > embed_tokens_q8k
Definition model.h:586
void ensure_bf16_concatenated_weights_loaded()
void ensure_q_proj_dequantized(int layer_idx)
void initialize_weights(const SafeTensorsLoader *loader, const GGUFData *gguf)
Definition model.cpp:39
std::vector< float > forward_cpu_batch(const std::vector< float > &batch_input_activations, int num_tokens_in_batch, int num_cpu_layers_to_process, int start_pos_in_sequence, KVCache *kv_cache, const std::vector< int > &prompt_lengths={})
Definition model.cpp:2498
void ensure_down_proj_dequantized(int layer_idx)
void ensure_gate_proj_dequantized(int layer_idx)
GGUFData * get_gguf_data_ptr()
Definition model.h:543
std::vector< float > embed_tokens_f32
Definition model.h:581
bool ir_only() const
Definition model.h:531
std::vector< float > forward(std::vector< float > &input, int n_tokens, KVCache *kv_cache, const std::vector< int > *attention_mask)
Run the forward pass for the model on CPU layers.
Definition model.cpp:595
void ensure_lm_head_dequantized()
std::unique_ptr< GGUFData > gguf_data_
Definition model.h:696
std::vector< float > lm_head_f32
Definition model.h:581
std::vector< block_q8_K > lm_head_q8k
Definition model.h:586
Safe CUDA header inclusion wrapper for Windows CUDA 12.1+ compatibility.
int n
std::vector< float > v
const char * name
size_t numel
node rmsnorm
node out
node linear
size_t j
static std::string tensor_name_to_string(TensorName tn)
Definition model.h:51
TensorName
Enumeration of tensor names used in the TinyLlama model.
Definition model.h:38
std::vector< uint16_t > uint8_vector_to_uint16_vector(const std::vector< uint8_t > &bytes, size_t numel)
Definition utils.cpp:177
ModelConfig parse_model_config(const nlohmann::json &json)
ModelConfig parse_model_config_from_gguf(const GGUFData &gguf)
void log_vector_summary(const std::string &name, const std::vector< float > &v, int head_count=5)
Definition utils.cpp:208
void log_vector_summary_batch(const std::string &name, const std::vector< float > &batch_vector, int num_tokens_in_batch, int single_token_vector_size, int head_count=5)
void matvec_bf16_f32(const std::vector< uint16_t > &mat, const std::vector< float > &vec, std::vector< float > &out, int M, int N)
int argmax(const std::vector< float > &v)
Definition utils.cpp:186
float bfloat16_to_float32(uint16_t b16)
Definition utils.cpp:145
void softmax(std::vector< float > &x)
std::function< void(int layer, const std::string &name, const std::vector< float > &v)> ForwardDiagCallback
Definition model.h:246
Weight quantization structures and functions for model compression.
SafeTensors format loader for efficient tensor loading, supporting single and sharded models.
nlohmann::json json
Definition server.cpp:68
Complete representation of a GGUF file's contents.
Key-Value cache for a single transformer layer.
Definition model.h:136
std::vector< float > v
Definition model.h:138
std::vector< float > k
Definition model.h:137
Complete Key-Value cache for all transformer layers.
Definition model.h:157
int max_batch_size
Definition model.h:165
void initialize_batch(int batch_size)
Initialize batch mode with specified number of sequences.
Definition model.h:216
int max_seq_len_config_
Definition model.h:169
void initialize(const ModelConfig &config, int total_num_model_layers, int num_gpu_layers_to_allocate, int max_seq_len_arg, int num_kv_heads, int head_dim, int max_batch_size_arg=1)
Initializes the KV cache with given dimensions.
Definition kv_cache.cpp:10
int total_model_layers_
Definition model.h:168
void clear_data()
Definition model.h:186
std::vector< KVCacheLayer > layers
Definition model.h:158
~KVCache()
Definition model.h:239
int seq_len
Definition model.h:161
void destroy_gpu_resources()
Definition kv_cache.cpp:217
std::vector< int > batch_seq_lens
Definition model.h:164
int current_batch_size
Definition model.h:166
Structure holding all weights for a single transformer layer.
Definition model.h:253
std::vector< uint16_t > post_attention_layernorm
Definition model.h:255
std::vector< block_q6_K > down_proj_q6k
Definition model.h:276
std::vector< block_q4_K > k_proj_q4k
Definition model.h:270
std::vector< block_q6_K > k_proj_q6k
Definition model.h:275
std::vector< float > input_layernorm_f32
Definition model.h:266
std::vector< block_q8_K > o_proj_q8k
Definition model.h:285
std::vector< uint16_t > gate_proj
Definition model.h:262
std::vector< block_q5_K > v_proj_q5k
Definition model.h:273
std::vector< uint16_t > v_proj
Definition model.h:259
std::vector< uint16_t > input_layernorm
Definition model.h:254
std::vector< block_q4_K > v_proj_q4k
Definition model.h:270
std::vector< block_q4_K > up_proj_q4k
Definition model.h:271
std::vector< block_q8_0 > o_proj_q8_0
Definition model.h:277
std::vector< float > up_proj_f32
Definition model.h:269
std::vector< block_q8_0 > moe_router_q8_0
Definition model.h:283
std::vector< uint16_t > o_proj
Definition model.h:260
std::vector< block_q5_K > o_proj_q5k
Definition model.h:273
std::vector< block_q8_K > down_proj_q8k
Definition model.h:286
std::vector< block_q4_K > down_proj_q4k
Definition model.h:271
std::vector< block_q4_K > gate_proj_q4k
Definition model.h:271
std::vector< float > v_proj_f32
Definition model.h:268
std::vector< block_q5_K > down_proj_q5k
Definition model.h:274
std::vector< block_q6_K > v_proj_q6k
Definition model.h:275
std::vector< block_q8_K > up_proj_q8k
Definition model.h:286
std::vector< block_q6_K > up_proj_q6k
Definition model.h:276
std::vector< block_q8_0 > v_proj_q8_0
Definition model.h:277
std::vector< float > k_proj_f32
Definition model.h:268
std::vector< block_q5_K > gate_proj_q5k
Definition model.h:274
std::vector< block_q8_K > v_proj_q8k
Definition model.h:285
std::vector< block_q8_0 > gate_proj_q8_0
Definition model.h:278
std::vector< block_q6_K > q_proj_q6k
Definition model.h:275
std::vector< float > moe_gate_exps_f32
Definition model.h:284
std::vector< block_q8_K > k_proj_q8k
Definition model.h:285
std::vector< float > moe_down_exps_f32
Definition model.h:284
std::vector< block_q6_K > gate_proj_q6k
Definition model.h:276
std::vector< block_q5_K > q_proj_q5k
Definition model.h:273
std::vector< float > moe_router_f32
Definition model.h:282
std::vector< block_q8_K > gate_proj_q8k
Definition model.h:286
std::vector< block_q5_K > up_proj_q5k
Definition model.h:274
std::vector< float > gate_proj_f32
Definition model.h:269
std::vector< block_q5_K > k_proj_q5k
Definition model.h:273
std::vector< float > o_proj_f32
Definition model.h:268
std::vector< uint16_t > down_proj
Definition model.h:264
std::vector< block_q8_0 > q_proj_q8_0
Definition model.h:277
std::vector< block_q8_0 > k_proj_q8_0
Definition model.h:277
std::vector< uint16_t > up_proj
Definition model.h:263
std::vector< block_q4_K > o_proj_q4k
Definition model.h:270
std::vector< float > q_proj_f32
Definition model.h:268
std::vector< uint16_t > q_proj
Definition model.h:257
std::vector< float > moe_up_exps_f32
Definition model.h:284
std::vector< block_q8_K > q_proj_q8k
Definition model.h:285
std::vector< float > post_attention_layernorm_f32
Definition model.h:267
std::vector< float > down_proj_f32
Definition model.h:269
std::vector< block_q6_K > o_proj_q6k
Definition model.h:275
std::vector< block_q8_0 > down_proj_q8_0
Definition model.h:278
std::vector< block_q8_0 > up_proj_q8_0
Definition model.h:278
std::vector< block_q4_K > q_proj_q4k
Definition model.h:270
std::vector< uint16_t > k_proj
Definition model.h:258
Model configuration structure holding architecture and hyperparameters.
Definition model.h:82
int hidden_size
Definition model.h:83
int vocab_size
Definition model.h:88
int pad_token_id
Definition model.h:97
std::string chat_template_string
Definition model.h:102
std::string pre_tokenizer_type
Definition model.h:101
std::string architecture
Definition model.h:98
std::string model_name
Definition model.h:99
float rms_norm_eps
Definition model.h:90
int num_attention_heads
Definition model.h:85
std::string chat_template_type
Definition model.h:100
bool use_mmap_for_gguf
Definition model.h:104
int intermediate_size
Definition model.h:84
int eos_token_id
Definition model.h:95
int num_cpu_offload_layers
Definition model.h:106
bool enable_memory_efficient_layers
Definition model.h:111
std::string torch_dtype
Definition model.h:93
bool is_gguf_file_loaded
Definition model.h:103
bool use_kvcache_quantization
Definition model.h:105
float rope_theta
Definition model.h:91
int num_experts_used
Definition model.h:108
int num_hidden_layers
Definition model.h:87
bool use_optimized_cuda_kernels
Definition model.h:114
int num_key_value_heads
Definition model.h:86
TokenizerFamily
Definition model.h:116
bool enable_prefill_chunking
Definition model.h:113
int num_experts
Definition model.h:107
int bos_token_id
Definition model.h:94
std::string hidden_act
Definition model.h:92
TokenizerFamily tokenizer_family
Definition model.h:123
int unk_token_id
Definition model.h:96
int max_position_embeddings
Definition model.h:89