Documentation
¶
Overview ¶
Package llama provides Go bindings for llama.cpp without requiring cgo. It uses purego to dynamically load the llama.cpp shared library at runtime.
Index ¶
- Variables
- func Init(libraryPath string) error
- func Shutdown()
- type BatchData
- type ChatMessage
- type Context
- func (c *Context) ClearKVCache()
- func (c *Context) Close()
- func (c *Context) ContextSize() uint32
- func (c *Context) Decode(tokens []LlamaToken, pos int32) error
- func (c *Context) Embedding(text string) ([]float32, error)
- func (c *Context) Generate(prompt string, opts GenerateOptions) (string, error)
- func (c *Context) GetEmbeddings() []float32
- func (c *Context) GetLogits() []float32
- func (c *Context) GetLogitsIth(i int32) []float32
- func (c *Context) Model() *Model
- func (c *Context) PrintTimings()
- func (c *Context) RemoveKVCache(seqID int32, p0, p1 int32) bool
- func (c *Context) ResetTimings()
- func (c *Context) Synchronize()
- type ContextOptions
- type GGMLType
- type GenerateOptions
- type LlamaAttentionType
- type LlamaBatch
- type LlamaChatMessage
- type LlamaContext
- type LlamaContextParams
- type LlamaContextType
- type LlamaFlashAttnType
- type LlamaLazyMode
- type LlamaLoadMode
- type LlamaModel
- type LlamaModelParams
- type LlamaPoolingType
- type LlamaPos
- type LlamaRopeScalingType
- type LlamaSampler
- type LlamaSamplerChainParams
- type LlamaSeqID
- type LlamaSplitMode
- type LlamaToken
- type LlamaTokenData
- type LlamaTokenDataArray
- type LlamaVocab
- type Model
- func (m *Model) ApplyChatTemplate(messages []ChatMessage, addAssistant bool) (string, error)
- func (m *Model) BOS() LlamaToken
- func (m *Model) Close()
- func (m *Model) Detokenize(tokens []LlamaToken) string
- func (m *Model) EOS() LlamaToken
- func (m *Model) EmbeddingSize() int32
- func (m *Model) IsEOG(token LlamaToken) bool
- func (m *Model) NewContext(opts ContextOptions) (*Context, error)
- func (m *Model) TokenToPiece(token LlamaToken) string
- func (m *Model) Tokenize(text string, addBOS bool, special bool) ([]LlamaToken, error)
- func (m *Model) VocabSize() int32
- type ModelOptions
- type Sampler
- type SamplingParams
Constants ¶
This section is empty.
Variables ¶
var ( ErrModelLoad = errors.New("failed to load model") ErrContextInit = errors.New("failed to initialize context") ErrTokenize = errors.New("tokenization failed") ErrDecode = errors.New("decode failed") ErrNotInitialized = errors.New("llama library not initialized - call Init() first") )
Functions ¶
Types ¶
type BatchData ¶
type BatchData struct {
Batch LlamaBatch
Tokens []LlamaToken
Pos []LlamaPos
NSeqID []int32
SeqIDData []LlamaSeqID
SeqIDPtrs []uintptr
Logits []int8
}
BatchData holds the underlying data for a batch to prevent GC collection
func BatchGetOne ¶
func BatchGetOne(tokens []LlamaToken, pos0 LlamaPos, seqID LlamaSeqID) *BatchData
BatchGetOne creates a batch for a single sequence of tokens. Returns BatchData which must be kept alive during the C call. Panics if tokens is empty.
type ChatMessage ¶
ChatMessage represents a role/content pair for ApplyChatTemplate.
type Context ¶
type Context struct {
// contains filtered or unexported fields
}
Context represents an inference context
func (*Context) ClearKVCache ¶
func (c *Context) ClearKVCache()
ClearKVCache clears the KV cache (memory) for this context.
func (*Context) ContextSize ¶
ContextSize returns the context window size
func (*Context) Decode ¶
func (c *Context) Decode(tokens []LlamaToken, pos int32) error
Decode processes a batch of tokens through the model
func (*Context) Generate ¶
func (c *Context) Generate(prompt string, opts GenerateOptions) (string, error)
Generate generates text from a prompt
func (*Context) GetEmbeddings ¶
GetEmbeddings returns a copy of the embeddings (requires embeddings mode). The returned slice is Go-owned and safe to retain across Decode calls.
func (*Context) GetLogits ¶
GetLogits returns a copy of the logits for the last token. The returned slice is Go-owned and safe to retain across Decode calls.
func (*Context) GetLogitsIth ¶
GetLogitsIth returns a copy of the logits for token at index i. The returned slice is Go-owned and safe to retain across Decode calls.
func (*Context) PrintTimings ¶
func (c *Context) PrintTimings()
PrintTimings prints timing information
func (*Context) RemoveKVCache ¶
RemoveKVCache removes KV cache entries for a sequence in position range [p0, p1) NOTE: This is a no-op in current llama.cpp versions where KV cache is managed internally
func (*Context) Synchronize ¶
func (c *Context) Synchronize()
Synchronize waits for all computations to complete
type ContextOptions ¶
type ContextOptions struct {
ContextSize uint32 // Context window size (0 = model default)
BatchSize uint32 // Batch size for prompt processing
Threads int32 // Number of threads (0 = auto)
ThreadsBatch int32 // Number of threads for batch processing (0 = same as Threads)
Embeddings bool // Enable embeddings mode
FlashAttention bool // Enable flash attention (if available)
}
ContextOptions contains options for creating a context
func DefaultContextOptions ¶
func DefaultContextOptions() ContextOptions
DefaultContextOptions returns default context options
type GenerateOptions ¶
type GenerateOptions struct {
// MaxTokens is the maximum number of tokens to generate
MaxTokens int
// Sampling parameters
Sampling SamplingParams
// StopTokens are tokens that stop generation
StopTokens []LlamaToken
// Callback is called for each generated token. Return false to stop.
Callback func(token LlamaToken, text string) bool
}
GenerateOptions contains options for text generation
func DefaultGenerateOptions ¶
func DefaultGenerateOptions() GenerateOptions
DefaultGenerateOptions returns default generation options
type LlamaAttentionType ¶
type LlamaAttentionType int32
const ( LlamaAttentionTypeUnspecified LlamaAttentionType = -1 LlamaAttentionTypeCausal LlamaAttentionType = 0 LlamaAttentionTypeNonCausal LlamaAttentionType = 1 )
type LlamaBatch ¶
type LlamaBatch struct {
NTokens int32 // n_tokens
Token uintptr // llama_token *
Embd uintptr // float *
Pos uintptr // llama_pos *
NSeqID uintptr // int32_t *
SeqID uintptr // llama_seq_id **
Logits uintptr // int8_t *
// contains filtered or unexported fields
}
LlamaBatch represents a batch of tokens for processing Must match C struct llama_batch layout exactly
type LlamaChatMessage ¶
LlamaChatMessage represents a chat message.
type LlamaContextParams ¶
type LlamaContextParams struct {
NCtx uint32
NBatch uint32
NUBatch uint32
NSeqMax uint32
NRsSeq uint32
NOutputsMax uint32
NOutputsMaxPerSeq uint32
NThreads int32
NThreadsBatch int32
CtxType LlamaContextType
RopeScalingType LlamaRopeScalingType
PoolingType LlamaPoolingType
AttentionType LlamaAttentionType
FlashAttnType LlamaFlashAttnType
RopeFreqBase float32
RopeFreqScale float32
YarnExtFactor float32
YarnAttnFactor float32
YarnBetaFast float32
YarnBetaSlow float32
YarnOrigCtx uint32
DefragThold float32
CbEval uintptr // ggml_backend_sched_eval_callback
CbEvalUserData uintptr // void *
TypeK GGMLType
TypeV GGMLType
MoeCacheSize uintptr // size_t
AbortCallback uintptr // ggml_abort_callback
AbortCallbackData uintptr // void *
Embeddings bool
OffloadKQV bool
NoPerf bool
OpOffload bool
SwaFull bool
KvUnified bool
Samplers uintptr // struct llama_sampler_seq_config *
NSamplers uint64 // size_t
CtxOther uintptr // struct llama_context *
// contains filtered or unexported fields
}
LlamaContextParams contains parameters for context creation Must match C struct llama_context_params layout exactly
func DefaultContextParams ¶
func DefaultContextParams() LlamaContextParams
DefaultContextParams returns default context parameters matching llama_context_default_params()
type LlamaContextType ¶
type LlamaContextType int32
const ( LlamaContextTypeDefault LlamaContextType = 0 LlamaContextTypeMTP LlamaContextType = 1 )
type LlamaFlashAttnType ¶
type LlamaFlashAttnType int32
const ( LlamaFlashAttnTypeAuto LlamaFlashAttnType = -1 LlamaFlashAttnTypeDisabled LlamaFlashAttnType = 0 LlamaFlashAttnTypeEnabled LlamaFlashAttnType = 1 )
type LlamaLazyMode ¶
type LlamaLazyMode int32
const ( LlamaLazyModeOff LlamaLazyMode = 0 LlamaLazyModeAuto LlamaLazyMode = 1 LlamaLazyModeOn LlamaLazyMode = 2 )
type LlamaLoadMode ¶
type LlamaLoadMode int32
const ( LlamaLoadModeAuto LlamaLoadMode = -1 LlamaLoadModeNone LlamaLoadMode = 0 LlamaLoadModeMmap LlamaLoadMode = 1 LlamaLoadModeMlock LlamaLoadMode = 2 LlamaLoadModeMmapMlock LlamaLoadMode = 3 LlamaLoadModeDirectIO LlamaLoadMode = 4 )
type LlamaModelParams ¶
type LlamaModelParams struct {
Devices uintptr // ggml_backend_dev_t *
TensorBuftOverrides uintptr // const struct llama_model_tensor_buft_override *
NGPULayers int32
SplitMode LlamaSplitMode
LoadMode LlamaLoadMode
LazyMode LlamaLazyMode
MainGPU int32
TensorSplit uintptr // const float *
ProgressCallback uintptr // llama_progress_callback
ProgressCallbackUserData uintptr // void *
KVOverrides uintptr // const struct llama_model_kv_override *
VocabOnly bool
CheckTensors bool
UseExtraBufts bool
NoHost bool
NoAlloc bool
LoadMTP bool
// contains filtered or unexported fields
}
LlamaModelParams contains parameters for model loading This struct must match C struct llama_model_params layout exactly
func DefaultModelParams ¶
func DefaultModelParams() LlamaModelParams
type LlamaPoolingType ¶
type LlamaPoolingType int32
const ( LlamaPoolingTypeUnspecified LlamaPoolingType = -1 LlamaPoolingTypeNone LlamaPoolingType = 0 LlamaPoolingTypeMean LlamaPoolingType = 1 LlamaPoolingTypeCLS LlamaPoolingType = 2 LlamaPoolingTypeLast LlamaPoolingType = 3 LlamaPoolingTypeRank LlamaPoolingType = 4 )
type LlamaRopeScalingType ¶
type LlamaRopeScalingType int32
const ( LlamaRopeScalingTypeUnspecified LlamaRopeScalingType = -1 LlamaRopeScalingTypeNone LlamaRopeScalingType = 0 LlamaRopeScalingTypeLinear LlamaRopeScalingType = 1 LlamaRopeScalingTypeYarn LlamaRopeScalingType = 2 LlamaRopeScalingTypeLongrope LlamaRopeScalingType = 3 )
type LlamaSamplerChainParams ¶
type LlamaSamplerChainParams struct {
NoPerf bool
}
LlamaSamplerChainParams contains parameters for sampler chain
func DefaultSamplerChainParams ¶
func DefaultSamplerChainParams() LlamaSamplerChainParams
DefaultSamplerChainParams returns default sampler chain parameters
type LlamaSplitMode ¶
type LlamaSplitMode int32
Enum types
const ( LlamaSplitModeNone LlamaSplitMode = 0 // single GPU LlamaSplitModeLayer LlamaSplitMode = 1 // split layers and KV across GPUs LlamaSplitModeRow LlamaSplitMode = 2 // split rows across GPUs LlamaSplitModeTensor LlamaSplitMode = 3 )
type LlamaTokenData ¶
type LlamaTokenData struct {
ID LlamaToken
Logit float32
P float32
}
LlamaTokenData represents token data for sampling
type LlamaTokenDataArray ¶
type LlamaTokenDataArray struct {
Data uintptr // llama_token_data *
Size uint64 // size_t
Selected int64
Sorted bool
}
LlamaTokenDataArray represents an array of token data for sampling
type Model ¶
type Model struct {
// contains filtered or unexported fields
}
Model represents a loaded llama model
func LoadModel ¶
func LoadModel(path string, opts ModelOptions) (*Model, error)
LoadModel loads a model from a file
func (*Model) ApplyChatTemplate ¶
func (m *Model) ApplyChatTemplate(messages []ChatMessage, addAssistant bool) (string, error)
ApplyChatTemplate formats messages using the model's embedded GGUF chat template (falling back to ChatML if none is embedded or the template isn't supported).
func (*Model) Detokenize ¶
func (m *Model) Detokenize(tokens []LlamaToken) string
Detokenize converts tokens back to text
func (*Model) EmbeddingSize ¶
EmbeddingSize returns the embedding dimension
func (*Model) IsEOG ¶
func (m *Model) IsEOG(token LlamaToken) bool
func (*Model) NewContext ¶
func (m *Model) NewContext(opts ContextOptions) (*Context, error)
NewContext creates a new inference context from a model
func (*Model) TokenToPiece ¶
func (m *Model) TokenToPiece(token LlamaToken) string
TokenToPiece converts a single token to its text representation
type ModelOptions ¶
type ModelOptions struct {
NGPULayers int32 // Number of layers to offload to GPU (0 = CPU only)
UseMmap bool // Use memory mapping for model loading
UseMlock bool // Lock model in memory
VocabOnly bool // Only load vocabulary
MainGPU int32 // Main GPU to use
}
ModelOptions contains options for loading a model
func DefaultModelOptions ¶
func DefaultModelOptions() ModelOptions
DefaultModelOptions returns default model loading options
type Sampler ¶
type Sampler struct {
// contains filtered or unexported fields
}
Sampler wraps llama.cpp's sampler chain
func NewSampler ¶
func NewSampler(params SamplingParams) *Sampler
NewSampler creates a new sampler with the given parameters
func NewSamplerWithVocab ¶
func NewSamplerWithVocab(params SamplingParams, vocab LlamaVocab) *Sampler
NewSamplerWithVocab creates a new sampler with the given parameters and vocabulary
func (*Sampler) Accept ¶
func (s *Sampler) Accept(token LlamaToken)
Accept tells the sampler that a token was accepted (for penalties)
type SamplingParams ¶
type SamplingParams struct {
// Temperature for sampling (1.0 = neutral, <1.0 = more deterministic, >1.0 = more random)
Temperature float32
// TopK limits sampling to the K most likely tokens (0 = disabled)
TopK int32
// TopP (nucleus sampling) limits to tokens with cumulative probability >= p
TopP float32
// MinP filters out tokens with probability < p * max_prob
MinP float32
// TypicalP for locally typical sampling
TypicalP float32
// RepeatPenalty penalizes repeated tokens
RepeatPenalty float32
// FrequencyPenalty penalizes based on frequency
FrequencyPenalty float32
// PresencePenalty penalizes based on presence
PresencePenalty float32
// PenaltyLastN number of tokens to consider for repetition penalty
PenaltyLastN int32
// Seed for random sampling (0 = random seed)
Seed uint32
// Greedy uses greedy sampling (ignores temperature and other params)
Greedy bool
// Grammar is an optional GBNF grammar string to constrain token generation
Grammar string
// GrammarRoot is the root rule name in Grammar (defaults to "root" if empty)
GrammarRoot string
}
SamplingParams contains parameters for text generation sampling
func DefaultSamplingParams ¶
func DefaultSamplingParams() SamplingParams
DefaultSamplingParams returns sensible default sampling parameters
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
examples
|
|
|
cpu
command
Example: CPU-only inference (no GPU)
|
Example: CPU-only inference (no GPU) |
|
cuda
command
Example: NVIDIA CUDA GPU acceleration
|
Example: NVIDIA CUDA GPU acceleration |
|
embeddings
command
Example demonstrating embeddings generation with go-llama-pure
|
Example demonstrating embeddings generation with go-llama-pure |
|
metal
command
Example: Apple Silicon with Metal GPU acceleration
|
Example: Apple Silicon with Metal GPU acceleration |
|
simple
command
Example demonstrating basic usage of go-llama-pure
|
Example demonstrating basic usage of go-llama-pure |