Skip to main content

llama.cpp — Core Data Structures

ggml_tensor (ggml.h:660)

Purpose: Fundamental n-dimensional tensor type. Every model weight, activation, and intermediate computation result is represented as a ggml_tensor. Tensors form a lazy compute DAG — building operations (e.g., ggml_mul_mat) creates tensor nodes with op fields; actual computation happens when ggml_graph_compute() executes the graph.

Fields:

FieldTypePurpose
typeenum ggml_typeData type (F32, F16, BF16, Q4_0, Q4_K, Q8_0, IQ series, etc. — 42 types)
bufferggml_backend_buffer*Backend buffer owning this tensor's memory (CPU, CUDA, Metal, etc.)
ne[4]int64_tShape: number of elements per dimension (max 4D)
nb[4]size_tStrides in bytes per dimension. nb[0] = type_size, nb[i] = nb[i-1]*ne[i-1]
openum ggml_opCompute operation (NONE for leaf tensors, MUL_MAT, ADD, RMS_NORM, etc.)
op_params[16]int32_tOperation-specific parameters (e.g., axis for SOFT_MAX, MUL_MAT parameters)
flagsint32_tTensor flags (e.g., DONT_MMAP, NOT_PERSISTENT)
src[GGML_MAX_SRC]ggml_tensor**Input tensors for compute graph node (up to 10 sources)
view_srcggml_tensor*Source tensor for views (shares underlying data)
view_offssize_tByte offset into view_src's data
datavoid*Raw data pointer (CPU or GPU address)
namechar[64]Human-readable tensor name (for debugging)
extravoid*Backend-specific extra data (e.g., CUDA tensor extras)

Key Functions:

FunctionComplexityNotes
ggml_new_tensor()O(1)Allocates tensor metadata from ggml_context arena
ggml_mul_mat()O(1) build / O(mnk) computeCreates lazy matrix multiply node
ggml_graph_compute()O(nodes)Topologically sorts DAG, dispatches to backends
ggml_view_tensor()O(1)Creates a view sharing the same data buffer

Complex Logic: ggml_graph_compute() topologically sorts the DAG, then dispatches each node to the appropriate backend (CPU, CUDA, Metal) via ggml_backend_sched. The scheduler determines which backend should handle each operation based on where the input tensors reside and which backends support the operation. Cross-backend copies are inserted automatically.


ggml_cgraph (ggml-impl.h:329)

Purpose: Compute graph — a directed acyclic graph of tensor operations. Built during forward pass construction, executed by the backend scheduler.

Fields:

FieldTypePurpose
sizeintMaximum number of nodes/leafs
n_nodesintNumber of active compute nodes
n_leafsintNumber of leaf (constant) tensors
nodesggml_tensor**Array of compute nodes (ops that produce output)
gradsggml_tensor**Gradient tensors (training only)
grad_accsggml_tensor**Gradient accumulators (training only)
leafsggml_tensor**Array of leaf tensors (model weights, constants)
use_countsint32_t*Reference counts per tensor (for memory reuse)
visited_hash_setggml_hash_setHash set for cycle detection during graph build
orderenum ggml_cgraph_eval_orderEvaluation order (left-to-right or topological)
uiduint64_tOptional identifier for graph matching

Design: The graph is built lazily — each ggml operation (e.g., ggml_mul_mat(ctx, a, b)) adds a new tensor node and registers its sources. During ggml_graph_compute(), nodes are evaluated in topological order. The visited_hash_set prevents duplicate tensor insertion.


ggml_backend_i (ggml-backend-impl.h:105)

Purpose: Virtual table (vtable) for hardware backend implementations. This is the core extension point for adding new compute hardware to GGML. Each backend (CPU, CUDA, Metal, Vulkan, etc.) implements this interface.

Function Pointers:

FunctionRequiredPurpose
get_nameYesReturn backend name string
freeYesRelease backend resources
set_tensor_asyncNoAsynchronously write tensor data
get_tensor_asyncNoAsynchronously read tensor data
cpy_tensor_asyncNoAsync cross-backend tensor copy
synchronizeNoWait for all pending async operations
graph_plan_createNoCreate reusable graph execution plan
graph_plan_computeNoExecute graph with pre-built plan
graph_computeYesExecute compute graph (async if supported)
event_record / event_waitNoInter-backend synchronization primitives
graph_optimizeNoBackend-specific graph optimization

Related Interfaces:

  • ggml_backend_buffer_type_i (ggml-backend-impl.h:17) — Buffer type vtable (allocation, alignment, is_host)
  • ggml_backend_buffer_i (ggml-backend-impl.h:41) — Buffer vtable (free, get_base, set_tensor, get_tensor)

llama_model (llama-model.h:512)

Purpose: Loaded model state — holds all model weights, hyperparameters, vocabulary, and metadata loaded from a GGUF file.

Key Fields:

FieldTypePurpose
typellm_typeModel type (e.g., LLM_TYPE_8B, LLM_TYPE_70B)
archllm_archArchitecture enum (LLAMA, GPT2, FALCON, MISTRAL, PHI, GEMMA, etc. — 100+ types)
hparamsllama_hparamsModel hyperparameters (dimensions, layers, heads, etc.)
vocabllama_vocabTokenizer vocabulary
tok_embdggml_tensor*Token embedding weight matrix
output_normggml_tensor*Final layer norm weight
outputggml_tensor*Output projection (lm_head) weight
layersvector<llama_layer>Per-layer weights (attention + FFN)
devicesvector<llama_device>List of devices used for this model
gguf_kvunordered_mapRaw GGUF metadata key-value pairs
lorasunordered_setActive LoRA adapters

Key Methods:

MethodPurpose
load_arch()Determine model architecture from GGUF metadata
load_hparams()Parse hyperparameters from GGUF
load_vocab()Load tokenizer vocabulary
load_tensors()Load all tensor weights into backend buffers

llama_hparams (llama-hparams.h:36)

Purpose: Model hyperparameters extracted from GGUF metadata. These define the model's architecture and are read-only after loading.

Key Fields:

FieldTypePurpose
n_embduint32_tEmbedding dimension
n_layeruint32_tNumber of transformer layers
n_expertuint32_tNumber of MoE experts (0 = dense)
n_expert_useduint32_tActive experts per token (MoE)
n_embd_head_k_fulluint32_tKey head dimension (full attention)
n_embd_head_v_fulluint32_tValue head dimension
n_rot_fulluint32_tRoPE dimension (full attention)
n_head_arr[]uint32_t[]Per-layer query head count (up to 512 layers)
n_head_kv_arr[]uint32_t[]Per-layer KV head count (GQA/MQA support)
n_ff_arr[]uint32_t[]Per-layer FFN hidden dimension
f_norm_rms_epsfloatRMS norm epsilon
rope_freq_base_trainfloatRoPE base frequency

Design: Per-layer arrays (n_head_arr, n_head_kv_arr, n_ff_arr) support architectures with non-uniform layer configurations (e.g., DeepSeek, Command-A with varying head counts).


llama_vocab (llama-vocab.h:67)

Purpose: Tokenizer vocabulary — maps between text and token IDs. Supports BPE, SPM, and WPM tokenizer types.

Key Fields:

FieldTypePurpose
token_datastructPer-token data: text, score, attributes
token_bos/eos/eot/unk/pad/nlllama_tokenSpecial token IDs
token_fim_pre/suf/mid/padllama_tokenFill-in-the-Middle tokens

Key Methods:

MethodPurpose
is_eog(id)Check if token is end-of-generation
text_to_token(text)Look up single token by text
token_to_byte(id)Map byte-level token to byte value

llama_batch (llama.h:235)

Purpose: Batch of tokens to process in a single llama_decode() call. Supports multi-sequence and position-specific processing.

Fields:

FieldTypePurpose
n_tokensint32_tNumber of tokens in this batch
tokenllama_token*Token IDs array
embdfloat*Embedding input (alternative to token IDs)
posllama_pos*Position array for each token
n_seq_idint32_t*Number of sequence IDs per token
seq_idllama_seq_id**Sequence ID assignments per token
logitsint8_t*Whether to compute logits for each token

Design: The seq_id field enables multi-request batching — tokens from different concurrent requests share a single batch but are assigned different sequence IDs. The KV cache uses sequence IDs to separate contexts. logits controls which tokens produce output (only the last token needs logits in autoregressive generation).


llama_layer (llama-model.h:213)

Purpose: Per-layer transformer weights. One llama_layer instance per layer in the model.

Key Fields (subset — there are 50+ tensors per layer for all architectures):

FieldTypePurpose
attn_normggml_tensor*Pre-attention layer norm weight
wq/wk/wv/woggml_tensor*Attention Q/K/V/O projection weights
wqkvggml_tensor*Fused QKV projection (some architectures)
ffn_normggml_tensor*Pre-FFN layer norm weight
ffn_up/ffn_gate/ffn_downggml_tensor*FFN up/gate/down projection weights
ffn_gate_exp/ffn_down_expggml_tensor*MoE expert weights
ffn_gate_shexpggml_tensor*Shared expert weight
attn_q_a_norm/attn_kv_a_normggml_tensor*MLA (Multi-head Latent Attention) norms
wq_a/wq_bggml_tensor*DeepSeek-style low-rank Q projection
wkv_a_mqa/wkv_bggml_tensor*DeepSeek MLA compressed KV

Design: The struct is a union of all possible per-layer tensors across 100+ architectures. Most architectures use only a subset. Pointers are nullptr for unused tensors. This avoids virtual dispatch while supporting diverse architectures.


llama_cparams (llama-cparams.h:9)

Purpose: Context parameters — runtime configuration for an inference context (distinct from model hyperparameters).

Key Fields:

FieldTypePurpose
n_ctxuint32_tTotal context window size
n_ctx_sequint32_tPer-sequence context limit
n_batchuint32_tLogical batch size for decode
n_ubatchuint32_tPhysical (micro) batch size
n_seq_maxuint32_tMaximum concurrent sequences
n_threadsint32_tThread count for generation
rope_freq_base/scalefloatRoPE configuration
embeddingsboolEnable embedding mode
flash_attnboolUse Flash Attention kernel
offload_kqvboolOffload KQV operations to GPU
kv_unifiedboolUnified KV cache (shared across sequences)

llama_kv_cells (llama-kv-cells.h:32)

Purpose: Metadata for KV cache cells — tracks which positions are occupied by which sequences. This is the "soft" KV cache state (positions, sequence assignments, shift tracking), separate from the actual key/value tensor data.

Key Fields:

FieldTypePurpose
posvector<llama_pos>Position of each cell (-1 = empty)
extvector<llama_kv_cell_ext>2D position data (for M-RoPE / vision models)
shiftvector<llama_pos>Position shift values (for context extension)
seqvector<bitset>Sequence membership bitset per cell
seq_posmap<llama_seq_id, set>Position sets per sequence
has_shiftboolWhether any cells have pending position shifts
usedbitsetWhich cells are currently in use

Complex Logic: The KV cache uses a cell-based tracking system. Each cell at index i stores its position, which sequences it belongs to (via bitset), and whether it has a pending position shift (for RoPE scaling / context shifting). The seq_pos map provides O(log n) lookup of all positions belonging to a given sequence. When the cache is full, cells are evicted using an LRU policy based on position comparisons.


llama_sampler / llama_sampler_i (include/llama.h)

Purpose: Sampling interface — a composable chain of sampling operations (temperature, top-k, top-p, repetition penalty, etc.). Uses a vtable pattern similar to ggml_backend_i.

Key vtable functions:

FunctionPurpose
nameReturn sampler name
acceptCalled when a token is accepted (for state updates)
applyApply sampling to a token candidate array
resetReset internal state
freeRelease resources

Built-in Samplers: temp, top_k, top_p, min_p, typical_p, penalty (repetition), mirostat, dri, grammar, dist (random selection), infill (token bias), branchefield, xtcd, dry, tail_free, eta_cutoff, epsilon_cutoff

Usage Pattern:

llama_sampler * chain = llama_sampler_chain_init(params);
llama_sampler_chain_add(chain, llama_sampler_init_top_k(40));
llama_sampler_chain_add(chain, llama_sampler_init_top_p(0.95, 1));
llama_sampler_chain_add(chain, llama_sampler_init_temp(0.8));
llama_sampler_chain_add(chain, llama_sampler_init_dist(seed));

llama_token id = llama_sampler_sample(chain, ctx, -1);