Skip to main content

Context Creation

Before running inference, create a context from a loaded model:
llama_model *
Previously loaded model
struct llama_context_params
Context configuration parameters
llama_context *
Returns context pointer, or NULL on failure

Example

Context Parameters

Key Parameters

uint32_t
default:"from model"
Text context window size. Maximum number of tokens the model can attend to. Use 0 to use the model’s training context size.
uint32_t
default:"2048"
Logical maximum batch size for llama_decode(). Controls how many tokens can be processed in a single call.
uint32_t
default:"512"
Physical maximum batch size. The logical batch is split into physical batches of this size for processing.
int32_t
default:"auto"
Number of threads for single-token generation (autoregressive decoding).
int32_t
default:"auto"
Number of threads for prompt processing and batch operations.
After creating a context, query the actual values using llama_n_ctx(), llama_n_batch(), etc., as they may differ from requested values.

The Batch Structure

Creating Batches

Decoding

llama_decode

Process a batch of tokens through the decoder:
llama_context *
Context with memory for KV cache
llama_batch
Batch of tokens to process
int32_t
  • 0: Success
  • 1: No KV slot available (try smaller batch or larger context)
  • 2: Aborted by callback
  • -1: Invalid input batch
  • < -1: Fatal error
llama_decode() requires the context to have memory. For encoder-decoder models, this processes the batch using the decoder.

llama_encode

Process a batch using the encoder (for encoder-decoder models):
int32_t
  • 0: Success
  • < 0: Error (memory state restored)
llama_encode() does not use the KV cache. It stores encoder output internally for later use by decoder’s cross-attention.

Basic Inference Loop

Getting Logits and Embeddings

Logits

Embeddings

Enable embeddings by setting ctx_params.embeddings = true during context creation.

Memory Management (KV Cache)

The KV cache stores key-value pairs for efficient attention computation:

Sequence Operations

Parallel Decoding Example

State Persistence

Save and restore context state:

Thread Control

Synchronization

This is automatically called when getting logits/embeddings. Explicit calls are rarely needed.

Cleanup

Always free contexts before freeing the associated model.

Complete Inference Example

Next Steps

Sampling

Learn about token sampling strategies

libllama Overview

Return to API overview